regop.isa revision 6464
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        flag_code = '''
540            if ((-ProdHi & mask(dataSize * 8)) !=
541                    bits(ProdLow, dataSize * 8 - 1)) {
542                ccFlagBits = ccFlagBits | (ext & (CFBit | OFBit | ECFBit));
543            } else {
544                ccFlagBits = ccFlagBits & ~(ext & (CFBit | OFBit | ECFBit));
545            }
546        '''
547
548    class Mul1u(WrRegOp):
549        code = '''
550            ProdLow = psrc1 * op2;
551            int halfSize = (dataSize * 8) / 2;
552            uint64_t shifter = (1ULL << halfSize);
553            uint64_t psrc1_h = psrc1 / shifter;
554            uint64_t psrc1_l = psrc1 & mask(halfSize);
555            uint64_t psrc2_h = (op2 / shifter) & mask(halfSize);
556            uint64_t psrc2_l = op2 & mask(halfSize);
557            ProdHi = ((psrc1_l * psrc2_h + psrc1_h * psrc2_l +
558                      ((psrc1_l * psrc2_l) / shifter)) / shifter) +
559                     psrc1_h * psrc2_h;
560            '''
561        flag_code = '''
562            if (ProdHi) {
563                ccFlagBits = ccFlagBits | (ext & (CFBit | OFBit | ECFBit));
564            } else {
565                ccFlagBits = ccFlagBits & ~(ext & (CFBit | OFBit | ECFBit));
566            }
567        '''
568
569    class Mulel(RdRegOp):
570        code = 'DestReg = merge(SrcReg1, ProdLow, dataSize);'
571
572    class Muleh(RdRegOp):
573        def __init__(self, dest, src1=None, flags=None, dataSize="env.dataSize"):
574            if not src1:
575                src1 = dest
576            super(RdRegOp, self).__init__(dest, src1, \
577                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
578        code = 'DestReg = merge(SrcReg1, ProdHi, dataSize);'
579
580    # One or two bit divide
581    class Div1(WrRegOp):
582        code = '''
583            //These are temporaries so that modifying them later won't make
584            //the ISA parser think they're also sources.
585            uint64_t quotient = 0;
586            uint64_t remainder = psrc1;
587            //Similarly, this is a temporary so changing it doesn't make it
588            //a source.
589            uint64_t divisor = op2;
590            //This is a temporary just for consistency and clarity.
591            uint64_t dividend = remainder;
592            //Do the division.
593            divide(dividend, divisor, quotient, remainder);
594            //Record the final results.
595            Remainder = remainder;
596            Quotient = quotient;
597            Divisor = divisor;
598            '''
599
600    # Step divide
601    class Div2(RegOp):
602        code = '''
603            uint64_t dividend = Remainder;
604            uint64_t divisor = Divisor;
605            uint64_t quotient = Quotient;
606            uint64_t remainder = dividend;
607            int remaining = op2;
608            //If we overshot, do nothing. This lets us unrool division loops a
609            //little.
610            if (remaining) {
611                //Shift in bits from the low order portion of the dividend
612                while(dividend < divisor && remaining) {
613                    dividend = (dividend << 1) | bits(SrcReg1, remaining - 1);
614                    quotient <<= 1;
615                    remaining--;
616                }
617                remainder = dividend;
618                //Do the division.
619                divide(dividend, divisor, quotient, remainder);
620            }
621            //Keep track of how many bits there are still to pull in.
622            DestReg = merge(DestReg, remaining, dataSize);
623            //Record the final results
624            Remainder = remainder;
625            Quotient = quotient;
626        '''
627        flag_code = '''
628            if (DestReg == 0)
629                ccFlagBits = ccFlagBits | (ext & EZFBit);
630            else
631                ccFlagBits = ccFlagBits & ~(ext & EZFBit);
632        '''
633
634    class Divq(RdRegOp):
635        code = 'DestReg = merge(SrcReg1, Quotient, dataSize);'
636
637    class Divr(RdRegOp):
638        code = 'DestReg = merge(SrcReg1, Remainder, dataSize);'
639
640    class Mov(CondRegOp):
641        code = 'DestReg = merge(SrcReg1, op2, dataSize)'
642        else_code = 'DestReg = merge(DestReg, DestReg, dataSize);'
643
644    # Shift instructions
645
646    class Sll(RegOp):
647        code = '''
648            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
649            DestReg = merge(DestReg, psrc1 << shiftAmt, dataSize);
650            '''
651        flag_code = '''
652            // If the shift amount is zero, no flags should be modified.
653            if (shiftAmt) {
654                //Zero out any flags we might modify. This way we only have to
655                //worry about setting them.
656                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
657                int CFBits = 0;
658                //Figure out if we -would- set the CF bits if requested.
659                if (shiftAmt <= dataSize * 8 &&
660                        bits(SrcReg1, dataSize * 8 - shiftAmt)) {
661                    CFBits = 1;
662                }
663                //If some combination of the CF bits need to be set, set them.
664                if ((ext & (CFBit | ECFBit)) && CFBits)
665                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
666                //Figure out what the OF bit should be.
667                if ((ext & OFBit) && (CFBits ^ bits(DestReg, dataSize * 8 - 1)))
668                    ccFlagBits = ccFlagBits | OFBit;
669                //Use the regular mechanisms to calculate the other flags.
670                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
671                        DestReg, psrc1, op2);
672            }
673        '''
674
675    class Srl(RegOp):
676        code = '''
677            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
678            // Because what happens to the bits shift -in- on a right shift
679            // is not defined in the C/C++ standard, we have to mask them out
680            // to be sure they're zero.
681            uint64_t logicalMask = mask(dataSize * 8 - shiftAmt);
682            DestReg = merge(DestReg, (psrc1 >> shiftAmt) & logicalMask, dataSize);
683            '''
684        flag_code = '''
685            // If the shift amount is zero, no flags should be modified.
686            if (shiftAmt) {
687                //Zero out any flags we might modify. This way we only have to
688                //worry about setting them.
689                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
690                //If some combination of the CF bits need to be set, set them.
691                if ((ext & (CFBit | ECFBit)) && 
692                        shiftAmt <= dataSize * 8 &&
693                        bits(SrcReg1, shiftAmt - 1)) {
694                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
695                }
696                //Figure out what the OF bit should be.
697                if ((ext & OFBit) && bits(SrcReg1, dataSize * 8 - 1))
698                    ccFlagBits = ccFlagBits | OFBit;
699                //Use the regular mechanisms to calculate the other flags.
700                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
701                        DestReg, psrc1, op2);
702            }
703        '''
704
705    class Sra(RegOp):
706        code = '''
707            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
708            // Because what happens to the bits shift -in- on a right shift
709            // is not defined in the C/C++ standard, we have to sign extend
710            // them manually to be sure.
711            uint64_t arithMask = (shiftAmt == 0) ? 0 :
712                -bits(psrc1, dataSize * 8 - 1) << (dataSize * 8 - shiftAmt);
713            DestReg = merge(DestReg, (psrc1 >> shiftAmt) | arithMask, dataSize);
714            '''
715        flag_code = '''
716            // If the shift amount is zero, no flags should be modified.
717            if (shiftAmt) {
718                //Zero out any flags we might modify. This way we only have to
719                //worry about setting them.
720                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
721                //If some combination of the CF bits need to be set, set them.
722                uint8_t effectiveShift =
723                    (shiftAmt <= dataSize * 8) ? shiftAmt : (dataSize * 8);
724                if ((ext & (CFBit | ECFBit)) &&
725                        bits(SrcReg1, effectiveShift - 1)) {
726                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
727                }
728                //Use the regular mechanisms to calculate the other flags.
729                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
730                        DestReg, psrc1, op2);
731            }
732        '''
733
734    class Ror(RegOp):
735        code = '''
736            uint8_t shiftAmt =
737                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
738            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
739            if(realShiftAmt)
740            {
741                uint64_t top = psrc1 << (dataSize * 8 - realShiftAmt);
742                uint64_t bottom = bits(psrc1, dataSize * 8, realShiftAmt);
743                DestReg = merge(DestReg, top | bottom, dataSize);
744            }
745            else
746                DestReg = merge(DestReg, DestReg, dataSize);
747            '''
748        flag_code = '''
749            // If the shift amount is zero, no flags should be modified.
750            if (shiftAmt) {
751                //Zero out any flags we might modify. This way we only have to
752                //worry about setting them.
753                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
754                //Find the most and second most significant bits of the result.
755                int msb = bits(DestReg, dataSize * 8 - 1);
756                int smsb = bits(DestReg, dataSize * 8 - 2);
757                //If some combination of the CF bits need to be set, set them.
758                if ((ext & (CFBit | ECFBit)) && msb)
759                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
760                //Figure out what the OF bit should be.
761                if ((ext & OFBit) && (msb ^ smsb))
762                    ccFlagBits = ccFlagBits | OFBit;
763                //Use the regular mechanisms to calculate the other flags.
764                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
765                        DestReg, psrc1, op2);
766            }
767        '''
768
769    class Rcr(RegOp):
770        code = '''
771            uint8_t shiftAmt =
772                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
773            uint8_t realShiftAmt = shiftAmt % (dataSize * 8 + 1);
774            if(realShiftAmt)
775            {
776                CCFlagBits flags = ccFlagBits;
777                uint64_t top = flags.cf << (dataSize * 8 - realShiftAmt);
778                if (realShiftAmt > 1)
779                    top |= psrc1 << (dataSize * 8 - realShiftAmt + 1);
780                uint64_t bottom = bits(psrc1, dataSize * 8 - 1, realShiftAmt);
781                DestReg = merge(DestReg, top | bottom, dataSize);
782            }
783            else
784                DestReg = merge(DestReg, DestReg, dataSize);
785            '''
786        flag_code = '''
787            // If the shift amount is zero, no flags should be modified.
788            if (shiftAmt) {
789                int origCFBit = (ccFlagBits & CFBit) ? 1 : 0;
790                //Zero out any flags we might modify. This way we only have to
791                //worry about setting them.
792                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
793                //Figure out what the OF bit should be.
794                if ((ext & OFBit) && (origCFBit ^
795                                      bits(SrcReg1, dataSize * 8 - 1))) {
796                    ccFlagBits = ccFlagBits | OFBit;
797                }
798                //If some combination of the CF bits need to be set, set them.
799                if ((ext & (CFBit | ECFBit)) &&
800                        (realShiftAmt == 0) ? origCFBit :
801                        bits(SrcReg1, realShiftAmt - 1)) {
802                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
803                }
804                //Use the regular mechanisms to calculate the other flags.
805                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
806                        DestReg, psrc1, op2);
807            }
808        '''
809
810    class Rol(RegOp):
811        code = '''
812            uint8_t shiftAmt =
813                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
814            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
815            if(realShiftAmt)
816            {
817                uint64_t top = psrc1 << realShiftAmt;
818                uint64_t bottom =
819                    bits(psrc1, dataSize * 8 - 1, dataSize * 8 - realShiftAmt);
820                DestReg = merge(DestReg, top | bottom, dataSize);
821            }
822            else
823                DestReg = merge(DestReg, DestReg, dataSize);
824            '''
825        flag_code = '''
826            // If the shift amount is zero, no flags should be modified.
827            if (shiftAmt) {
828                //Zero out any flags we might modify. This way we only have to
829                //worry about setting them.
830                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
831                //The CF bits, if set, would be set to the lsb of the result.
832                int lsb = DestReg & 0x1;
833                int msb = bits(DestReg, dataSize * 8 - 1);
834                //If some combination of the CF bits need to be set, set them.
835                if ((ext & (CFBit | ECFBit)) && lsb)
836                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
837                //Figure out what the OF bit should be.
838                if ((ext & OFBit) && (msb ^ lsb))
839                    ccFlagBits = ccFlagBits | OFBit;
840                //Use the regular mechanisms to calculate the other flags.
841                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
842                        DestReg, psrc1, op2);
843            }
844        '''
845
846    class Rcl(RegOp):
847        code = '''
848            uint8_t shiftAmt =
849                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
850            uint8_t realShiftAmt = shiftAmt % (dataSize * 8 + 1);
851            if(realShiftAmt)
852            {
853                CCFlagBits flags = ccFlagBits;
854                uint64_t top = psrc1 << realShiftAmt;
855                uint64_t bottom = flags.cf << (realShiftAmt - 1);
856                if(shiftAmt > 1)
857                    bottom |=
858                        bits(psrc1, dataSize * 8 - 1,
859                                   dataSize * 8 - realShiftAmt + 1);
860                DestReg = merge(DestReg, top | bottom, dataSize);
861            }
862            else
863                DestReg = merge(DestReg, DestReg, dataSize);
864            '''
865        flag_code = '''
866            // If the shift amount is zero, no flags should be modified.
867            if (shiftAmt) {
868                int origCFBit = (ccFlagBits & CFBit) ? 1 : 0;
869                //Zero out any flags we might modify. This way we only have to
870                //worry about setting them.
871                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
872                int msb = bits(DestReg, dataSize * 8 - 1);
873                int CFBits = bits(SrcReg1, dataSize * 8 - realShiftAmt);
874                //If some combination of the CF bits need to be set, set them.
875                if ((ext & (CFBit | ECFBit)) && 
876                        (realShiftAmt == 0) ? origCFBit : CFBits)
877                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
878                //Figure out what the OF bit should be.
879                if ((ext & OFBit) && (msb ^ CFBits))
880                    ccFlagBits = ccFlagBits | OFBit;
881                //Use the regular mechanisms to calculate the other flags.
882                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
883                        DestReg, psrc1, op2);
884            }
885        '''
886
887    class Wrip(WrRegOp, CondRegOp):
888        code = 'RIP = psrc1 + sop2 + CSBase'
889        else_code="RIP = RIP;"
890
891    class Wruflags(WrRegOp):
892        code = 'ccFlagBits = psrc1 ^ op2'
893
894    class Wrflags(WrRegOp):
895        code = '''
896            MiscReg newFlags = psrc1 ^ op2;
897            MiscReg userFlagMask = 0xDD5;
898            // Get only the user flags
899            ccFlagBits = newFlags & userFlagMask;
900            // Get everything else
901            nccFlagBits = newFlags & ~userFlagMask;
902        '''
903
904    class Rdip(RdRegOp):
905        code = 'DestReg = RIP - CSBase'
906
907    class Ruflags(RdRegOp):
908        code = 'DestReg = ccFlagBits'
909
910    class Rflags(RdRegOp):
911        code = 'DestReg = ccFlagBits | nccFlagBits'
912
913    class Ruflag(RegOp):
914        code = '''
915            int flag = bits(ccFlagBits, imm8);
916            DestReg = merge(DestReg, flag, dataSize);
917            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
918                                       (ccFlagBits & ~EZFBit);
919            '''
920        def __init__(self, dest, imm, flags=None, \
921                dataSize="env.dataSize"):
922            super(Ruflag, self).__init__(dest, \
923                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
924
925    class Rflag(RegOp):
926        code = '''
927            MiscReg flagMask = 0x3F7FDD5;
928            MiscReg flags = (nccFlagBits | ccFlagBits) & flagMask;
929            int flag = bits(flags, imm8);
930            DestReg = merge(DestReg, flag, dataSize);
931            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
932                                       (ccFlagBits & ~EZFBit);
933            '''
934        def __init__(self, dest, imm, flags=None, \
935                dataSize="env.dataSize"):
936            super(Rflag, self).__init__(dest, \
937                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
938
939    class Sext(RegOp):
940        code = '''
941            IntReg val = psrc1;
942            // Mask the bit position so that it wraps.
943            int bitPos = op2 & (dataSize * 8 - 1);
944            int sign_bit = bits(val, bitPos, bitPos);
945            uint64_t maskVal = mask(bitPos+1);
946            val = sign_bit ? (val | ~maskVal) : (val & maskVal);
947            DestReg = merge(DestReg, val, dataSize);
948            '''
949        flag_code = '''
950            if (!sign_bit)
951                ccFlagBits = ccFlagBits &
952                    ~(ext & (CFBit | ECFBit | ZFBit | EZFBit));
953            else
954                ccFlagBits = ccFlagBits |
955                    (ext & (CFBit | ECFBit | ZFBit | EZFBit));
956            '''
957
958    class Zext(RegOp):
959        code = 'DestReg = merge(DestReg, bits(psrc1, op2, 0), dataSize);'
960
961    class Rddr(RegOp):
962        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
963            super(Rddr, self).__init__(dest, \
964                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
965        code = '''
966            CR4 cr4 = CR4Op;
967            DR7 dr7 = DR7Op;
968            if ((cr4.de == 1 && (src1 == 4 || src1 == 5)) || src1 >= 8) {
969                fault = new InvalidOpcode();
970            } else if (dr7.gd) {
971                fault = new DebugException();
972            } else {
973                DestReg = merge(DestReg, DebugSrc1, dataSize);
974            }
975        '''
976
977    class Wrdr(RegOp):
978        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
979            super(Wrdr, self).__init__(dest, \
980                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
981        code = '''
982            CR4 cr4 = CR4Op;
983            DR7 dr7 = DR7Op;
984            if ((cr4.de == 1 && (dest == 4 || dest == 5)) || dest >= 8) {
985                fault = new InvalidOpcode();
986            } else if ((dest == 6 || dest == 7) && bits(psrc1, 63, 32) &&
987                    machInst.mode.mode == LongMode) {
988                fault = new GeneralProtection(0);
989            } else if (dr7.gd) {
990                fault = new DebugException();
991            } else {
992                DebugDest = psrc1;
993            }
994        '''
995
996    class Rdcr(RegOp):
997        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
998            super(Rdcr, self).__init__(dest, \
999                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1000        code = '''
1001            if (src1 == 1 || (src1 > 4 && src1 < 8) || (src1 > 8)) {
1002                fault = new InvalidOpcode();
1003            } else {
1004                DestReg = merge(DestReg, ControlSrc1, dataSize);
1005            }
1006        '''
1007
1008    class Wrcr(RegOp):
1009        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1010            super(Wrcr, self).__init__(dest, \
1011                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1012        code = '''
1013            if (dest == 1 || (dest > 4 && dest < 8) || (dest > 8)) {
1014                fault = new InvalidOpcode();
1015            } else {
1016                // There are *s in the line below so it doesn't confuse the
1017                // parser. They may be unnecessary.
1018                //Mis*cReg old*Val = pick(Cont*rolDest, 0, dat*aSize);
1019                MiscReg newVal = psrc1;
1020
1021                // Check for any modifications that would cause a fault.
1022                switch(dest) {
1023                  case 0:
1024                    {
1025                        Efer efer = EferOp;
1026                        CR0 cr0 = newVal;
1027                        CR4 oldCr4 = CR4Op;
1028                        if (bits(newVal, 63, 32) ||
1029                                (!cr0.pe && cr0.pg) ||
1030                                (!cr0.cd && cr0.nw) ||
1031                                (cr0.pg && efer.lme && !oldCr4.pae))
1032                            fault = new GeneralProtection(0);
1033                    }
1034                    break;
1035                  case 2:
1036                    break;
1037                  case 3:
1038                    break;
1039                  case 4:
1040                    {
1041                        CR4 cr4 = newVal;
1042                        // PAE can't be disabled in long mode.
1043                        if (bits(newVal, 63, 11) ||
1044                                (machInst.mode.mode == LongMode && !cr4.pae))
1045                            fault = new GeneralProtection(0);
1046                    }
1047                    break;
1048                  case 8:
1049                    {
1050                        if (bits(newVal, 63, 4))
1051                            fault = new GeneralProtection(0);
1052                    }
1053                  default:
1054                    panic("Unrecognized control register %d.\\n", dest);
1055                }
1056                ControlDest = newVal;
1057            }
1058            '''
1059
1060    # Microops for manipulating segmentation registers
1061    class SegOp(CondRegOp):
1062        abstract = True
1063        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1064            super(SegOp, self).__init__(dest, \
1065                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1066
1067    class Wrbase(SegOp):
1068        code = '''
1069            SegBaseDest = psrc1;
1070        '''
1071
1072    class Wrlimit(SegOp):
1073        code = '''
1074            SegLimitDest = psrc1;
1075        '''
1076
1077    class Wrsel(SegOp):
1078        code = '''
1079            SegSelDest = psrc1;
1080        '''
1081
1082    class WrAttr(SegOp):
1083        code = '''
1084            SegAttrDest = psrc1;
1085        '''
1086
1087    class Rdbase(SegOp):
1088        code = '''
1089            DestReg = merge(DestReg, SegBaseSrc1, dataSize);
1090        '''
1091
1092    class Rdlimit(SegOp):
1093        code = '''
1094            DestReg = merge(DestReg, SegLimitSrc1, dataSize);
1095        '''
1096
1097    class RdAttr(SegOp):
1098        code = '''
1099            DestReg = merge(DestReg, SegAttrSrc1, dataSize);
1100        '''
1101
1102    class Rdsel(SegOp):
1103        code = '''
1104            DestReg = merge(DestReg, SegSelSrc1, dataSize);
1105        '''
1106
1107    class Rdval(RegOp):
1108        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1109            super(Rdval, self).__init__(dest, src1, \
1110                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1111        code = '''
1112            DestReg = MiscRegSrc1;
1113        '''
1114
1115    class Wrval(RegOp):
1116        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1117            super(Wrval, self).__init__(dest, src1, \
1118                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1119        code = '''
1120            MiscRegDest = SrcReg1;
1121        '''
1122
1123    class Chks(RegOp):
1124        def __init__(self, dest, src1, src2=0,
1125                flags=None, dataSize="env.dataSize"):
1126            super(Chks, self).__init__(dest,
1127                    src1, src2, flags, dataSize)
1128        code = '''
1129            // The selector is in source 1 and can be at most 16 bits.
1130            SegSelector selector = DestReg;
1131            SegDescriptor desc = SrcReg1;
1132            HandyM5Reg m5reg = M5Reg;
1133
1134            switch (imm8)
1135            {
1136              case SegNoCheck:
1137                break;
1138              case SegCSCheck:
1139                // Make sure it's the right type
1140                if (desc.s == 0 || desc.type.codeOrData != 1) {
1141                    fault = new GeneralProtection(0);
1142                } else if (m5reg.cpl != desc.dpl) {
1143                    fault = new GeneralProtection(0);
1144                }
1145                break;
1146              case SegCallGateCheck:
1147                panic("CS checks for far calls/jumps through call gates"
1148                        "not implemented.\\n");
1149                break;
1150              case SegSoftIntGateCheck:
1151                // Check permissions.
1152                if (desc.dpl < m5reg.cpl) {
1153                    fault = new GeneralProtection(selector);
1154                    break;
1155                }
1156                // Fall through on purpose
1157              case SegIntGateCheck:
1158                // Make sure the gate's the right type.
1159                if ((m5reg.mode == LongMode && (desc.type & 0xe) != 0xe) ||
1160                        ((desc.type & 0x6) != 0x6)) {
1161                    fault = new GeneralProtection(0);
1162                }
1163                break;
1164              case SegSSCheck:
1165                if (selector.si || selector.ti) {
1166                    if (!desc.p) {
1167                        fault = new StackFault(selector);
1168                    }
1169                } else {
1170                    if ((m5reg.submode != SixtyFourBitMode ||
1171                                m5reg.cpl == 3) ||
1172                            !(desc.s == 1 &&
1173                            desc.type.codeOrData == 0 && desc.type.w) ||
1174                            (desc.dpl != m5reg.cpl) ||
1175                            (selector.rpl != m5reg.cpl)) {
1176                        fault = new GeneralProtection(selector);
1177                    }
1178                }
1179                break;
1180              case SegIretCheck:
1181                {
1182                    if ((!selector.si && !selector.ti) ||
1183                            (selector.rpl < m5reg.cpl) ||
1184                            !(desc.s == 1 && desc.type.codeOrData == 1) ||
1185                            (!desc.type.c && desc.dpl != selector.rpl) ||
1186                            (desc.type.c && desc.dpl > selector.rpl)) {
1187                        fault = new GeneralProtection(selector);
1188                    } else if (!desc.p) {
1189                        fault = new SegmentNotPresent(selector);
1190                    }
1191                    break;
1192                }
1193              case SegIntCSCheck:
1194                if (m5reg.mode == LongMode) {
1195                    if (desc.l != 1 || desc.d != 0) {
1196                        fault = new GeneralProtection(selector);
1197                    }
1198                } else {
1199                    panic("Interrupt CS checks not implemented "
1200                            "in legacy mode.\\n");
1201                }
1202                break;
1203              case SegTRCheck:
1204                if (!selector.si || selector.ti) {
1205                    fault = new GeneralProtection(selector);
1206                }
1207                break;
1208              case SegTSSCheck:
1209                if (!desc.p) {
1210                    fault = new SegmentNotPresent(selector);
1211                } else if (!(desc.type == 0x9 ||
1212                        (desc.type == 1 &&
1213                         m5reg.mode != LongMode))) {
1214                    fault = new GeneralProtection(selector);
1215                }
1216                break;
1217              case SegInGDTCheck:
1218                if (selector.ti) {
1219                    fault = new GeneralProtection(selector);
1220                }
1221                break;
1222              case SegLDTCheck:
1223                if (!desc.p) {
1224                    fault = new SegmentNotPresent(selector);
1225                } else if (desc.type != 0x2) {
1226                    fault = new GeneralProtection(selector);
1227                }
1228                break;
1229              default:
1230                panic("Undefined segment check type.\\n");
1231            }
1232        '''
1233        flag_code = '''
1234            // Check for a NULL selector and set ZF,EZF appropriately.
1235            ccFlagBits = ccFlagBits & ~(ext & (ZFBit | EZFBit));
1236            if (!selector.si && !selector.ti)
1237                ccFlagBits = ccFlagBits | (ext & (ZFBit | EZFBit));
1238        '''
1239
1240    class Wrdh(RegOp):
1241        code = '''
1242            SegDescriptor desc = SrcReg1;
1243
1244            uint64_t target = bits(SrcReg2, 31, 0) << 32;
1245            switch(desc.type) {
1246              case LDT64:
1247              case AvailableTSS64:
1248              case BusyTSS64:
1249                replaceBits(target, 23, 0, desc.baseLow);
1250                replaceBits(target, 31, 24, desc.baseHigh);
1251                break;
1252              case CallGate64:
1253              case IntGate64:
1254              case TrapGate64:
1255                replaceBits(target, 15, 0, bits(desc, 15, 0));
1256                replaceBits(target, 31, 16, bits(desc, 63, 48));
1257                break;
1258              default:
1259                panic("Wrdh used with wrong descriptor type!\\n");
1260            }
1261            DestReg = target;
1262        '''
1263
1264    class Wrtsc(WrRegOp):
1265        code = '''
1266            TscOp = psrc1;
1267        '''
1268
1269    class Rdtsc(RdRegOp):
1270        code = '''
1271            DestReg = TscOp;
1272        '''
1273
1274    class Rdm5reg(RdRegOp):
1275        code = '''
1276            DestReg = M5Reg;
1277        '''
1278
1279    class Wrdl(RegOp):
1280        code = '''
1281            SegDescriptor desc = SrcReg1;
1282            SegSelector selector = SrcReg2;
1283            if (selector.si || selector.ti) {
1284                if (!desc.p)
1285                    panic("Segment not present.\\n");
1286                SegAttr attr = 0;
1287                attr.dpl = desc.dpl;
1288                attr.unusable = 0;
1289                attr.defaultSize = desc.d;
1290                attr.longMode = desc.l;
1291                attr.avl = desc.avl;
1292                attr.granularity = desc.g;
1293                attr.present = desc.p;
1294                attr.system = desc.s;
1295                attr.type = desc.type;
1296                if (!desc.s) {
1297                    // The expand down bit happens to be set for gates.
1298                    if (desc.type.e) {
1299                        panic("Gate descriptor encountered.\\n");
1300                    }
1301                    attr.readable = 1;
1302                    attr.writable = 1;
1303                    attr.expandDown = 0;
1304                } else {
1305                    if (desc.type.codeOrData) {
1306                        attr.expandDown = 0;
1307                        attr.readable = desc.type.r;
1308                        attr.writable = 0;
1309                    } else {
1310                        attr.expandDown = desc.type.e;
1311                        attr.readable = 1;
1312                        attr.writable = desc.type.w;
1313                    }
1314                }
1315                Addr base = desc.baseLow | (desc.baseHigh << 24);
1316                Addr limit = desc.limitLow | (desc.limitHigh << 16);
1317                if (desc.g)
1318                    limit = (limit << 12) | mask(12);
1319                SegBaseDest = base;
1320                SegLimitDest = limit;
1321                SegAttrDest = attr;
1322            } else {
1323                SegBaseDest = SegBaseDest;
1324                SegLimitDest = SegLimitDest;
1325                SegAttrDest = SegAttrDest;
1326            }
1327        '''
1328}};
1329