regop.isa revision 6462:209c3818a863
1// Copyright (c) 2007-2008 The Hewlett-Packard Development Company
2// All rights reserved.
3//
4// Redistribution and use of this software in source and binary forms,
5// with or without modification, are permitted provided that the
6// following conditions are met:
7//
8// The software must be used only for Non-Commercial Use which means any
9// use which is NOT directed to receiving any direct monetary
10// compensation for, or commercial advantage from such use.  Illustrative
11// examples of non-commercial use are academic research, personal study,
12// teaching, education and corporate research & development.
13// Illustrative examples of commercial use are distributing products for
14// commercial advantage and providing services using the software for
15// commercial advantage.
16//
17// If you wish to use this software or functionality therein that may be
18// covered by patents for commercial use, please contact:
19//     Director of Intellectual Property Licensing
20//     Office of Strategy and Technology
21//     Hewlett-Packard Company
22//     1501 Page Mill Road
23//     Palo Alto, California  94304
24//
25// Redistributions of source code must retain the above copyright notice,
26// this list of conditions and the following disclaimer.  Redistributions
27// in binary form must reproduce the above copyright notice, this list of
28// conditions and the following disclaimer in the documentation and/or
29// other materials provided with the distribution.  Neither the name of
30// the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
31// contributors may be used to endorse or promote products derived from
32// this software without specific prior written permission.  No right of
33// sublicense is granted herewith.  Derivatives of the software and
34// output created using the software may be prepared, but only for
35// Non-Commercial Uses.  Derivatives of the software may be shared with
36// others provided: (i) the others agree to abide by the list of
37// conditions herein which includes the Non-Commercial Use restrictions;
38// and (ii) such Derivatives of the software include the above copyright
39// notice to acknowledge the contribution from this software where
40// applicable, this list of conditions and the disclaimer below.
41//
42// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
43// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
44// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
45// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
46// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
47// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
48// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
49// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
50// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
51// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
52// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
53//
54// Authors: Gabe Black
55
56//////////////////////////////////////////////////////////////////////////
57//
58// RegOp Microop templates
59//
60//////////////////////////////////////////////////////////////////////////
61
62def template MicroRegOpExecute {{
63        Fault %(class_name)s::execute(%(CPU_exec_context)s *xc,
64                Trace::InstRecord *traceData) const
65        {
66            Fault fault = NoFault;
67
68            DPRINTF(X86, "The data size is %d\n", dataSize);
69            %(op_decl)s;
70            %(op_rd)s;
71
72            if(%(cond_check)s)
73            {
74                %(code)s;
75                %(flag_code)s;
76            }
77            else
78            {
79                %(else_code)s;
80            }
81
82            //Write the resulting state to the execution context
83            if(fault == NoFault)
84            {
85                %(op_wb)s;
86            }
87            return fault;
88        }
89}};
90
91def template MicroRegOpImmExecute {{
92        Fault %(class_name)s::execute(%(CPU_exec_context)s *xc,
93                Trace::InstRecord *traceData) const
94        {
95            Fault fault = NoFault;
96
97            %(op_decl)s;
98            %(op_rd)s;
99
100            if(%(cond_check)s)
101            {
102                %(code)s;
103                %(flag_code)s;
104            }
105            else
106            {
107                %(else_code)s;
108            }
109
110            //Write the resulting state to the execution context
111            if(fault == NoFault)
112            {
113                %(op_wb)s;
114            }
115            return fault;
116        }
117}};
118
119def template MicroRegOpDeclare {{
120    class %(class_name)s : public %(base_class)s
121    {
122      protected:
123        void buildMe();
124
125      public:
126        %(class_name)s(ExtMachInst _machInst,
127                const char * instMnem,
128                bool isMicro, bool isDelayed, bool isFirst, bool isLast,
129                InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
130                uint8_t _dataSize, uint16_t _ext);
131
132        %(class_name)s(ExtMachInst _machInst,
133                const char * instMnem,
134                InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
135                uint8_t _dataSize, uint16_t _ext);
136
137        %(BasicExecDeclare)s
138    };
139}};
140
141def template MicroRegOpImmDeclare {{
142
143    class %(class_name)s : public %(base_class)s
144    {
145      protected:
146        void buildMe();
147
148      public:
149        %(class_name)s(ExtMachInst _machInst,
150                const char * instMnem,
151                bool isMicro, bool isDelayed, bool isFirst, bool isLast,
152                InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
153                uint8_t _dataSize, uint16_t _ext);
154
155        %(class_name)s(ExtMachInst _machInst,
156                const char * instMnem,
157                InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
158                uint8_t _dataSize, uint16_t _ext);
159
160        %(BasicExecDeclare)s
161    };
162}};
163
164def template MicroRegOpConstructor {{
165
166    inline void %(class_name)s::buildMe()
167    {
168        %(constructor)s;
169    }
170
171    inline %(class_name)s::%(class_name)s(
172            ExtMachInst machInst, const char * instMnem,
173            InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
174            uint8_t _dataSize, uint16_t _ext) :
175        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
176                false, false, false, false,
177                _src1, _src2, _dest, _dataSize, _ext,
178                %(op_class)s)
179    {
180        buildMe();
181    }
182
183    inline %(class_name)s::%(class_name)s(
184            ExtMachInst machInst, const char * instMnem,
185            bool isMicro, bool isDelayed, bool isFirst, bool isLast,
186            InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
187            uint8_t _dataSize, uint16_t _ext) :
188        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
189                isMicro, isDelayed, isFirst, isLast,
190                _src1, _src2, _dest, _dataSize, _ext,
191                %(op_class)s)
192    {
193        buildMe();
194    }
195}};
196
197def template MicroRegOpImmConstructor {{
198
199    inline void %(class_name)s::buildMe()
200    {
201        %(constructor)s;
202    }
203
204    inline %(class_name)s::%(class_name)s(
205            ExtMachInst machInst, const char * instMnem,
206            InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
207            uint8_t _dataSize, uint16_t _ext) :
208        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
209                false, false, false, false,
210                _src1, _imm8, _dest, _dataSize, _ext,
211                %(op_class)s)
212    {
213        buildMe();
214    }
215
216    inline %(class_name)s::%(class_name)s(
217            ExtMachInst machInst, const char * instMnem,
218            bool isMicro, bool isDelayed, bool isFirst, bool isLast,
219            InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
220            uint8_t _dataSize, uint16_t _ext) :
221        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
222                isMicro, isDelayed, isFirst, isLast,
223                _src1, _imm8, _dest, _dataSize, _ext,
224                %(op_class)s)
225    {
226        buildMe();
227    }
228}};
229
230output header {{
231    void
232    divide(uint64_t dividend, uint64_t divisor,
233            uint64_t &quotient, uint64_t &remainder);
234
235    enum SegmentSelectorCheck {
236      SegNoCheck, SegCSCheck, SegCallGateCheck, SegIntGateCheck,
237      SegSoftIntGateCheck, SegSSCheck, SegIretCheck, SegIntCSCheck,
238      SegTRCheck, SegTSSCheck, SegInGDTCheck, SegLDTCheck
239    };
240
241    enum LongModeDescriptorType {
242        LDT64 = 2,
243        AvailableTSS64 = 9,
244        BusyTSS64 = 0xb,
245        CallGate64 = 0xc,
246        IntGate64 = 0xe,
247        TrapGate64 = 0xf
248    };
249}};
250
251output decoder {{
252    void
253    divide(uint64_t dividend, uint64_t divisor,
254            uint64_t &quotient, uint64_t &remainder)
255    {
256        //Check for divide by zero.
257        if (divisor == 0)
258            panic("Divide by zero!\\n");
259        //If the divisor is bigger than the dividend, don't do anything.
260        if (divisor <= dividend) {
261            //Shift the divisor so it's msb lines up with the dividend.
262            int dividendMsb = findMsbSet(dividend);
263            int divisorMsb = findMsbSet(divisor);
264            int shift = dividendMsb - divisorMsb;
265            divisor <<= shift;
266            //Compute what we'll add to the quotient if the divisor isn't
267            //now larger than the dividend.
268            uint64_t quotientBit = 1;
269            quotientBit <<= shift;
270            //If we need to step back a bit (no pun intended) because the
271            //divisor got too to large, do that here. This is the "or two"
272            //part of one or two bit division.
273            if (divisor > dividend) {
274                quotientBit >>= 1;
275                divisor >>= 1;
276            }
277            //Decrement the remainder and increment the quotient.
278            quotient += quotientBit;
279            remainder -= divisor;
280        }
281    }
282}};
283
284let {{
285    # Make these empty strings so that concatenating onto
286    # them will always work.
287    header_output = ""
288    decoder_output = ""
289    exec_output = ""
290
291    immTemplates = (
292            MicroRegOpImmDeclare,
293            MicroRegOpImmConstructor,
294            MicroRegOpImmExecute)
295
296    regTemplates = (
297            MicroRegOpDeclare,
298            MicroRegOpConstructor,
299            MicroRegOpExecute)
300
301    class RegOpMeta(type):
302        def buildCppClasses(self, name, Name, suffix, \
303                code, flag_code, cond_check, else_code):
304
305            # Globals to stick the output in
306            global header_output
307            global decoder_output
308            global exec_output
309
310            # Stick all the code together so it can be searched at once
311            allCode = "|".join((code, flag_code, cond_check, else_code))
312
313            # If op2 is used anywhere, make register and immediate versions
314            # of this code.
315            matcher = re.compile("(?<!\\w)(?P<prefix>s?)op2(?P<typeQual>\\.\\w+)?")
316            match = matcher.search(allCode)
317            if match:
318                typeQual = ""
319                if match.group("typeQual"):
320                    typeQual = match.group("typeQual")
321                src2_name = "%spsrc2%s" % (match.group("prefix"), typeQual)
322                self.buildCppClasses(name, Name, suffix,
323                        matcher.sub(src2_name, code),
324                        matcher.sub(src2_name, flag_code),
325                        matcher.sub(src2_name, cond_check),
326                        matcher.sub(src2_name, else_code))
327                self.buildCppClasses(name + "i", Name, suffix + "Imm",
328                        matcher.sub("imm8", code),
329                        matcher.sub("imm8", flag_code),
330                        matcher.sub("imm8", cond_check),
331                        matcher.sub("imm8", else_code))
332                return
333
334            # If there's something optional to do with flags, generate
335            # a version without it and fix up this version to use it.
336            if flag_code != "" or cond_check != "true":
337                self.buildCppClasses(name, Name, suffix,
338                        code, "", "true", else_code)
339                suffix = "Flags" + suffix
340
341            # If psrc1 or psrc2 is used, we need to actually insert code to
342            # compute it.
343            matcher = re.compile("(?<!\w)psrc1(?!\w)")
344            if matcher.search(allCode):
345                code = "uint64_t psrc1 = pick(SrcReg1, 0, dataSize);" + code
346            matcher = re.compile("(?<!\w)psrc2(?!\w)")
347            if matcher.search(allCode):
348                code = "uint64_t psrc2 = pick(SrcReg2, 1, dataSize);" + code
349            # Also make available versions which do sign extension
350            matcher = re.compile("(?<!\w)spsrc1(?!\w)")
351            if matcher.search(allCode):
352                code = "int64_t spsrc1 = signedPick(SrcReg1, 0, dataSize);" + code
353            matcher = re.compile("(?<!\w)spsrc2(?!\w)")
354            if matcher.search(allCode):
355                code = "int64_t spsrc2 = signedPick(SrcReg2, 1, dataSize);" + code
356
357            base = "X86ISA::RegOp"
358
359            # If imm8 shows up in the code, use the immediate templates, if
360            # not, hopefully the register ones will be correct.
361            templates = regTemplates
362            matcher = re.compile("(?<!\w)imm8(?!\w)")
363            if matcher.search(allCode):
364                base += "Imm"
365                templates = immTemplates
366
367            # Get everything ready for the substitution
368            iop = InstObjParams(name, Name + suffix, base,
369                    {"code" : code,
370                     "flag_code" : flag_code,
371                     "cond_check" : cond_check,
372                     "else_code" : else_code})
373
374            # Generate the actual code (finally!)
375            header_output += templates[0].subst(iop)
376            decoder_output += templates[1].subst(iop)
377            exec_output += templates[2].subst(iop)
378
379
380        def __new__(mcls, Name, bases, dict):
381            abstract = False
382            name = Name.lower()
383            if "abstract" in dict:
384                abstract = dict['abstract']
385                del dict['abstract']
386
387            cls = super(RegOpMeta, mcls).__new__(mcls, Name, bases, dict)
388            if not abstract:
389                cls.className = Name
390                cls.base_mnemonic = name
391                code = cls.code
392                flag_code = cls.flag_code
393                cond_check = cls.cond_check
394                else_code = cls.else_code
395
396                # Set up the C++ classes
397                mcls.buildCppClasses(cls, name, Name, "",
398                        code, flag_code, cond_check, else_code)
399
400                # Hook into the microassembler dict
401                global microopClasses
402                microopClasses[name] = cls
403
404                allCode = "|".join((code, flag_code, cond_check, else_code))
405
406                # If op2 is used anywhere, make register and immediate versions
407                # of this code.
408                matcher = re.compile("op2(?P<typeQual>\\.\\w+)?")
409                if matcher.search(allCode):
410                    microopClasses[name + 'i'] = cls
411            return cls
412
413
414    class RegOp(X86Microop):
415        __metaclass__ = RegOpMeta
416        # This class itself doesn't act as a microop
417        abstract = True
418
419        # Default template parameter values
420        flag_code = ""
421        cond_check = "true"
422        else_code = ";"
423
424        def __init__(self, dest, src1, op2, flags = None, dataSize = "env.dataSize"):
425            self.dest = dest
426            self.src1 = src1
427            self.op2 = op2
428            self.flags = flags
429            self.dataSize = dataSize
430            if flags is None:
431                self.ext = 0
432            else:
433                if not isinstance(flags, (list, tuple)):
434                    raise Exception, "flags must be a list or tuple of flags"
435                self.ext = " | ".join(flags)
436                self.className += "Flags"
437
438        def getAllocator(self, *microFlags):
439            className = self.className
440            if self.mnemonic == self.base_mnemonic + 'i':
441                className += "Imm"
442            allocator = '''new %(class_name)s(machInst, macrocodeBlock
443                    %(flags)s, %(src1)s, %(op2)s, %(dest)s,
444                    %(dataSize)s, %(ext)s)''' % {
445                "class_name" : className,
446                "flags" : self.microFlagsText(microFlags),
447                "src1" : self.src1, "op2" : self.op2,
448                "dest" : self.dest,
449                "dataSize" : self.dataSize,
450                "ext" : self.ext}
451            return allocator
452
453    class LogicRegOp(RegOp):
454        abstract = True
455        flag_code = '''
456            //Don't have genFlags handle the OF or CF bits
457            uint64_t mask = CFBit | ECFBit | OFBit;
458            ccFlagBits = genFlags(ccFlagBits, ext & ~mask, DestReg, psrc1, op2);
459            //If a logic microop wants to set these, it wants to set them to 0.
460            ccFlagBits &= ~(CFBit & ext);
461            ccFlagBits &= ~(ECFBit & ext);
462            ccFlagBits &= ~(OFBit & ext);
463        '''
464
465    class FlagRegOp(RegOp):
466        abstract = True
467        flag_code = \
468            "ccFlagBits = genFlags(ccFlagBits, ext, DestReg, psrc1, op2);"
469
470    class SubRegOp(RegOp):
471        abstract = True
472        flag_code = \
473            "ccFlagBits = genFlags(ccFlagBits, ext, DestReg, psrc1, ~op2, true);"
474
475    class CondRegOp(RegOp):
476        abstract = True
477        cond_check = "checkCondition(ccFlagBits, ext)"
478
479    class RdRegOp(RegOp):
480        abstract = True
481        def __init__(self, dest, src1=None, dataSize="env.dataSize"):
482            if not src1:
483                src1 = dest
484            super(RdRegOp, self).__init__(dest, src1, \
485                    "InstRegIndex(NUM_INTREGS)", None, dataSize)
486
487    class WrRegOp(RegOp):
488        abstract = True
489        def __init__(self, src1, src2, flags=None, dataSize="env.dataSize"):
490            super(WrRegOp, self).__init__("InstRegIndex(NUM_INTREGS)", \
491                    src1, src2, flags, dataSize)
492
493    class Add(FlagRegOp):
494        code = 'DestReg = merge(DestReg, psrc1 + op2, dataSize);'
495
496    class Or(LogicRegOp):
497        code = 'DestReg = merge(DestReg, psrc1 | op2, dataSize);'
498
499    class Adc(FlagRegOp):
500        code = '''
501            CCFlagBits flags = ccFlagBits;
502            DestReg = merge(DestReg, psrc1 + op2 + flags.cf, dataSize);
503            '''
504
505    class Sbb(SubRegOp):
506        code = '''
507            CCFlagBits flags = ccFlagBits;
508            DestReg = merge(DestReg, psrc1 - op2 - flags.cf, dataSize);
509            '''
510
511    class And(LogicRegOp):
512        code = 'DestReg = merge(DestReg, psrc1 & op2, dataSize)'
513
514    class Sub(SubRegOp):
515        code = 'DestReg = merge(DestReg, psrc1 - op2, dataSize)'
516
517    class Xor(LogicRegOp):
518        code = 'DestReg = merge(DestReg, psrc1 ^ op2, dataSize)'
519
520    class Mul1s(WrRegOp):
521        code = '''
522            ProdLow = psrc1 * op2;
523            int halfSize = (dataSize * 8) / 2;
524            uint64_t shifter = (1ULL << halfSize);
525            uint64_t hiResult;
526            uint64_t psrc1_h = psrc1 / shifter;
527            uint64_t psrc1_l = psrc1 & mask(halfSize);
528            uint64_t psrc2_h = (op2 / shifter) & mask(halfSize);
529            uint64_t psrc2_l = op2 & mask(halfSize);
530            hiResult = ((psrc1_l * psrc2_h + psrc1_h * psrc2_l +
531                        ((psrc1_l * psrc2_l) / shifter)) /shifter) +
532                       psrc1_h * psrc2_h;
533            if (bits(psrc1, dataSize * 8 - 1))
534                hiResult -= op2;
535            if (bits(op2, dataSize * 8 - 1))
536                hiResult -= psrc1;
537            ProdHi = hiResult;
538            '''
539
540    class Mul1u(WrRegOp):
541        code = '''
542            ProdLow = psrc1 * op2;
543            int halfSize = (dataSize * 8) / 2;
544            uint64_t shifter = (1ULL << halfSize);
545            uint64_t psrc1_h = psrc1 / shifter;
546            uint64_t psrc1_l = psrc1 & mask(halfSize);
547            uint64_t psrc2_h = (op2 / shifter) & mask(halfSize);
548            uint64_t psrc2_l = op2 & mask(halfSize);
549            ProdHi = ((psrc1_l * psrc2_h + psrc1_h * psrc2_l +
550                      ((psrc1_l * psrc2_l) / shifter)) / shifter) +
551                     psrc1_h * psrc2_h;
552            '''
553
554    class Mulel(RdRegOp):
555        code = 'DestReg = merge(SrcReg1, ProdLow, dataSize);'
556
557    class Muleh(RdRegOp):
558        def __init__(self, dest, src1=None, flags=None, dataSize="env.dataSize"):
559            if not src1:
560                src1 = dest
561            super(RdRegOp, self).__init__(dest, src1, \
562                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
563        code = 'DestReg = merge(SrcReg1, ProdHi, dataSize);'
564        flag_code = '''
565            if (ProdHi)
566                ccFlagBits = ccFlagBits | (ext & (CFBit | OFBit | ECFBit));
567            else
568                ccFlagBits = ccFlagBits & ~(ext & (CFBit | OFBit | ECFBit));
569        '''
570
571    # One or two bit divide
572    class Div1(WrRegOp):
573        code = '''
574            //These are temporaries so that modifying them later won't make
575            //the ISA parser think they're also sources.
576            uint64_t quotient = 0;
577            uint64_t remainder = psrc1;
578            //Similarly, this is a temporary so changing it doesn't make it
579            //a source.
580            uint64_t divisor = op2;
581            //This is a temporary just for consistency and clarity.
582            uint64_t dividend = remainder;
583            //Do the division.
584            divide(dividend, divisor, quotient, remainder);
585            //Record the final results.
586            Remainder = remainder;
587            Quotient = quotient;
588            Divisor = divisor;
589            '''
590
591    # Step divide
592    class Div2(RegOp):
593        code = '''
594            uint64_t dividend = Remainder;
595            uint64_t divisor = Divisor;
596            uint64_t quotient = Quotient;
597            uint64_t remainder = dividend;
598            int remaining = op2;
599            //If we overshot, do nothing. This lets us unrool division loops a
600            //little.
601            if (remaining) {
602                //Shift in bits from the low order portion of the dividend
603                while(dividend < divisor && remaining) {
604                    dividend = (dividend << 1) | bits(SrcReg1, remaining - 1);
605                    quotient <<= 1;
606                    remaining--;
607                }
608                remainder = dividend;
609                //Do the division.
610                divide(dividend, divisor, quotient, remainder);
611            }
612            //Keep track of how many bits there are still to pull in.
613            DestReg = merge(DestReg, remaining, dataSize);
614            //Record the final results
615            Remainder = remainder;
616            Quotient = quotient;
617        '''
618        flag_code = '''
619            if (DestReg == 0)
620                ccFlagBits = ccFlagBits | (ext & EZFBit);
621            else
622                ccFlagBits = ccFlagBits & ~(ext & EZFBit);
623        '''
624
625    class Divq(RdRegOp):
626        code = 'DestReg = merge(SrcReg1, Quotient, dataSize);'
627
628    class Divr(RdRegOp):
629        code = 'DestReg = merge(SrcReg1, Remainder, dataSize);'
630
631    class Mov(CondRegOp):
632        code = 'DestReg = merge(SrcReg1, op2, dataSize)'
633        else_code = 'DestReg=DestReg;'
634
635    # Shift instructions
636
637    class Sll(RegOp):
638        code = '''
639            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
640            DestReg = merge(DestReg, psrc1 << shiftAmt, dataSize);
641            '''
642        flag_code = '''
643            // If the shift amount is zero, no flags should be modified.
644            if (shiftAmt) {
645                //Zero out any flags we might modify. This way we only have to
646                //worry about setting them.
647                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
648                int CFBits = 0;
649                //Figure out if we -would- set the CF bits if requested.
650                if (shiftAmt <= dataSize * 8 &&
651                        bits(SrcReg1, dataSize * 8 - shiftAmt)) {
652                    CFBits = 1;
653                }
654                //If some combination of the CF bits need to be set, set them.
655                if ((ext & (CFBit | ECFBit)) && CFBits)
656                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
657                //Figure out what the OF bit should be.
658                if ((ext & OFBit) && (CFBits ^ bits(DestReg, dataSize * 8 - 1)))
659                    ccFlagBits = ccFlagBits | OFBit;
660                //Use the regular mechanisms to calculate the other flags.
661                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
662                        DestReg, psrc1, op2);
663            }
664        '''
665
666    class Srl(RegOp):
667        code = '''
668            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
669            // Because what happens to the bits shift -in- on a right shift
670            // is not defined in the C/C++ standard, we have to mask them out
671            // to be sure they're zero.
672            uint64_t logicalMask = mask(dataSize * 8 - shiftAmt);
673            DestReg = merge(DestReg, (psrc1 >> shiftAmt) & logicalMask, dataSize);
674            '''
675        flag_code = '''
676            // If the shift amount is zero, no flags should be modified.
677            if (shiftAmt) {
678                //Zero out any flags we might modify. This way we only have to
679                //worry about setting them.
680                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
681                //If some combination of the CF bits need to be set, set them.
682                if ((ext & (CFBit | ECFBit)) && 
683                        shiftAmt <= dataSize * 8 &&
684                        bits(SrcReg1, shiftAmt - 1)) {
685                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
686                }
687                //Figure out what the OF bit should be.
688                if ((ext & OFBit) && bits(SrcReg1, dataSize * 8 - 1))
689                    ccFlagBits = ccFlagBits | OFBit;
690                //Use the regular mechanisms to calculate the other flags.
691                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
692                        DestReg, psrc1, op2);
693            }
694        '''
695
696    class Sra(RegOp):
697        code = '''
698            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
699            // Because what happens to the bits shift -in- on a right shift
700            // is not defined in the C/C++ standard, we have to sign extend
701            // them manually to be sure.
702            uint64_t arithMask = (shiftAmt == 0) ? 0 :
703                -bits(psrc1, dataSize * 8 - 1) << (dataSize * 8 - shiftAmt);
704            DestReg = merge(DestReg, (psrc1 >> shiftAmt) | arithMask, dataSize);
705            '''
706        flag_code = '''
707            // If the shift amount is zero, no flags should be modified.
708            if (shiftAmt) {
709                //Zero out any flags we might modify. This way we only have to
710                //worry about setting them.
711                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
712                //If some combination of the CF bits need to be set, set them.
713                uint8_t effectiveShift =
714                    (shiftAmt <= dataSize * 8) ? shiftAmt : (dataSize * 8);
715                if ((ext & (CFBit | ECFBit)) &&
716                        bits(SrcReg1, effectiveShift - 1)) {
717                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
718                }
719                //Use the regular mechanisms to calculate the other flags.
720                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
721                        DestReg, psrc1, op2);
722            }
723        '''
724
725    class Ror(RegOp):
726        code = '''
727            uint8_t shiftAmt =
728                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
729            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
730            if(realShiftAmt)
731            {
732                uint64_t top = psrc1 << (dataSize * 8 - realShiftAmt);
733                uint64_t bottom = bits(psrc1, dataSize * 8, realShiftAmt);
734                DestReg = merge(DestReg, top | bottom, dataSize);
735            }
736            else
737                DestReg = merge(DestReg, DestReg, dataSize);
738            '''
739        flag_code = '''
740            // If the shift amount is zero, no flags should be modified.
741            if (shiftAmt) {
742                //Zero out any flags we might modify. This way we only have to
743                //worry about setting them.
744                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
745                //Find the most and second most significant bits of the result.
746                int msb = bits(DestReg, dataSize * 8 - 1);
747                int smsb = bits(DestReg, dataSize * 8 - 2);
748                //If some combination of the CF bits need to be set, set them.
749                if ((ext & (CFBit | ECFBit)) && msb)
750                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
751                //Figure out what the OF bit should be.
752                if ((ext & OFBit) && (msb ^ smsb))
753                    ccFlagBits = ccFlagBits | OFBit;
754                //Use the regular mechanisms to calculate the other flags.
755                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
756                        DestReg, psrc1, op2);
757            }
758        '''
759
760    class Rcr(RegOp):
761        code = '''
762            uint8_t shiftAmt =
763                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
764            uint8_t realShiftAmt = shiftAmt % (dataSize * 8 + 1);
765            if(realShiftAmt)
766            {
767                CCFlagBits flags = ccFlagBits;
768                uint64_t top = flags.cf << (dataSize * 8 - realShiftAmt);
769                if (realShiftAmt > 1)
770                    top |= psrc1 << (dataSize * 8 - realShiftAmt + 1);
771                uint64_t bottom = bits(psrc1, dataSize * 8 - 1, realShiftAmt);
772                DestReg = merge(DestReg, top | bottom, dataSize);
773            }
774            else
775                DestReg = merge(DestReg, DestReg, dataSize);
776            '''
777        flag_code = '''
778            // If the shift amount is zero, no flags should be modified.
779            if (shiftAmt) {
780                int origCFBit = (ccFlagBits & CFBit) ? 1 : 0;
781                //Zero out any flags we might modify. This way we only have to
782                //worry about setting them.
783                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
784                //Figure out what the OF bit should be.
785                if ((ext & OFBit) && (origCFBit ^
786                                      bits(SrcReg1, dataSize * 8 - 1))) {
787                    ccFlagBits = ccFlagBits | OFBit;
788                }
789                //If some combination of the CF bits need to be set, set them.
790                if ((ext & (CFBit | ECFBit)) &&
791                        (realShiftAmt == 0) ? origCFBit :
792                        bits(SrcReg1, realShiftAmt - 1)) {
793                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
794                }
795                //Use the regular mechanisms to calculate the other flags.
796                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
797                        DestReg, psrc1, op2);
798            }
799        '''
800
801    class Rol(RegOp):
802        code = '''
803            uint8_t shiftAmt =
804                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
805            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
806            if(realShiftAmt)
807            {
808                uint64_t top = psrc1 << realShiftAmt;
809                uint64_t bottom =
810                    bits(psrc1, dataSize * 8 - 1, dataSize * 8 - realShiftAmt);
811                DestReg = merge(DestReg, top | bottom, dataSize);
812            }
813            else
814                DestReg = merge(DestReg, DestReg, dataSize);
815            '''
816        flag_code = '''
817            // If the shift amount is zero, no flags should be modified.
818            if (shiftAmt) {
819                //Zero out any flags we might modify. This way we only have to
820                //worry about setting them.
821                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
822                //The CF bits, if set, would be set to the lsb of the result.
823                int lsb = DestReg & 0x1;
824                int msb = bits(DestReg, dataSize * 8 - 1);
825                //If some combination of the CF bits need to be set, set them.
826                if ((ext & (CFBit | ECFBit)) && lsb)
827                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
828                //Figure out what the OF bit should be.
829                if ((ext & OFBit) && (msb ^ lsb))
830                    ccFlagBits = ccFlagBits | OFBit;
831                //Use the regular mechanisms to calculate the other flags.
832                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
833                        DestReg, psrc1, op2);
834            }
835        '''
836
837    class Rcl(RegOp):
838        code = '''
839            uint8_t shiftAmt =
840                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
841            uint8_t realShiftAmt = shiftAmt % (dataSize * 8 + 1);
842            if(realShiftAmt)
843            {
844                CCFlagBits flags = ccFlagBits;
845                uint64_t top = psrc1 << realShiftAmt;
846                uint64_t bottom = flags.cf << (realShiftAmt - 1);
847                if(shiftAmt > 1)
848                    bottom |=
849                        bits(psrc1, dataSize * 8 - 1,
850                                   dataSize * 8 - realShiftAmt + 1);
851                DestReg = merge(DestReg, top | bottom, dataSize);
852            }
853            else
854                DestReg = merge(DestReg, DestReg, dataSize);
855            '''
856        flag_code = '''
857            // If the shift amount is zero, no flags should be modified.
858            if (shiftAmt) {
859                int origCFBit = (ccFlagBits & CFBit) ? 1 : 0;
860                //Zero out any flags we might modify. This way we only have to
861                //worry about setting them.
862                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
863                int msb = bits(DestReg, dataSize * 8 - 1);
864                int CFBits = bits(SrcReg1, dataSize * 8 - realShiftAmt);
865                //If some combination of the CF bits need to be set, set them.
866                if ((ext & (CFBit | ECFBit)) && 
867                        (realShiftAmt == 0) ? origCFBit : CFBits)
868                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
869                //Figure out what the OF bit should be.
870                if ((ext & OFBit) && (msb ^ CFBits))
871                    ccFlagBits = ccFlagBits | OFBit;
872                //Use the regular mechanisms to calculate the other flags.
873                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
874                        DestReg, psrc1, op2);
875            }
876        '''
877
878    class Wrip(WrRegOp, CondRegOp):
879        code = 'RIP = psrc1 + sop2 + CSBase'
880        else_code="RIP = RIP;"
881
882    class Wruflags(WrRegOp):
883        code = 'ccFlagBits = psrc1 ^ op2'
884
885    class Wrflags(WrRegOp):
886        code = '''
887            MiscReg newFlags = psrc1 ^ op2;
888            MiscReg userFlagMask = 0xDD5;
889            // Get only the user flags
890            ccFlagBits = newFlags & userFlagMask;
891            // Get everything else
892            nccFlagBits = newFlags & ~userFlagMask;
893        '''
894
895    class Rdip(RdRegOp):
896        code = 'DestReg = RIP - CSBase'
897
898    class Ruflags(RdRegOp):
899        code = 'DestReg = ccFlagBits'
900
901    class Rflags(RdRegOp):
902        code = 'DestReg = ccFlagBits | nccFlagBits'
903
904    class Ruflag(RegOp):
905        code = '''
906            int flag = bits(ccFlagBits, imm8);
907            DestReg = merge(DestReg, flag, dataSize);
908            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
909                                       (ccFlagBits & ~EZFBit);
910            '''
911        def __init__(self, dest, imm, flags=None, \
912                dataSize="env.dataSize"):
913            super(Ruflag, self).__init__(dest, \
914                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
915
916    class Rflag(RegOp):
917        code = '''
918            MiscReg flagMask = 0x3F7FDD5;
919            MiscReg flags = (nccFlagBits | ccFlagBits) & flagMask;
920            int flag = bits(flags, imm8);
921            DestReg = merge(DestReg, flag, dataSize);
922            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
923                                       (ccFlagBits & ~EZFBit);
924            '''
925        def __init__(self, dest, imm, flags=None, \
926                dataSize="env.dataSize"):
927            super(Rflag, self).__init__(dest, \
928                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
929
930    class Sext(RegOp):
931        code = '''
932            IntReg val = psrc1;
933            // Mask the bit position so that it wraps.
934            int bitPos = op2 & (dataSize * 8 - 1);
935            int sign_bit = bits(val, bitPos, bitPos);
936            uint64_t maskVal = mask(bitPos+1);
937            val = sign_bit ? (val | ~maskVal) : (val & maskVal);
938            DestReg = merge(DestReg, val, dataSize);
939            '''
940        flag_code = '''
941            if (!sign_bit)
942                ccFlagBits = ccFlagBits &
943                    ~(ext & (CFBit | ECFBit | ZFBit | EZFBit));
944            else
945                ccFlagBits = ccFlagBits |
946                    (ext & (CFBit | ECFBit | ZFBit | EZFBit));
947            '''
948
949    class Zext(RegOp):
950        code = 'DestReg = merge(DestReg, bits(psrc1, op2, 0), dataSize);'
951
952    class Rddr(RegOp):
953        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
954            super(Rddr, self).__init__(dest, \
955                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
956        code = '''
957            CR4 cr4 = CR4Op;
958            DR7 dr7 = DR7Op;
959            if ((cr4.de == 1 && (src1 == 4 || src1 == 5)) || src1 >= 8) {
960                fault = new InvalidOpcode();
961            } else if (dr7.gd) {
962                fault = new DebugException();
963            } else {
964                DestReg = merge(DestReg, DebugSrc1, dataSize);
965            }
966        '''
967
968    class Wrdr(RegOp):
969        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
970            super(Wrdr, self).__init__(dest, \
971                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
972        code = '''
973            CR4 cr4 = CR4Op;
974            DR7 dr7 = DR7Op;
975            if ((cr4.de == 1 && (dest == 4 || dest == 5)) || dest >= 8) {
976                fault = new InvalidOpcode();
977            } else if ((dest == 6 || dest == 7) && bits(psrc1, 63, 32) &&
978                    machInst.mode.mode == LongMode) {
979                fault = new GeneralProtection(0);
980            } else if (dr7.gd) {
981                fault = new DebugException();
982            } else {
983                DebugDest = psrc1;
984            }
985        '''
986
987    class Rdcr(RegOp):
988        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
989            super(Rdcr, self).__init__(dest, \
990                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
991        code = '''
992            if (src1 == 1 || (src1 > 4 && src1 < 8) || (src1 > 8)) {
993                fault = new InvalidOpcode();
994            } else {
995                DestReg = merge(DestReg, ControlSrc1, dataSize);
996            }
997        '''
998
999    class Wrcr(RegOp):
1000        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1001            super(Wrcr, self).__init__(dest, \
1002                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1003        code = '''
1004            if (dest == 1 || (dest > 4 && dest < 8) || (dest > 8)) {
1005                fault = new InvalidOpcode();
1006            } else {
1007                // There are *s in the line below so it doesn't confuse the
1008                // parser. They may be unnecessary.
1009                //Mis*cReg old*Val = pick(Cont*rolDest, 0, dat*aSize);
1010                MiscReg newVal = psrc1;
1011
1012                // Check for any modifications that would cause a fault.
1013                switch(dest) {
1014                  case 0:
1015                    {
1016                        Efer efer = EferOp;
1017                        CR0 cr0 = newVal;
1018                        CR4 oldCr4 = CR4Op;
1019                        if (bits(newVal, 63, 32) ||
1020                                (!cr0.pe && cr0.pg) ||
1021                                (!cr0.cd && cr0.nw) ||
1022                                (cr0.pg && efer.lme && !oldCr4.pae))
1023                            fault = new GeneralProtection(0);
1024                    }
1025                    break;
1026                  case 2:
1027                    break;
1028                  case 3:
1029                    break;
1030                  case 4:
1031                    {
1032                        CR4 cr4 = newVal;
1033                        // PAE can't be disabled in long mode.
1034                        if (bits(newVal, 63, 11) ||
1035                                (machInst.mode.mode == LongMode && !cr4.pae))
1036                            fault = new GeneralProtection(0);
1037                    }
1038                    break;
1039                  case 8:
1040                    {
1041                        if (bits(newVal, 63, 4))
1042                            fault = new GeneralProtection(0);
1043                    }
1044                  default:
1045                    panic("Unrecognized control register %d.\\n", dest);
1046                }
1047                ControlDest = newVal;
1048            }
1049            '''
1050
1051    # Microops for manipulating segmentation registers
1052    class SegOp(CondRegOp):
1053        abstract = True
1054        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1055            super(SegOp, self).__init__(dest, \
1056                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1057
1058    class Wrbase(SegOp):
1059        code = '''
1060            SegBaseDest = psrc1;
1061        '''
1062
1063    class Wrlimit(SegOp):
1064        code = '''
1065            SegLimitDest = psrc1;
1066        '''
1067
1068    class Wrsel(SegOp):
1069        code = '''
1070            SegSelDest = psrc1;
1071        '''
1072
1073    class WrAttr(SegOp):
1074        code = '''
1075            SegAttrDest = psrc1;
1076        '''
1077
1078    class Rdbase(SegOp):
1079        code = '''
1080            DestReg = merge(DestReg, SegBaseSrc1, dataSize);
1081        '''
1082
1083    class Rdlimit(SegOp):
1084        code = '''
1085            DestReg = merge(DestReg, SegLimitSrc1, dataSize);
1086        '''
1087
1088    class RdAttr(SegOp):
1089        code = '''
1090            DestReg = merge(DestReg, SegAttrSrc1, dataSize);
1091        '''
1092
1093    class Rdsel(SegOp):
1094        code = '''
1095            DestReg = merge(DestReg, SegSelSrc1, dataSize);
1096        '''
1097
1098    class Rdval(RegOp):
1099        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1100            super(Rdval, self).__init__(dest, src1, \
1101                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1102        code = '''
1103            DestReg = MiscRegSrc1;
1104        '''
1105
1106    class Wrval(RegOp):
1107        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1108            super(Wrval, self).__init__(dest, src1, \
1109                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1110        code = '''
1111            MiscRegDest = SrcReg1;
1112        '''
1113
1114    class Chks(RegOp):
1115        def __init__(self, dest, src1, src2=0,
1116                flags=None, dataSize="env.dataSize"):
1117            super(Chks, self).__init__(dest,
1118                    src1, src2, flags, dataSize)
1119        code = '''
1120            // The selector is in source 1 and can be at most 16 bits.
1121            SegSelector selector = DestReg;
1122            SegDescriptor desc = SrcReg1;
1123            HandyM5Reg m5reg = M5Reg;
1124
1125            switch (imm8)
1126            {
1127              case SegNoCheck:
1128                break;
1129              case SegCSCheck:
1130                // Make sure it's the right type
1131                if (desc.s == 0 || desc.type.codeOrData != 1) {
1132                    fault = new GeneralProtection(0);
1133                } else if (m5reg.cpl != desc.dpl) {
1134                    fault = new GeneralProtection(0);
1135                }
1136                break;
1137              case SegCallGateCheck:
1138                panic("CS checks for far calls/jumps through call gates"
1139                        "not implemented.\\n");
1140                break;
1141              case SegSoftIntGateCheck:
1142                // Check permissions.
1143                if (desc.dpl < m5reg.cpl) {
1144                    fault = new GeneralProtection(selector);
1145                    break;
1146                }
1147                // Fall through on purpose
1148              case SegIntGateCheck:
1149                // Make sure the gate's the right type.
1150                if ((m5reg.mode == LongMode && (desc.type & 0xe) != 0xe) ||
1151                        ((desc.type & 0x6) != 0x6)) {
1152                    fault = new GeneralProtection(0);
1153                }
1154                break;
1155              case SegSSCheck:
1156                if (selector.si || selector.ti) {
1157                    if (!desc.p) {
1158                        fault = new StackFault(selector);
1159                    }
1160                } else {
1161                    if ((m5reg.submode != SixtyFourBitMode ||
1162                                m5reg.cpl == 3) ||
1163                            !(desc.s == 1 &&
1164                            desc.type.codeOrData == 0 && desc.type.w) ||
1165                            (desc.dpl != m5reg.cpl) ||
1166                            (selector.rpl != m5reg.cpl)) {
1167                        fault = new GeneralProtection(selector);
1168                    }
1169                }
1170                break;
1171              case SegIretCheck:
1172                {
1173                    if ((!selector.si && !selector.ti) ||
1174                            (selector.rpl < m5reg.cpl) ||
1175                            !(desc.s == 1 && desc.type.codeOrData == 1) ||
1176                            (!desc.type.c && desc.dpl != selector.rpl) ||
1177                            (desc.type.c && desc.dpl > selector.rpl)) {
1178                        fault = new GeneralProtection(selector);
1179                    } else if (!desc.p) {
1180                        fault = new SegmentNotPresent(selector);
1181                    }
1182                    break;
1183                }
1184              case SegIntCSCheck:
1185                if (m5reg.mode == LongMode) {
1186                    if (desc.l != 1 || desc.d != 0) {
1187                        fault = new GeneralProtection(selector);
1188                    }
1189                } else {
1190                    panic("Interrupt CS checks not implemented "
1191                            "in legacy mode.\\n");
1192                }
1193                break;
1194              case SegTRCheck:
1195                if (!selector.si || selector.ti) {
1196                    fault = new GeneralProtection(selector);
1197                }
1198                break;
1199              case SegTSSCheck:
1200                if (!desc.p) {
1201                    fault = new SegmentNotPresent(selector);
1202                } else if (!(desc.type == 0x9 ||
1203                        (desc.type == 1 &&
1204                         m5reg.mode != LongMode))) {
1205                    fault = new GeneralProtection(selector);
1206                }
1207                break;
1208              case SegInGDTCheck:
1209                if (selector.ti) {
1210                    fault = new GeneralProtection(selector);
1211                }
1212                break;
1213              case SegLDTCheck:
1214                if (!desc.p) {
1215                    fault = new SegmentNotPresent(selector);
1216                } else if (desc.type != 0x2) {
1217                    fault = new GeneralProtection(selector);
1218                }
1219                break;
1220              default:
1221                panic("Undefined segment check type.\\n");
1222            }
1223        '''
1224        flag_code = '''
1225            // Check for a NULL selector and set ZF,EZF appropriately.
1226            ccFlagBits = ccFlagBits & ~(ext & (ZFBit | EZFBit));
1227            if (!selector.si && !selector.ti)
1228                ccFlagBits = ccFlagBits | (ext & (ZFBit | EZFBit));
1229        '''
1230
1231    class Wrdh(RegOp):
1232        code = '''
1233            SegDescriptor desc = SrcReg1;
1234
1235            uint64_t target = bits(SrcReg2, 31, 0) << 32;
1236            switch(desc.type) {
1237              case LDT64:
1238              case AvailableTSS64:
1239              case BusyTSS64:
1240                replaceBits(target, 23, 0, desc.baseLow);
1241                replaceBits(target, 31, 24, desc.baseHigh);
1242                break;
1243              case CallGate64:
1244              case IntGate64:
1245              case TrapGate64:
1246                replaceBits(target, 15, 0, bits(desc, 15, 0));
1247                replaceBits(target, 31, 16, bits(desc, 63, 48));
1248                break;
1249              default:
1250                panic("Wrdh used with wrong descriptor type!\\n");
1251            }
1252            DestReg = target;
1253        '''
1254
1255    class Wrtsc(WrRegOp):
1256        code = '''
1257            TscOp = psrc1;
1258        '''
1259
1260    class Rdtsc(RdRegOp):
1261        code = '''
1262            DestReg = TscOp;
1263        '''
1264
1265    class Rdm5reg(RdRegOp):
1266        code = '''
1267            DestReg = M5Reg;
1268        '''
1269
1270    class Wrdl(RegOp):
1271        code = '''
1272            SegDescriptor desc = SrcReg1;
1273            SegSelector selector = SrcReg2;
1274            if (selector.si || selector.ti) {
1275                if (!desc.p)
1276                    panic("Segment not present.\\n");
1277                SegAttr attr = 0;
1278                attr.dpl = desc.dpl;
1279                attr.unusable = 0;
1280                attr.defaultSize = desc.d;
1281                attr.longMode = desc.l;
1282                attr.avl = desc.avl;
1283                attr.granularity = desc.g;
1284                attr.present = desc.p;
1285                attr.system = desc.s;
1286                attr.type = desc.type;
1287                if (!desc.s) {
1288                    // The expand down bit happens to be set for gates.
1289                    if (desc.type.e) {
1290                        panic("Gate descriptor encountered.\\n");
1291                    }
1292                    attr.readable = 1;
1293                    attr.writable = 1;
1294                    attr.expandDown = 0;
1295                } else {
1296                    if (desc.type.codeOrData) {
1297                        attr.expandDown = 0;
1298                        attr.readable = desc.type.r;
1299                        attr.writable = 0;
1300                    } else {
1301                        attr.expandDown = desc.type.e;
1302                        attr.readable = 1;
1303                        attr.writable = desc.type.w;
1304                    }
1305                }
1306                Addr base = desc.baseLow | (desc.baseHigh << 24);
1307                Addr limit = desc.limitLow | (desc.limitHigh << 16);
1308                if (desc.g)
1309                    limit = (limit << 12) | mask(12);
1310                SegBaseDest = base;
1311                SegLimitDest = limit;
1312                SegAttrDest = attr;
1313            } else {
1314                SegBaseDest = SegBaseDest;
1315                SegLimitDest = SegLimitDest;
1316                SegAttrDest = SegAttrDest;
1317            }
1318        '''
1319}};
1320