regop.isa revision 7070:abdcb0389716
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, uint8_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, uint8_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, uint8_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, uint8_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                imm_name = "%simm8" % match.group("prefix")
328                self.buildCppClasses(name + "i", Name, suffix + "Imm",
329                        matcher.sub(imm_name, code),
330                        matcher.sub(imm_name, flag_code),
331                        matcher.sub(imm_name, cond_check),
332                        matcher.sub(imm_name, else_code))
333                return
334
335            # If there's something optional to do with flags, generate
336            # a version without it and fix up this version to use it.
337            if flag_code != "" or cond_check != "true":
338                self.buildCppClasses(name, Name, suffix,
339                        code, "", "true", else_code)
340                suffix = "Flags" + suffix
341
342            # If psrc1 or psrc2 is used, we need to actually insert code to
343            # compute it.
344            matcher = re.compile("(?<!\w)psrc1(?!\w)")
345            if matcher.search(allCode):
346                code = "uint64_t psrc1 = pick(SrcReg1, 0, dataSize);" + code
347            matcher = re.compile("(?<!\w)psrc2(?!\w)")
348            if matcher.search(allCode):
349                code = "uint64_t psrc2 = pick(SrcReg2, 1, dataSize);" + code
350            # Also make available versions which do sign extension
351            matcher = re.compile("(?<!\w)spsrc1(?!\w)")
352            if matcher.search(allCode):
353                code = "int64_t spsrc1 = signedPick(SrcReg1, 0, dataSize);" + code
354            matcher = re.compile("(?<!\w)spsrc2(?!\w)")
355            if matcher.search(allCode):
356                code = "int64_t spsrc2 = signedPick(SrcReg2, 1, dataSize);" + code
357            matcher = re.compile("(?<!\w)simm8(?!\w)")
358            if matcher.search(allCode):
359                code = "int8_t simm8 = imm8;" + code
360
361            base = "X86ISA::RegOp"
362
363            # If imm8 shows up in the code, use the immediate templates, if
364            # not, hopefully the register ones will be correct.
365            templates = regTemplates
366            matcher = re.compile("(?<!\w)s?imm8(?!\w)")
367            if matcher.search(allCode):
368                base += "Imm"
369                templates = immTemplates
370
371            # Get everything ready for the substitution
372            iop = InstObjParams(name, Name + suffix, base,
373                    {"code" : code,
374                     "flag_code" : flag_code,
375                     "cond_check" : cond_check,
376                     "else_code" : else_code})
377
378            # Generate the actual code (finally!)
379            header_output += templates[0].subst(iop)
380            decoder_output += templates[1].subst(iop)
381            exec_output += templates[2].subst(iop)
382
383
384        def __new__(mcls, Name, bases, dict):
385            abstract = False
386            name = Name.lower()
387            if "abstract" in dict:
388                abstract = dict['abstract']
389                del dict['abstract']
390
391            cls = super(RegOpMeta, mcls).__new__(mcls, Name, bases, dict)
392            if not abstract:
393                cls.className = Name
394                cls.base_mnemonic = name
395                code = cls.code
396                flag_code = cls.flag_code
397                cond_check = cls.cond_check
398                else_code = cls.else_code
399
400                # Set up the C++ classes
401                mcls.buildCppClasses(cls, name, Name, "",
402                        code, flag_code, cond_check, else_code)
403
404                # Hook into the microassembler dict
405                global microopClasses
406                microopClasses[name] = cls
407
408                allCode = "|".join((code, flag_code, cond_check, else_code))
409
410                # If op2 is used anywhere, make register and immediate versions
411                # of this code.
412                matcher = re.compile("op2(?P<typeQual>\\.\\w+)?")
413                if matcher.search(allCode):
414                    microopClasses[name + 'i'] = cls
415            return cls
416
417
418    class RegOp(X86Microop):
419        __metaclass__ = RegOpMeta
420        # This class itself doesn't act as a microop
421        abstract = True
422
423        # Default template parameter values
424        flag_code = ""
425        cond_check = "true"
426        else_code = ";"
427
428        def __init__(self, dest, src1, op2, flags = None, dataSize = "env.dataSize"):
429            self.dest = dest
430            self.src1 = src1
431            self.op2 = op2
432            self.flags = flags
433            self.dataSize = dataSize
434            if flags is None:
435                self.ext = 0
436            else:
437                if not isinstance(flags, (list, tuple)):
438                    raise Exception, "flags must be a list or tuple of flags"
439                self.ext = " | ".join(flags)
440                self.className += "Flags"
441
442        def getAllocator(self, *microFlags):
443            className = self.className
444            if self.mnemonic == self.base_mnemonic + 'i':
445                className += "Imm"
446            allocator = '''new %(class_name)s(machInst, macrocodeBlock
447                    %(flags)s, %(src1)s, %(op2)s, %(dest)s,
448                    %(dataSize)s, %(ext)s)''' % {
449                "class_name" : className,
450                "flags" : self.microFlagsText(microFlags),
451                "src1" : self.src1, "op2" : self.op2,
452                "dest" : self.dest,
453                "dataSize" : self.dataSize,
454                "ext" : self.ext}
455            return allocator
456
457    class LogicRegOp(RegOp):
458        abstract = True
459        flag_code = '''
460            //Don't have genFlags handle the OF or CF bits
461            uint64_t mask = CFBit | ECFBit | OFBit;
462            ccFlagBits = genFlags(ccFlagBits, ext & ~mask, DestReg, psrc1, op2);
463            //If a logic microop wants to set these, it wants to set them to 0.
464            ccFlagBits &= ~(CFBit & ext);
465            ccFlagBits &= ~(ECFBit & ext);
466            ccFlagBits &= ~(OFBit & ext);
467        '''
468
469    class FlagRegOp(RegOp):
470        abstract = True
471        flag_code = \
472            "ccFlagBits = genFlags(ccFlagBits, ext, DestReg, psrc1, op2);"
473
474    class SubRegOp(RegOp):
475        abstract = True
476        flag_code = \
477            "ccFlagBits = genFlags(ccFlagBits, ext, DestReg, psrc1, ~op2, true);"
478
479    class CondRegOp(RegOp):
480        abstract = True
481        cond_check = "checkCondition(ccFlagBits, ext)"
482
483    class RdRegOp(RegOp):
484        abstract = True
485        def __init__(self, dest, src1=None, dataSize="env.dataSize"):
486            if not src1:
487                src1 = dest
488            super(RdRegOp, self).__init__(dest, src1, \
489                    "InstRegIndex(NUM_INTREGS)", None, dataSize)
490
491    class WrRegOp(RegOp):
492        abstract = True
493        def __init__(self, src1, src2, flags=None, dataSize="env.dataSize"):
494            super(WrRegOp, self).__init__("InstRegIndex(NUM_INTREGS)", \
495                    src1, src2, flags, dataSize)
496
497    class Add(FlagRegOp):
498        code = 'DestReg = merge(DestReg, psrc1 + op2, dataSize);'
499
500    class Or(LogicRegOp):
501        code = 'DestReg = merge(DestReg, psrc1 | op2, dataSize);'
502
503    class Adc(FlagRegOp):
504        code = '''
505            CCFlagBits flags = ccFlagBits;
506            DestReg = merge(DestReg, psrc1 + op2 + flags.cf, dataSize);
507            '''
508
509    class Sbb(SubRegOp):
510        code = '''
511            CCFlagBits flags = ccFlagBits;
512            DestReg = merge(DestReg, psrc1 - op2 - flags.cf, dataSize);
513            '''
514
515    class And(LogicRegOp):
516        code = 'DestReg = merge(DestReg, psrc1 & op2, dataSize)'
517
518    class Sub(SubRegOp):
519        code = 'DestReg = merge(DestReg, psrc1 - op2, dataSize)'
520
521    class Xor(LogicRegOp):
522        code = 'DestReg = merge(DestReg, psrc1 ^ op2, dataSize)'
523
524    class Mul1s(WrRegOp):
525        code = '''
526            ProdLow = psrc1 * op2;
527            int halfSize = (dataSize * 8) / 2;
528            uint64_t shifter = (ULL(1) << halfSize);
529            uint64_t hiResult;
530            uint64_t psrc1_h = psrc1 / shifter;
531            uint64_t psrc1_l = psrc1 & mask(halfSize);
532            uint64_t psrc2_h = (op2 / shifter) & mask(halfSize);
533            uint64_t psrc2_l = op2 & mask(halfSize);
534            hiResult = ((psrc1_l * psrc2_h + psrc1_h * psrc2_l +
535                        ((psrc1_l * psrc2_l) / shifter)) /shifter) +
536                       psrc1_h * psrc2_h;
537            if (bits(psrc1, dataSize * 8 - 1))
538                hiResult -= op2;
539            if (bits(op2, dataSize * 8 - 1))
540                hiResult -= psrc1;
541            ProdHi = hiResult;
542            '''
543        flag_code = '''
544            if ((-ProdHi & mask(dataSize * 8)) !=
545                    bits(ProdLow, dataSize * 8 - 1)) {
546                ccFlagBits = ccFlagBits | (ext & (CFBit | OFBit | ECFBit));
547            } else {
548                ccFlagBits = ccFlagBits & ~(ext & (CFBit | OFBit | ECFBit));
549            }
550        '''
551
552    class Mul1u(WrRegOp):
553        code = '''
554            ProdLow = psrc1 * op2;
555            int halfSize = (dataSize * 8) / 2;
556            uint64_t shifter = (ULL(1) << halfSize);
557            uint64_t psrc1_h = psrc1 / shifter;
558            uint64_t psrc1_l = psrc1 & mask(halfSize);
559            uint64_t psrc2_h = (op2 / shifter) & mask(halfSize);
560            uint64_t psrc2_l = op2 & mask(halfSize);
561            ProdHi = ((psrc1_l * psrc2_h + psrc1_h * psrc2_l +
562                      ((psrc1_l * psrc2_l) / shifter)) / shifter) +
563                     psrc1_h * psrc2_h;
564            '''
565        flag_code = '''
566            if (ProdHi) {
567                ccFlagBits = ccFlagBits | (ext & (CFBit | OFBit | ECFBit));
568            } else {
569                ccFlagBits = ccFlagBits & ~(ext & (CFBit | OFBit | ECFBit));
570            }
571        '''
572
573    class Mulel(RdRegOp):
574        code = 'DestReg = merge(SrcReg1, ProdLow, dataSize);'
575
576    class Muleh(RdRegOp):
577        def __init__(self, dest, src1=None, flags=None, dataSize="env.dataSize"):
578            if not src1:
579                src1 = dest
580            super(RdRegOp, self).__init__(dest, src1, \
581                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
582        code = 'DestReg = merge(SrcReg1, ProdHi, dataSize);'
583
584    # One or two bit divide
585    class Div1(WrRegOp):
586        code = '''
587            //These are temporaries so that modifying them later won't make
588            //the ISA parser think they're also sources.
589            uint64_t quotient = 0;
590            uint64_t remainder = psrc1;
591            //Similarly, this is a temporary so changing it doesn't make it
592            //a source.
593            uint64_t divisor = op2;
594            //This is a temporary just for consistency and clarity.
595            uint64_t dividend = remainder;
596            //Do the division.
597            divide(dividend, divisor, quotient, remainder);
598            //Record the final results.
599            Remainder = remainder;
600            Quotient = quotient;
601            Divisor = divisor;
602            '''
603
604    # Step divide
605    class Div2(RegOp):
606        code = '''
607            uint64_t dividend = Remainder;
608            uint64_t divisor = Divisor;
609            uint64_t quotient = Quotient;
610            uint64_t remainder = dividend;
611            int remaining = op2;
612            //If we overshot, do nothing. This lets us unrool division loops a
613            //little.
614            if (remaining) {
615                if (divisor & (ULL(1) << 63)) {
616                    while (remaining && !(dividend & (ULL(1) << 63))) {
617                        dividend = (dividend << 1) |
618                            bits(SrcReg1, remaining - 1);
619                        quotient <<= 1;
620                        remaining--;
621                    }
622                    if (dividend & (ULL(1) << 63)) {
623                        if (dividend < divisor && remaining) {
624                            dividend = (dividend << 1) |
625                                bits(SrcReg1, remaining - 1);
626                            quotient <<= 1;
627                            remaining--;
628                        }
629                        quotient++;
630                        dividend -= divisor;
631                    }
632                    remainder = dividend;
633                } else {
634                    //Shift in bits from the low order portion of the dividend
635                    while (dividend < divisor && remaining) {
636                        dividend = (dividend << 1) |
637                            bits(SrcReg1, remaining - 1);
638                        quotient <<= 1;
639                        remaining--;
640                    }
641                    remainder = dividend;
642                    //Do the division.
643                    divide(dividend, divisor, quotient, remainder);
644                }
645            }
646            //Keep track of how many bits there are still to pull in.
647            DestReg = merge(DestReg, remaining, dataSize);
648            //Record the final results
649            Remainder = remainder;
650            Quotient = quotient;
651        '''
652        flag_code = '''
653            if (DestReg == 0)
654                ccFlagBits = ccFlagBits | (ext & EZFBit);
655            else
656                ccFlagBits = ccFlagBits & ~(ext & EZFBit);
657        '''
658
659    class Divq(RdRegOp):
660        code = 'DestReg = merge(SrcReg1, Quotient, dataSize);'
661
662    class Divr(RdRegOp):
663        code = 'DestReg = merge(SrcReg1, Remainder, dataSize);'
664
665    class Mov(CondRegOp):
666        code = 'DestReg = merge(SrcReg1, op2, dataSize)'
667        else_code = 'DestReg = DestReg;'
668
669    # Shift instructions
670
671    class Sll(RegOp):
672        code = '''
673            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
674            DestReg = merge(DestReg, psrc1 << shiftAmt, dataSize);
675            '''
676        flag_code = '''
677            // If the shift amount is zero, no flags should be modified.
678            if (shiftAmt) {
679                //Zero out any flags we might modify. This way we only have to
680                //worry about setting them.
681                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
682                int CFBits = 0;
683                //Figure out if we -would- set the CF bits if requested.
684                if (shiftAmt <= dataSize * 8 &&
685                        bits(SrcReg1, dataSize * 8 - shiftAmt)) {
686                    CFBits = 1;
687                }
688                //If some combination of the CF bits need to be set, set them.
689                if ((ext & (CFBit | ECFBit)) && CFBits)
690                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
691                //Figure out what the OF bit should be.
692                if ((ext & OFBit) && (CFBits ^ bits(DestReg, dataSize * 8 - 1)))
693                    ccFlagBits = ccFlagBits | OFBit;
694                //Use the regular mechanisms to calculate the other flags.
695                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
696                        DestReg, psrc1, op2);
697            }
698        '''
699
700    class Srl(RegOp):
701        code = '''
702            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
703            // Because what happens to the bits shift -in- on a right shift
704            // is not defined in the C/C++ standard, we have to mask them out
705            // to be sure they're zero.
706            uint64_t logicalMask = mask(dataSize * 8 - shiftAmt);
707            DestReg = merge(DestReg, (psrc1 >> shiftAmt) & logicalMask, dataSize);
708            '''
709        flag_code = '''
710            // If the shift amount is zero, no flags should be modified.
711            if (shiftAmt) {
712                //Zero out any flags we might modify. This way we only have to
713                //worry about setting them.
714                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
715                //If some combination of the CF bits need to be set, set them.
716                if ((ext & (CFBit | ECFBit)) && 
717                        shiftAmt <= dataSize * 8 &&
718                        bits(SrcReg1, shiftAmt - 1)) {
719                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
720                }
721                //Figure out what the OF bit should be.
722                if ((ext & OFBit) && bits(SrcReg1, dataSize * 8 - 1))
723                    ccFlagBits = ccFlagBits | OFBit;
724                //Use the regular mechanisms to calculate the other flags.
725                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
726                        DestReg, psrc1, op2);
727            }
728        '''
729
730    class Sra(RegOp):
731        code = '''
732            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
733            // Because what happens to the bits shift -in- on a right shift
734            // is not defined in the C/C++ standard, we have to sign extend
735            // them manually to be sure.
736            uint64_t arithMask = (shiftAmt == 0) ? 0 :
737                -bits(psrc1, dataSize * 8 - 1) << (dataSize * 8 - shiftAmt);
738            DestReg = merge(DestReg, (psrc1 >> shiftAmt) | arithMask, dataSize);
739            '''
740        flag_code = '''
741            // If the shift amount is zero, no flags should be modified.
742            if (shiftAmt) {
743                //Zero out any flags we might modify. This way we only have to
744                //worry about setting them.
745                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
746                //If some combination of the CF bits need to be set, set them.
747                uint8_t effectiveShift =
748                    (shiftAmt <= dataSize * 8) ? shiftAmt : (dataSize * 8);
749                if ((ext & (CFBit | ECFBit)) &&
750                        bits(SrcReg1, effectiveShift - 1)) {
751                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
752                }
753                //Use the regular mechanisms to calculate the other flags.
754                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
755                        DestReg, psrc1, op2);
756            }
757        '''
758
759    class Ror(RegOp):
760        code = '''
761            uint8_t shiftAmt =
762                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
763            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
764            if(realShiftAmt)
765            {
766                uint64_t top = psrc1 << (dataSize * 8 - realShiftAmt);
767                uint64_t bottom = bits(psrc1, dataSize * 8, realShiftAmt);
768                DestReg = merge(DestReg, top | bottom, dataSize);
769            }
770            else
771                DestReg = merge(DestReg, DestReg, dataSize);
772            '''
773        flag_code = '''
774            // If the shift amount is zero, no flags should be modified.
775            if (shiftAmt) {
776                //Zero out any flags we might modify. This way we only have to
777                //worry about setting them.
778                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
779                //Find the most and second most significant bits of the result.
780                int msb = bits(DestReg, dataSize * 8 - 1);
781                int smsb = bits(DestReg, dataSize * 8 - 2);
782                //If some combination of the CF bits need to be set, set them.
783                if ((ext & (CFBit | ECFBit)) && msb)
784                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
785                //Figure out what the OF bit should be.
786                if ((ext & OFBit) && (msb ^ smsb))
787                    ccFlagBits = ccFlagBits | OFBit;
788                //Use the regular mechanisms to calculate the other flags.
789                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
790                        DestReg, psrc1, op2);
791            }
792        '''
793
794    class Rcr(RegOp):
795        code = '''
796            uint8_t shiftAmt =
797                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
798            uint8_t realShiftAmt = shiftAmt % (dataSize * 8 + 1);
799            if(realShiftAmt)
800            {
801                CCFlagBits flags = ccFlagBits;
802                uint64_t top = flags.cf << (dataSize * 8 - realShiftAmt);
803                if (realShiftAmt > 1)
804                    top |= psrc1 << (dataSize * 8 - realShiftAmt + 1);
805                uint64_t bottom = bits(psrc1, dataSize * 8 - 1, realShiftAmt);
806                DestReg = merge(DestReg, top | bottom, dataSize);
807            }
808            else
809                DestReg = merge(DestReg, DestReg, dataSize);
810            '''
811        flag_code = '''
812            // If the shift amount is zero, no flags should be modified.
813            if (shiftAmt) {
814                int origCFBit = (ccFlagBits & CFBit) ? 1 : 0;
815                //Zero out any flags we might modify. This way we only have to
816                //worry about setting them.
817                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
818                //Figure out what the OF bit should be.
819                if ((ext & OFBit) && (origCFBit ^
820                                      bits(SrcReg1, dataSize * 8 - 1))) {
821                    ccFlagBits = ccFlagBits | OFBit;
822                }
823                //If some combination of the CF bits need to be set, set them.
824                if ((ext & (CFBit | ECFBit)) &&
825                        (realShiftAmt == 0) ? origCFBit :
826                        bits(SrcReg1, realShiftAmt - 1)) {
827                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
828                }
829                //Use the regular mechanisms to calculate the other flags.
830                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
831                        DestReg, psrc1, op2);
832            }
833        '''
834
835    class Rol(RegOp):
836        code = '''
837            uint8_t shiftAmt =
838                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
839            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
840            if(realShiftAmt)
841            {
842                uint64_t top = psrc1 << realShiftAmt;
843                uint64_t bottom =
844                    bits(psrc1, dataSize * 8 - 1, dataSize * 8 - realShiftAmt);
845                DestReg = merge(DestReg, top | bottom, dataSize);
846            }
847            else
848                DestReg = merge(DestReg, DestReg, dataSize);
849            '''
850        flag_code = '''
851            // If the shift amount is zero, no flags should be modified.
852            if (shiftAmt) {
853                //Zero out any flags we might modify. This way we only have to
854                //worry about setting them.
855                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
856                //The CF bits, if set, would be set to the lsb of the result.
857                int lsb = DestReg & 0x1;
858                int msb = bits(DestReg, dataSize * 8 - 1);
859                //If some combination of the CF bits need to be set, set them.
860                if ((ext & (CFBit | ECFBit)) && lsb)
861                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
862                //Figure out what the OF bit should be.
863                if ((ext & OFBit) && (msb ^ lsb))
864                    ccFlagBits = ccFlagBits | OFBit;
865                //Use the regular mechanisms to calculate the other flags.
866                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
867                        DestReg, psrc1, op2);
868            }
869        '''
870
871    class Rcl(RegOp):
872        code = '''
873            uint8_t shiftAmt =
874                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
875            uint8_t realShiftAmt = shiftAmt % (dataSize * 8 + 1);
876            if(realShiftAmt)
877            {
878                CCFlagBits flags = ccFlagBits;
879                uint64_t top = psrc1 << realShiftAmt;
880                uint64_t bottom = flags.cf << (realShiftAmt - 1);
881                if(shiftAmt > 1)
882                    bottom |=
883                        bits(psrc1, dataSize * 8 - 1,
884                                   dataSize * 8 - realShiftAmt + 1);
885                DestReg = merge(DestReg, top | bottom, dataSize);
886            }
887            else
888                DestReg = merge(DestReg, DestReg, dataSize);
889            '''
890        flag_code = '''
891            // If the shift amount is zero, no flags should be modified.
892            if (shiftAmt) {
893                int origCFBit = (ccFlagBits & CFBit) ? 1 : 0;
894                //Zero out any flags we might modify. This way we only have to
895                //worry about setting them.
896                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
897                int msb = bits(DestReg, dataSize * 8 - 1);
898                int CFBits = bits(SrcReg1, dataSize * 8 - realShiftAmt);
899                //If some combination of the CF bits need to be set, set them.
900                if ((ext & (CFBit | ECFBit)) && 
901                        (realShiftAmt == 0) ? origCFBit : CFBits)
902                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
903                //Figure out what the OF bit should be.
904                if ((ext & OFBit) && (msb ^ CFBits))
905                    ccFlagBits = ccFlagBits | OFBit;
906                //Use the regular mechanisms to calculate the other flags.
907                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
908                        DestReg, psrc1, op2);
909            }
910        '''
911
912    class Sld(RegOp):
913        code = '''
914            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
915            uint8_t dataBits = dataSize * 8;
916            uint8_t realShiftAmt = shiftAmt % (2 * dataBits);
917            uint64_t result;
918            if (realShiftAmt == 0) {
919                result = psrc1;
920            } else if (realShiftAmt < dataBits) {
921                result = (psrc1 << realShiftAmt) |
922                         (DoubleBits >> (dataBits - realShiftAmt));
923            } else {
924                result = (DoubleBits << (realShiftAmt - dataBits)) |
925                         (psrc1 >> (2 * dataBits - realShiftAmt));
926            }
927            DestReg = merge(DestReg, result, dataSize);
928            '''
929        flag_code = '''
930            // If the shift amount is zero, no flags should be modified.
931            if (shiftAmt) {
932                //Zero out any flags we might modify. This way we only have to
933                //worry about setting them.
934                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
935                int CFBits = 0;
936                //Figure out if we -would- set the CF bits if requested.
937                if ((realShiftAmt == 0 &&
938                        bits(DoubleBits, 0)) ||
939                    (realShiftAmt <= dataBits &&
940                     bits(SrcReg1, dataBits - realShiftAmt)) ||
941                    (realShiftAmt > dataBits &&
942                     bits(DoubleBits, 2 * dataBits - realShiftAmt))) {
943                    CFBits = 1;
944                }
945                //If some combination of the CF bits need to be set, set them.
946                if ((ext & (CFBit | ECFBit)) && CFBits)
947                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
948                //Figure out what the OF bit should be.
949                if ((ext & OFBit) && (bits(SrcReg1, dataBits - 1) ^
950                                      bits(result, dataBits - 1)))
951                    ccFlagBits = ccFlagBits | OFBit;
952                //Use the regular mechanisms to calculate the other flags.
953                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
954                        DestReg, psrc1, op2);
955            }
956        '''
957
958    class Srd(RegOp):
959        code = '''
960            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
961            uint8_t dataBits = dataSize * 8;
962            uint8_t realShiftAmt = shiftAmt % (2 * dataBits);
963            uint64_t result;
964            if (realShiftAmt == 0) {
965                result = psrc1;
966            } else if (realShiftAmt < dataBits) {
967                // Because what happens to the bits shift -in- on a right
968                // shift is not defined in the C/C++ standard, we have to
969                // mask them out to be sure they're zero.
970                uint64_t logicalMask = mask(dataBits - realShiftAmt);
971                result = ((psrc1 >> realShiftAmt) & logicalMask) |
972                         (DoubleBits << (dataBits - realShiftAmt));
973            } else {
974                uint64_t logicalMask = mask(2 * dataBits - realShiftAmt);
975                result = ((DoubleBits >> (realShiftAmt - dataBits)) &
976                          logicalMask) |
977                         (psrc1 << (2 * dataBits - realShiftAmt));
978            }
979            DestReg = merge(DestReg, result, dataSize);
980            '''
981        flag_code = '''
982            // If the shift amount is zero, no flags should be modified.
983            if (shiftAmt) {
984                //Zero out any flags we might modify. This way we only have to
985                //worry about setting them.
986                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
987                int CFBits = 0;
988                //If some combination of the CF bits need to be set, set them.
989                if ((realShiftAmt == 0 &&
990                            bits(DoubleBits, dataBits - 1)) ||
991                        (realShiftAmt <= dataBits &&
992                         bits(SrcReg1, realShiftAmt - 1)) ||
993                        (realShiftAmt > dataBits &&
994                         bits(DoubleBits, realShiftAmt - dataBits - 1))) {
995                    CFBits = 1;
996                }
997                //If some combination of the CF bits need to be set, set them.
998                if ((ext & (CFBit | ECFBit)) && CFBits)
999                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
1000                //Figure out what the OF bit should be.
1001                if ((ext & OFBit) && (bits(SrcReg1, dataBits - 1) ^
1002                                      bits(result, dataBits - 1)))
1003                    ccFlagBits = ccFlagBits | OFBit;
1004                //Use the regular mechanisms to calculate the other flags.
1005                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
1006                        DestReg, psrc1, op2);
1007            }
1008        '''
1009
1010    class Mdb(WrRegOp):
1011        code = 'DoubleBits = psrc1 ^ op2;'
1012
1013    class Wrip(WrRegOp, CondRegOp):
1014        code = 'RIP = psrc1 + sop2 + CSBase'
1015        else_code="RIP = RIP;"
1016
1017    class Wruflags(WrRegOp):
1018        code = 'ccFlagBits = psrc1 ^ op2'
1019
1020    class Wrflags(WrRegOp):
1021        code = '''
1022            MiscReg newFlags = psrc1 ^ op2;
1023            MiscReg userFlagMask = 0xDD5;
1024            // Get only the user flags
1025            ccFlagBits = newFlags & userFlagMask;
1026            // Get everything else
1027            nccFlagBits = newFlags & ~userFlagMask;
1028        '''
1029
1030    class Rdip(RdRegOp):
1031        code = 'DestReg = RIP - CSBase'
1032
1033    class Ruflags(RdRegOp):
1034        code = 'DestReg = ccFlagBits'
1035
1036    class Rflags(RdRegOp):
1037        code = 'DestReg = ccFlagBits | nccFlagBits'
1038
1039    class Ruflag(RegOp):
1040        code = '''
1041            int flag = bits(ccFlagBits, imm8);
1042            DestReg = merge(DestReg, flag, dataSize);
1043            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
1044                                       (ccFlagBits & ~EZFBit);
1045            '''
1046        def __init__(self, dest, imm, flags=None, \
1047                dataSize="env.dataSize"):
1048            super(Ruflag, self).__init__(dest, \
1049                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
1050
1051    class Rflag(RegOp):
1052        code = '''
1053            MiscReg flagMask = 0x3F7FDD5;
1054            MiscReg flags = (nccFlagBits | ccFlagBits) & flagMask;
1055            int flag = bits(flags, imm8);
1056            DestReg = merge(DestReg, flag, dataSize);
1057            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
1058                                       (ccFlagBits & ~EZFBit);
1059            '''
1060        def __init__(self, dest, imm, flags=None, \
1061                dataSize="env.dataSize"):
1062            super(Rflag, self).__init__(dest, \
1063                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
1064
1065    class Sext(RegOp):
1066        code = '''
1067            IntReg val = psrc1;
1068            // Mask the bit position so that it wraps.
1069            int bitPos = op2 & (dataSize * 8 - 1);
1070            int sign_bit = bits(val, bitPos, bitPos);
1071            uint64_t maskVal = mask(bitPos+1);
1072            val = sign_bit ? (val | ~maskVal) : (val & maskVal);
1073            DestReg = merge(DestReg, val, dataSize);
1074            '''
1075        flag_code = '''
1076            if (!sign_bit)
1077                ccFlagBits = ccFlagBits &
1078                    ~(ext & (CFBit | ECFBit | ZFBit | EZFBit));
1079            else
1080                ccFlagBits = ccFlagBits |
1081                    (ext & (CFBit | ECFBit | ZFBit | EZFBit));
1082            '''
1083
1084    class Zext(RegOp):
1085        code = 'DestReg = merge(DestReg, bits(psrc1, op2, 0), dataSize);'
1086
1087    class Rddr(RegOp):
1088        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1089            super(Rddr, self).__init__(dest, \
1090                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1091        code = '''
1092            CR4 cr4 = CR4Op;
1093            DR7 dr7 = DR7Op;
1094            if ((cr4.de == 1 && (src1 == 4 || src1 == 5)) || src1 >= 8) {
1095                fault = new InvalidOpcode();
1096            } else if (dr7.gd) {
1097                fault = new DebugException();
1098            } else {
1099                DestReg = merge(DestReg, DebugSrc1, dataSize);
1100            }
1101        '''
1102
1103    class Wrdr(RegOp):
1104        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1105            super(Wrdr, self).__init__(dest, \
1106                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1107        code = '''
1108            CR4 cr4 = CR4Op;
1109            DR7 dr7 = DR7Op;
1110            if ((cr4.de == 1 && (dest == 4 || dest == 5)) || dest >= 8) {
1111                fault = new InvalidOpcode();
1112            } else if ((dest == 6 || dest == 7) && bits(psrc1, 63, 32) &&
1113                    machInst.mode.mode == LongMode) {
1114                fault = new GeneralProtection(0);
1115            } else if (dr7.gd) {
1116                fault = new DebugException();
1117            } else {
1118                DebugDest = psrc1;
1119            }
1120        '''
1121
1122    class Rdcr(RegOp):
1123        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1124            super(Rdcr, self).__init__(dest, \
1125                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1126        code = '''
1127            if (src1 == 1 || (src1 > 4 && src1 < 8) || (src1 > 8)) {
1128                fault = new InvalidOpcode();
1129            } else {
1130                DestReg = merge(DestReg, ControlSrc1, dataSize);
1131            }
1132        '''
1133
1134    class Wrcr(RegOp):
1135        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1136            super(Wrcr, self).__init__(dest, \
1137                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1138        code = '''
1139            if (dest == 1 || (dest > 4 && dest < 8) || (dest > 8)) {
1140                fault = new InvalidOpcode();
1141            } else {
1142                // There are *s in the line below so it doesn't confuse the
1143                // parser. They may be unnecessary.
1144                //Mis*cReg old*Val = pick(Cont*rolDest, 0, dat*aSize);
1145                MiscReg newVal = psrc1;
1146
1147                // Check for any modifications that would cause a fault.
1148                switch(dest) {
1149                  case 0:
1150                    {
1151                        Efer efer = EferOp;
1152                        CR0 cr0 = newVal;
1153                        CR4 oldCr4 = CR4Op;
1154                        if (bits(newVal, 63, 32) ||
1155                                (!cr0.pe && cr0.pg) ||
1156                                (!cr0.cd && cr0.nw) ||
1157                                (cr0.pg && efer.lme && !oldCr4.pae))
1158                            fault = new GeneralProtection(0);
1159                    }
1160                    break;
1161                  case 2:
1162                    break;
1163                  case 3:
1164                    break;
1165                  case 4:
1166                    {
1167                        CR4 cr4 = newVal;
1168                        // PAE can't be disabled in long mode.
1169                        if (bits(newVal, 63, 11) ||
1170                                (machInst.mode.mode == LongMode && !cr4.pae))
1171                            fault = new GeneralProtection(0);
1172                    }
1173                    break;
1174                  case 8:
1175                    {
1176                        if (bits(newVal, 63, 4))
1177                            fault = new GeneralProtection(0);
1178                    }
1179                  default:
1180                    panic("Unrecognized control register %d.\\n", dest);
1181                }
1182                ControlDest = newVal;
1183            }
1184            '''
1185
1186    # Microops for manipulating segmentation registers
1187    class SegOp(CondRegOp):
1188        abstract = True
1189        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1190            super(SegOp, self).__init__(dest, \
1191                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1192
1193    class Wrbase(SegOp):
1194        code = '''
1195            SegBaseDest = psrc1;
1196        '''
1197
1198    class Wrlimit(SegOp):
1199        code = '''
1200            SegLimitDest = psrc1;
1201        '''
1202
1203    class Wrsel(SegOp):
1204        code = '''
1205            SegSelDest = psrc1;
1206        '''
1207
1208    class WrAttr(SegOp):
1209        code = '''
1210            SegAttrDest = psrc1;
1211        '''
1212
1213    class Rdbase(SegOp):
1214        code = '''
1215            DestReg = merge(DestReg, SegBaseSrc1, dataSize);
1216        '''
1217
1218    class Rdlimit(SegOp):
1219        code = '''
1220            DestReg = merge(DestReg, SegLimitSrc1, dataSize);
1221        '''
1222
1223    class RdAttr(SegOp):
1224        code = '''
1225            DestReg = merge(DestReg, SegAttrSrc1, dataSize);
1226        '''
1227
1228    class Rdsel(SegOp):
1229        code = '''
1230            DestReg = merge(DestReg, SegSelSrc1, dataSize);
1231        '''
1232
1233    class Rdval(RegOp):
1234        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1235            super(Rdval, self).__init__(dest, src1, \
1236                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1237        code = '''
1238            DestReg = MiscRegSrc1;
1239        '''
1240
1241    class Wrval(RegOp):
1242        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1243            super(Wrval, self).__init__(dest, src1, \
1244                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1245        code = '''
1246            MiscRegDest = SrcReg1;
1247        '''
1248
1249    class Chks(RegOp):
1250        def __init__(self, dest, src1, src2=0,
1251                flags=None, dataSize="env.dataSize"):
1252            super(Chks, self).__init__(dest,
1253                    src1, src2, flags, dataSize)
1254        code = '''
1255            // The selector is in source 1 and can be at most 16 bits.
1256            SegSelector selector = DestReg;
1257            SegDescriptor desc = SrcReg1;
1258            HandyM5Reg m5reg = M5Reg;
1259
1260            switch (imm8)
1261            {
1262              case SegNoCheck:
1263                break;
1264              case SegCSCheck:
1265                // Make sure it's the right type
1266                if (desc.s == 0 || desc.type.codeOrData != 1) {
1267                    fault = new GeneralProtection(0);
1268                } else if (m5reg.cpl != desc.dpl) {
1269                    fault = new GeneralProtection(0);
1270                }
1271                break;
1272              case SegCallGateCheck:
1273                panic("CS checks for far calls/jumps through call gates"
1274                        "not implemented.\\n");
1275                break;
1276              case SegSoftIntGateCheck:
1277                // Check permissions.
1278                if (desc.dpl < m5reg.cpl) {
1279                    fault = new GeneralProtection(selector);
1280                    break;
1281                }
1282                // Fall through on purpose
1283              case SegIntGateCheck:
1284                // Make sure the gate's the right type.
1285                if ((m5reg.mode == LongMode && (desc.type & 0xe) != 0xe) ||
1286                        ((desc.type & 0x6) != 0x6)) {
1287                    fault = new GeneralProtection(0);
1288                }
1289                break;
1290              case SegSSCheck:
1291                if (selector.si || selector.ti) {
1292                    if (!desc.p) {
1293                        fault = new StackFault(selector);
1294                    }
1295                } else {
1296                    if ((m5reg.submode != SixtyFourBitMode ||
1297                                m5reg.cpl == 3) ||
1298                            !(desc.s == 1 &&
1299                            desc.type.codeOrData == 0 && desc.type.w) ||
1300                            (desc.dpl != m5reg.cpl) ||
1301                            (selector.rpl != m5reg.cpl)) {
1302                        fault = new GeneralProtection(selector);
1303                    }
1304                }
1305                break;
1306              case SegIretCheck:
1307                {
1308                    if ((!selector.si && !selector.ti) ||
1309                            (selector.rpl < m5reg.cpl) ||
1310                            !(desc.s == 1 && desc.type.codeOrData == 1) ||
1311                            (!desc.type.c && desc.dpl != selector.rpl) ||
1312                            (desc.type.c && desc.dpl > selector.rpl)) {
1313                        fault = new GeneralProtection(selector);
1314                    } else if (!desc.p) {
1315                        fault = new SegmentNotPresent(selector);
1316                    }
1317                    break;
1318                }
1319              case SegIntCSCheck:
1320                if (m5reg.mode == LongMode) {
1321                    if (desc.l != 1 || desc.d != 0) {
1322                        fault = new GeneralProtection(selector);
1323                    }
1324                } else {
1325                    panic("Interrupt CS checks not implemented "
1326                            "in legacy mode.\\n");
1327                }
1328                break;
1329              case SegTRCheck:
1330                if (!selector.si || selector.ti) {
1331                    fault = new GeneralProtection(selector);
1332                }
1333                break;
1334              case SegTSSCheck:
1335                if (!desc.p) {
1336                    fault = new SegmentNotPresent(selector);
1337                } else if (!(desc.type == 0x9 ||
1338                        (desc.type == 1 &&
1339                         m5reg.mode != LongMode))) {
1340                    fault = new GeneralProtection(selector);
1341                }
1342                break;
1343              case SegInGDTCheck:
1344                if (selector.ti) {
1345                    fault = new GeneralProtection(selector);
1346                }
1347                break;
1348              case SegLDTCheck:
1349                if (!desc.p) {
1350                    fault = new SegmentNotPresent(selector);
1351                } else if (desc.type != 0x2) {
1352                    fault = new GeneralProtection(selector);
1353                }
1354                break;
1355              default:
1356                panic("Undefined segment check type.\\n");
1357            }
1358        '''
1359        flag_code = '''
1360            // Check for a NULL selector and set ZF,EZF appropriately.
1361            ccFlagBits = ccFlagBits & ~(ext & (ZFBit | EZFBit));
1362            if (!selector.si && !selector.ti)
1363                ccFlagBits = ccFlagBits | (ext & (ZFBit | EZFBit));
1364        '''
1365
1366    class Wrdh(RegOp):
1367        code = '''
1368            SegDescriptor desc = SrcReg1;
1369
1370            uint64_t target = bits(SrcReg2, 31, 0) << 32;
1371            switch(desc.type) {
1372              case LDT64:
1373              case AvailableTSS64:
1374              case BusyTSS64:
1375                replaceBits(target, 23, 0, desc.baseLow);
1376                replaceBits(target, 31, 24, desc.baseHigh);
1377                break;
1378              case CallGate64:
1379              case IntGate64:
1380              case TrapGate64:
1381                replaceBits(target, 15, 0, bits(desc, 15, 0));
1382                replaceBits(target, 31, 16, bits(desc, 63, 48));
1383                break;
1384              default:
1385                panic("Wrdh used with wrong descriptor type!\\n");
1386            }
1387            DestReg = target;
1388        '''
1389
1390    class Wrtsc(WrRegOp):
1391        code = '''
1392            TscOp = psrc1;
1393        '''
1394
1395    class Rdtsc(RdRegOp):
1396        code = '''
1397            DestReg = TscOp;
1398        '''
1399
1400    class Rdm5reg(RdRegOp):
1401        code = '''
1402            DestReg = M5Reg;
1403        '''
1404
1405    class Wrdl(RegOp):
1406        code = '''
1407            SegDescriptor desc = SrcReg1;
1408            SegSelector selector = SrcReg2;
1409            if (selector.si || selector.ti) {
1410                if (!desc.p)
1411                    panic("Segment not present.\\n");
1412                SegAttr attr = 0;
1413                attr.dpl = desc.dpl;
1414                attr.unusable = 0;
1415                attr.defaultSize = desc.d;
1416                attr.longMode = desc.l;
1417                attr.avl = desc.avl;
1418                attr.granularity = desc.g;
1419                attr.present = desc.p;
1420                attr.system = desc.s;
1421                attr.type = desc.type;
1422                if (!desc.s) {
1423                    // The expand down bit happens to be set for gates.
1424                    if (desc.type.e) {
1425                        panic("Gate descriptor encountered.\\n");
1426                    }
1427                    attr.readable = 1;
1428                    attr.writable = 1;
1429                    attr.expandDown = 0;
1430                } else {
1431                    if (desc.type.codeOrData) {
1432                        attr.expandDown = 0;
1433                        attr.readable = desc.type.r;
1434                        attr.writable = 0;
1435                    } else {
1436                        attr.expandDown = desc.type.e;
1437                        attr.readable = 1;
1438                        attr.writable = desc.type.w;
1439                    }
1440                }
1441                Addr base = desc.baseLow | (desc.baseHigh << 24);
1442                Addr limit = desc.limitLow | (desc.limitHigh << 16);
1443                if (desc.g)
1444                    limit = (limit << 12) | mask(12);
1445                SegBaseDest = base;
1446                SegLimitDest = limit;
1447                SegAttrDest = attr;
1448            } else {
1449                SegBaseDest = SegBaseDest;
1450                SegLimitDest = SegLimitDest;
1451                SegAttrDest = SegAttrDest;
1452            }
1453        '''
1454}};
1455