Don't provide two different definitions of ModRMDecision, OpcodeDecision, and Context...
[oota-llvm.git] / lib / Target / X86 / Disassembler / X86DisassemblerDecoder.cpp
1 //===-- X86DisassemblerDecoder.c - Disassembler decoder -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is part of the X86 Disassembler.
11 // It contains the implementation of the instruction decoder.
12 // Documentation for the disassembler can be found in X86Disassembler.h.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include <stdarg.h>   /* for va_*()       */
17 #include <stdio.h>    /* for vsnprintf()  */
18 #include <stdlib.h>   /* for exit()       */
19 #include <string.h>   /* for memset()     */
20
21 #include "X86DisassemblerDecoder.h"
22
23 using namespace llvm::X86Disassembler;
24
25 /// Specifies whether a ModR/M byte is needed and (if so) which
26 /// instruction each possible value of the ModR/M byte corresponds to.  Once
27 /// this information is known, we have narrowed down to a single instruction.
28 struct ModRMDecision {
29   uint8_t modrm_type;
30   uint16_t instructionIDs;
31 };
32
33 /// Specifies which set of ModR/M->instruction tables to look at
34 /// given a particular opcode.
35 struct OpcodeDecision {
36   ModRMDecision modRMDecisions[256];
37 };
38
39 /// Specifies which opcode->instruction tables to look at given
40 /// a particular context (set of attributes).  Since there are many possible
41 /// contexts, the decoder first uses CONTEXTS_SYM to determine which context
42 /// applies given a specific set of attributes.  Hence there are only IC_max
43 /// entries in this table, rather than 2^(ATTR_max).
44 struct ContextDecision {
45   OpcodeDecision opcodeDecisions[IC_max];
46 };
47
48 #include "X86GenDisassemblerTables.inc"
49
50 #define TRUE  1
51 #define FALSE 0
52
53 #ifndef NDEBUG
54 #define debug(s) do { Debug(__FILE__, __LINE__, s); } while (0)
55 #else
56 #define debug(s) do { } while (0)
57 #endif
58
59
60 /*
61  * contextForAttrs - Client for the instruction context table.  Takes a set of
62  *   attributes and returns the appropriate decode context.
63  *
64  * @param attrMask  - Attributes, from the enumeration attributeBits.
65  * @return          - The InstructionContext to use when looking up an
66  *                    an instruction with these attributes.
67  */
68 static InstructionContext contextForAttrs(uint16_t attrMask) {
69   return static_cast<InstructionContext>(CONTEXTS_SYM[attrMask]);
70 }
71
72 /*
73  * modRMRequired - Reads the appropriate instruction table to determine whether
74  *   the ModR/M byte is required to decode a particular instruction.
75  *
76  * @param type        - The opcode type (i.e., how many bytes it has).
77  * @param insnContext - The context for the instruction, as returned by
78  *                      contextForAttrs.
79  * @param opcode      - The last byte of the instruction's opcode, not counting
80  *                      ModR/M extensions and escapes.
81  * @return            - TRUE if the ModR/M byte is required, FALSE otherwise.
82  */
83 static int modRMRequired(OpcodeType type,
84                          InstructionContext insnContext,
85                          uint16_t opcode) {
86   const struct ContextDecision* decision = 0;
87
88   switch (type) {
89   case ONEBYTE:
90     decision = &ONEBYTE_SYM;
91     break;
92   case TWOBYTE:
93     decision = &TWOBYTE_SYM;
94     break;
95   case THREEBYTE_38:
96     decision = &THREEBYTE38_SYM;
97     break;
98   case THREEBYTE_3A:
99     decision = &THREEBYTE3A_SYM;
100     break;
101   case XOP8_MAP:
102     decision = &XOP8_MAP_SYM;
103     break;
104   case XOP9_MAP:
105     decision = &XOP9_MAP_SYM;
106     break;
107   case XOPA_MAP:
108     decision = &XOPA_MAP_SYM;
109     break;
110   }
111
112   return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
113     modrm_type != MODRM_ONEENTRY;
114 }
115
116 /*
117  * decode - Reads the appropriate instruction table to obtain the unique ID of
118  *   an instruction.
119  *
120  * @param type        - See modRMRequired().
121  * @param insnContext - See modRMRequired().
122  * @param opcode      - See modRMRequired().
123  * @param modRM       - The ModR/M byte if required, or any value if not.
124  * @return            - The UID of the instruction, or 0 on failure.
125  */
126 static InstrUID decode(OpcodeType type,
127                        InstructionContext insnContext,
128                        uint8_t opcode,
129                        uint8_t modRM) {
130   const struct ModRMDecision* dec = 0;
131
132   switch (type) {
133   case ONEBYTE:
134     dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
135     break;
136   case TWOBYTE:
137     dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
138     break;
139   case THREEBYTE_38:
140     dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
141     break;
142   case THREEBYTE_3A:
143     dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
144     break;
145   case XOP8_MAP:
146     dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
147     break;
148   case XOP9_MAP:
149     dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
150     break;
151   case XOPA_MAP:
152     dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
153     break;
154   }
155
156   switch (dec->modrm_type) {
157   default:
158     debug("Corrupt table!  Unknown modrm_type");
159     return 0;
160   case MODRM_ONEENTRY:
161     return modRMTable[dec->instructionIDs];
162   case MODRM_SPLITRM:
163     if (modFromModRM(modRM) == 0x3)
164       return modRMTable[dec->instructionIDs+1];
165     return modRMTable[dec->instructionIDs];
166   case MODRM_SPLITREG:
167     if (modFromModRM(modRM) == 0x3)
168       return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
169     return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
170   case MODRM_SPLITMISC:
171     if (modFromModRM(modRM) == 0x3)
172       return modRMTable[dec->instructionIDs+(modRM & 0x3f)+8];
173     return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
174   case MODRM_FULL:
175     return modRMTable[dec->instructionIDs+modRM];
176   }
177 }
178
179 /*
180  * specifierForUID - Given a UID, returns the name and operand specification for
181  *   that instruction.
182  *
183  * @param uid - The unique ID for the instruction.  This should be returned by
184  *              decode(); specifierForUID will not check bounds.
185  * @return    - A pointer to the specification for that instruction.
186  */
187 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
188   return &INSTRUCTIONS_SYM[uid];
189 }
190
191 /*
192  * consumeByte - Uses the reader function provided by the user to consume one
193  *   byte from the instruction's memory and advance the cursor.
194  *
195  * @param insn  - The instruction with the reader function to use.  The cursor
196  *                for this instruction is advanced.
197  * @param byte  - A pointer to a pre-allocated memory buffer to be populated
198  *                with the data read.
199  * @return      - 0 if the read was successful; nonzero otherwise.
200  */
201 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
202   int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
203
204   if (!ret)
205     ++(insn->readerCursor);
206
207   return ret;
208 }
209
210 /*
211  * lookAtByte - Like consumeByte, but does not advance the cursor.
212  *
213  * @param insn  - See consumeByte().
214  * @param byte  - See consumeByte().
215  * @return      - See consumeByte().
216  */
217 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
218   return insn->reader(insn->readerArg, byte, insn->readerCursor);
219 }
220
221 static void unconsumeByte(struct InternalInstruction* insn) {
222   insn->readerCursor--;
223 }
224
225 #define CONSUME_FUNC(name, type)                                  \
226   static int name(struct InternalInstruction* insn, type* ptr) {  \
227     type combined = 0;                                            \
228     unsigned offset;                                              \
229     for (offset = 0; offset < sizeof(type); ++offset) {           \
230       uint8_t byte;                                               \
231       int ret = insn->reader(insn->readerArg,                     \
232                              &byte,                               \
233                              insn->readerCursor + offset);        \
234       if (ret)                                                    \
235         return ret;                                               \
236       combined = combined | ((uint64_t)byte << (offset * 8));     \
237     }                                                             \
238     *ptr = combined;                                              \
239     insn->readerCursor += sizeof(type);                           \
240     return 0;                                                     \
241   }
242
243 /*
244  * consume* - Use the reader function provided by the user to consume data
245  *   values of various sizes from the instruction's memory and advance the
246  *   cursor appropriately.  These readers perform endian conversion.
247  *
248  * @param insn    - See consumeByte().
249  * @param ptr     - A pointer to a pre-allocated memory of appropriate size to
250  *                  be populated with the data read.
251  * @return        - See consumeByte().
252  */
253 CONSUME_FUNC(consumeInt8, int8_t)
254 CONSUME_FUNC(consumeInt16, int16_t)
255 CONSUME_FUNC(consumeInt32, int32_t)
256 CONSUME_FUNC(consumeUInt16, uint16_t)
257 CONSUME_FUNC(consumeUInt32, uint32_t)
258 CONSUME_FUNC(consumeUInt64, uint64_t)
259
260 /*
261  * dbgprintf - Uses the logging function provided by the user to log a single
262  *   message, typically without a carriage-return.
263  *
264  * @param insn    - The instruction containing the logging function.
265  * @param format  - See printf().
266  * @param ...     - See printf().
267  */
268 static void dbgprintf(struct InternalInstruction* insn,
269                       const char* format,
270                       ...) {
271   char buffer[256];
272   va_list ap;
273
274   if (!insn->dlog)
275     return;
276
277   va_start(ap, format);
278   (void)vsnprintf(buffer, sizeof(buffer), format, ap);
279   va_end(ap);
280
281   insn->dlog(insn->dlogArg, buffer);
282
283   return;
284 }
285
286 /*
287  * setPrefixPresent - Marks that a particular prefix is present at a particular
288  *   location.
289  *
290  * @param insn      - The instruction to be marked as having the prefix.
291  * @param prefix    - The prefix that is present.
292  * @param location  - The location where the prefix is located (in the address
293  *                    space of the instruction's reader).
294  */
295 static void setPrefixPresent(struct InternalInstruction* insn,
296                                     uint8_t prefix,
297                                     uint64_t location)
298 {
299   insn->prefixPresent[prefix] = 1;
300   insn->prefixLocations[prefix] = location;
301 }
302
303 /*
304  * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
305  *   present at a given location.
306  *
307  * @param insn      - The instruction to be queried.
308  * @param prefix    - The prefix.
309  * @param location  - The location to query.
310  * @return          - Whether the prefix is at that location.
311  */
312 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
313                                uint8_t prefix,
314                                uint64_t location)
315 {
316   if (insn->prefixPresent[prefix] == 1 &&
317      insn->prefixLocations[prefix] == location)
318     return TRUE;
319   else
320     return FALSE;
321 }
322
323 /*
324  * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
325  *   instruction as having them.  Also sets the instruction's default operand,
326  *   address, and other relevant data sizes to report operands correctly.
327  *
328  * @param insn  - The instruction whose prefixes are to be read.
329  * @return      - 0 if the instruction could be read until the end of the prefix
330  *                bytes, and no prefixes conflicted; nonzero otherwise.
331  */
332 static int readPrefixes(struct InternalInstruction* insn) {
333   BOOL isPrefix = TRUE;
334   BOOL prefixGroups[4] = { FALSE };
335   uint64_t prefixLocation;
336   uint8_t byte = 0;
337   uint8_t nextByte;
338
339   BOOL hasAdSize = FALSE;
340   BOOL hasOpSize = FALSE;
341
342   dbgprintf(insn, "readPrefixes()");
343
344   while (isPrefix) {
345     prefixLocation = insn->readerCursor;
346
347     /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
348     if (consumeByte(insn, &byte))
349       break;
350
351     /*
352      * If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
353      * break and let it be disassembled as a normal "instruction".
354      */
355     if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0)
356       break;
357
358     if (insn->readerCursor - 1 == insn->startLocation
359         && (byte == 0xf2 || byte == 0xf3)
360         && !lookAtByte(insn, &nextByte))
361     {
362       /*
363        * If the byte is 0xf2 or 0xf3, and any of the following conditions are
364        * met:
365        * - it is followed by a LOCK (0xf0) prefix
366        * - it is followed by an xchg instruction
367        * then it should be disassembled as a xacquire/xrelease not repne/rep.
368        */
369       if ((byte == 0xf2 || byte == 0xf3) &&
370           ((nextByte == 0xf0) |
371           ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90)))
372         insn->xAcquireRelease = TRUE;
373       /*
374        * Also if the byte is 0xf3, and the following condition is met:
375        * - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
376        *                       "mov mem, imm" (opcode 0xc6/0xc7) instructions.
377        * then it should be disassembled as an xrelease not rep.
378        */
379       if (byte == 0xf3 &&
380           (nextByte == 0x88 || nextByte == 0x89 ||
381            nextByte == 0xc6 || nextByte == 0xc7))
382         insn->xAcquireRelease = TRUE;
383       if (insn->mode == MODE_64BIT && (nextByte & 0xf0) == 0x40) {
384         if (consumeByte(insn, &nextByte))
385           return -1;
386         if (lookAtByte(insn, &nextByte))
387           return -1;
388         unconsumeByte(insn);
389       }
390       if (nextByte != 0x0f && nextByte != 0x90)
391         break;
392     }
393
394     switch (byte) {
395     case 0xf0:  /* LOCK */
396     case 0xf2:  /* REPNE/REPNZ */
397     case 0xf3:  /* REP or REPE/REPZ */
398       if (prefixGroups[0])
399         dbgprintf(insn, "Redundant Group 1 prefix");
400       prefixGroups[0] = TRUE;
401       setPrefixPresent(insn, byte, prefixLocation);
402       break;
403     case 0x2e:  /* CS segment override -OR- Branch not taken */
404     case 0x36:  /* SS segment override -OR- Branch taken */
405     case 0x3e:  /* DS segment override */
406     case 0x26:  /* ES segment override */
407     case 0x64:  /* FS segment override */
408     case 0x65:  /* GS segment override */
409       switch (byte) {
410       case 0x2e:
411         insn->segmentOverride = SEG_OVERRIDE_CS;
412         break;
413       case 0x36:
414         insn->segmentOverride = SEG_OVERRIDE_SS;
415         break;
416       case 0x3e:
417         insn->segmentOverride = SEG_OVERRIDE_DS;
418         break;
419       case 0x26:
420         insn->segmentOverride = SEG_OVERRIDE_ES;
421         break;
422       case 0x64:
423         insn->segmentOverride = SEG_OVERRIDE_FS;
424         break;
425       case 0x65:
426         insn->segmentOverride = SEG_OVERRIDE_GS;
427         break;
428       default:
429         debug("Unhandled override");
430         return -1;
431       }
432       if (prefixGroups[1])
433         dbgprintf(insn, "Redundant Group 2 prefix");
434       prefixGroups[1] = TRUE;
435       setPrefixPresent(insn, byte, prefixLocation);
436       break;
437     case 0x66:  /* Operand-size override */
438       if (prefixGroups[2])
439         dbgprintf(insn, "Redundant Group 3 prefix");
440       prefixGroups[2] = TRUE;
441       hasOpSize = TRUE;
442       setPrefixPresent(insn, byte, prefixLocation);
443       break;
444     case 0x67:  /* Address-size override */
445       if (prefixGroups[3])
446         dbgprintf(insn, "Redundant Group 4 prefix");
447       prefixGroups[3] = TRUE;
448       hasAdSize = TRUE;
449       setPrefixPresent(insn, byte, prefixLocation);
450       break;
451     default:    /* Not a prefix byte */
452       isPrefix = FALSE;
453       break;
454     }
455
456     if (isPrefix)
457       dbgprintf(insn, "Found prefix 0x%hhx", byte);
458   }
459
460   insn->vectorExtensionType = TYPE_NO_VEX_XOP;
461
462   if (byte == 0x62) {
463     uint8_t byte1, byte2;
464
465     if (consumeByte(insn, &byte1)) {
466       dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
467       return -1;
468     }
469
470     if (lookAtByte(insn, &byte2)) {
471       dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
472       return -1;
473     }
474
475     if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
476        ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
477       insn->vectorExtensionType = TYPE_EVEX;
478     }
479     else {
480       unconsumeByte(insn); /* unconsume byte1 */
481       unconsumeByte(insn); /* unconsume byte  */
482       insn->necessaryPrefixLocation = insn->readerCursor - 2;
483     }
484
485     if (insn->vectorExtensionType == TYPE_EVEX) {
486       insn->vectorExtensionPrefix[0] = byte;
487       insn->vectorExtensionPrefix[1] = byte1;
488       if (consumeByte(insn, &insn->vectorExtensionPrefix[2])) {
489         dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
490         return -1;
491       }
492       if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
493         dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
494         return -1;
495       }
496
497       /* We simulate the REX prefix for simplicity's sake */
498       if (insn->mode == MODE_64BIT) {
499         insn->rexPrefix = 0x40
500                         | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
501                         | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
502                         | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
503                         | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
504       }
505
506       dbgprintf(insn, "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
507               insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
508               insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]);
509     }
510   }
511   else if (byte == 0xc4) {
512     uint8_t byte1;
513
514     if (lookAtByte(insn, &byte1)) {
515       dbgprintf(insn, "Couldn't read second byte of VEX");
516       return -1;
517     }
518
519     if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
520       insn->vectorExtensionType = TYPE_VEX_3B;
521       insn->necessaryPrefixLocation = insn->readerCursor - 1;
522     }
523     else {
524       unconsumeByte(insn);
525       insn->necessaryPrefixLocation = insn->readerCursor - 1;
526     }
527
528     if (insn->vectorExtensionType == TYPE_VEX_3B) {
529       insn->vectorExtensionPrefix[0] = byte;
530       consumeByte(insn, &insn->vectorExtensionPrefix[1]);
531       consumeByte(insn, &insn->vectorExtensionPrefix[2]);
532
533       /* We simulate the REX prefix for simplicity's sake */
534
535       if (insn->mode == MODE_64BIT) {
536         insn->rexPrefix = 0x40
537                         | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
538                         | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
539                         | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
540                         | (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
541       }
542
543       dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
544                 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
545                 insn->vectorExtensionPrefix[2]);
546     }
547   }
548   else if (byte == 0xc5) {
549     uint8_t byte1;
550
551     if (lookAtByte(insn, &byte1)) {
552       dbgprintf(insn, "Couldn't read second byte of VEX");
553       return -1;
554     }
555
556     if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
557       insn->vectorExtensionType = TYPE_VEX_2B;
558     }
559     else {
560       unconsumeByte(insn);
561     }
562
563     if (insn->vectorExtensionType == TYPE_VEX_2B) {
564       insn->vectorExtensionPrefix[0] = byte;
565       consumeByte(insn, &insn->vectorExtensionPrefix[1]);
566
567       if (insn->mode == MODE_64BIT) {
568         insn->rexPrefix = 0x40
569                         | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
570       }
571
572       switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1]))
573       {
574       default:
575         break;
576       case VEX_PREFIX_66:
577         hasOpSize = TRUE;
578         break;
579       }
580
581       dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
582                 insn->vectorExtensionPrefix[0],
583                 insn->vectorExtensionPrefix[1]);
584     }
585   }
586   else if (byte == 0x8f) {
587     uint8_t byte1;
588
589     if (lookAtByte(insn, &byte1)) {
590       dbgprintf(insn, "Couldn't read second byte of XOP");
591       return -1;
592     }
593
594     if ((byte1 & 0x38) != 0x0) { /* 0 in these 3 bits is a POP instruction. */
595       insn->vectorExtensionType = TYPE_XOP;
596       insn->necessaryPrefixLocation = insn->readerCursor - 1;
597     }
598     else {
599       unconsumeByte(insn);
600       insn->necessaryPrefixLocation = insn->readerCursor - 1;
601     }
602
603     if (insn->vectorExtensionType == TYPE_XOP) {
604       insn->vectorExtensionPrefix[0] = byte;
605       consumeByte(insn, &insn->vectorExtensionPrefix[1]);
606       consumeByte(insn, &insn->vectorExtensionPrefix[2]);
607
608       /* We simulate the REX prefix for simplicity's sake */
609
610       if (insn->mode == MODE_64BIT) {
611         insn->rexPrefix = 0x40
612                         | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
613                         | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
614                         | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
615                         | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
616       }
617
618       switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2]))
619       {
620       default:
621         break;
622       case VEX_PREFIX_66:
623         hasOpSize = TRUE;
624         break;
625       }
626
627       dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
628                 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
629                 insn->vectorExtensionPrefix[2]);
630     }
631   }
632   else {
633     if (insn->mode == MODE_64BIT) {
634       if ((byte & 0xf0) == 0x40) {
635         uint8_t opcodeByte;
636
637         if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
638           dbgprintf(insn, "Redundant REX prefix");
639           return -1;
640         }
641
642         insn->rexPrefix = byte;
643         insn->necessaryPrefixLocation = insn->readerCursor - 2;
644
645         dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
646       } else {
647         unconsumeByte(insn);
648         insn->necessaryPrefixLocation = insn->readerCursor - 1;
649       }
650     } else {
651       unconsumeByte(insn);
652       insn->necessaryPrefixLocation = insn->readerCursor - 1;
653     }
654   }
655
656   if (insn->mode == MODE_16BIT) {
657     insn->registerSize       = (hasOpSize ? 4 : 2);
658     insn->addressSize        = (hasAdSize ? 4 : 2);
659     insn->displacementSize   = (hasAdSize ? 4 : 2);
660     insn->immediateSize      = (hasOpSize ? 4 : 2);
661   } else if (insn->mode == MODE_32BIT) {
662     insn->registerSize       = (hasOpSize ? 2 : 4);
663     insn->addressSize        = (hasAdSize ? 2 : 4);
664     insn->displacementSize   = (hasAdSize ? 2 : 4);
665     insn->immediateSize      = (hasOpSize ? 2 : 4);
666   } else if (insn->mode == MODE_64BIT) {
667     if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
668       insn->registerSize       = 8;
669       insn->addressSize        = (hasAdSize ? 4 : 8);
670       insn->displacementSize   = 4;
671       insn->immediateSize      = 4;
672     } else if (insn->rexPrefix) {
673       insn->registerSize       = (hasOpSize ? 2 : 4);
674       insn->addressSize        = (hasAdSize ? 4 : 8);
675       insn->displacementSize   = (hasOpSize ? 2 : 4);
676       insn->immediateSize      = (hasOpSize ? 2 : 4);
677     } else {
678       insn->registerSize       = (hasOpSize ? 2 : 4);
679       insn->addressSize        = (hasAdSize ? 4 : 8);
680       insn->displacementSize   = (hasOpSize ? 2 : 4);
681       insn->immediateSize      = (hasOpSize ? 2 : 4);
682     }
683   }
684
685   return 0;
686 }
687
688 /*
689  * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
690  *   extended or escape opcodes).
691  *
692  * @param insn  - The instruction whose opcode is to be read.
693  * @return      - 0 if the opcode could be read successfully; nonzero otherwise.
694  */
695 static int readOpcode(struct InternalInstruction* insn) {
696   /* Determine the length of the primary opcode */
697
698   uint8_t current;
699
700   dbgprintf(insn, "readOpcode()");
701
702   insn->opcodeType = ONEBYTE;
703
704   if (insn->vectorExtensionType == TYPE_EVEX)
705   {
706     switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
707     default:
708       dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
709                 mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
710       return -1;
711     case VEX_LOB_0F:
712       insn->opcodeType = TWOBYTE;
713       return consumeByte(insn, &insn->opcode);
714     case VEX_LOB_0F38:
715       insn->opcodeType = THREEBYTE_38;
716       return consumeByte(insn, &insn->opcode);
717     case VEX_LOB_0F3A:
718       insn->opcodeType = THREEBYTE_3A;
719       return consumeByte(insn, &insn->opcode);
720     }
721   }
722   else if (insn->vectorExtensionType == TYPE_VEX_3B) {
723     switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
724     default:
725       dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
726                 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
727       return -1;
728     case VEX_LOB_0F:
729       insn->opcodeType = TWOBYTE;
730       return consumeByte(insn, &insn->opcode);
731     case VEX_LOB_0F38:
732       insn->opcodeType = THREEBYTE_38;
733       return consumeByte(insn, &insn->opcode);
734     case VEX_LOB_0F3A:
735       insn->opcodeType = THREEBYTE_3A;
736       return consumeByte(insn, &insn->opcode);
737     }
738   }
739   else if (insn->vectorExtensionType == TYPE_VEX_2B) {
740     insn->opcodeType = TWOBYTE;
741     return consumeByte(insn, &insn->opcode);
742   }
743   else if (insn->vectorExtensionType == TYPE_XOP) {
744     switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
745     default:
746       dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
747                 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
748       return -1;
749     case XOP_MAP_SELECT_8:
750       insn->opcodeType = XOP8_MAP;
751       return consumeByte(insn, &insn->opcode);
752     case XOP_MAP_SELECT_9:
753       insn->opcodeType = XOP9_MAP;
754       return consumeByte(insn, &insn->opcode);
755     case XOP_MAP_SELECT_A:
756       insn->opcodeType = XOPA_MAP;
757       return consumeByte(insn, &insn->opcode);
758     }
759   }
760
761   if (consumeByte(insn, &current))
762     return -1;
763
764   if (current == 0x0f) {
765     dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
766
767     if (consumeByte(insn, &current))
768       return -1;
769
770     if (current == 0x38) {
771       dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
772
773       if (consumeByte(insn, &current))
774         return -1;
775
776       insn->opcodeType = THREEBYTE_38;
777     } else if (current == 0x3a) {
778       dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
779
780       if (consumeByte(insn, &current))
781         return -1;
782
783       insn->opcodeType = THREEBYTE_3A;
784     } else {
785       dbgprintf(insn, "Didn't find a three-byte escape prefix");
786
787       insn->opcodeType = TWOBYTE;
788     }
789   }
790
791   /*
792    * At this point we have consumed the full opcode.
793    * Anything we consume from here on must be unconsumed.
794    */
795
796   insn->opcode = current;
797
798   return 0;
799 }
800
801 static int readModRM(struct InternalInstruction* insn);
802
803 /*
804  * getIDWithAttrMask - Determines the ID of an instruction, consuming
805  *   the ModR/M byte as appropriate for extended and escape opcodes,
806  *   and using a supplied attribute mask.
807  *
808  * @param instructionID - A pointer whose target is filled in with the ID of the
809  *                        instruction.
810  * @param insn          - The instruction whose ID is to be determined.
811  * @param attrMask      - The attribute mask to search.
812  * @return              - 0 if the ModR/M could be read when needed or was not
813  *                        needed; nonzero otherwise.
814  */
815 static int getIDWithAttrMask(uint16_t* instructionID,
816                              struct InternalInstruction* insn,
817                              uint16_t attrMask) {
818   BOOL hasModRMExtension;
819
820   InstructionContext instructionClass = contextForAttrs(attrMask);
821
822   hasModRMExtension = modRMRequired(insn->opcodeType,
823                                     instructionClass,
824                                     insn->opcode);
825
826   if (hasModRMExtension) {
827     if (readModRM(insn))
828       return -1;
829
830     *instructionID = decode(insn->opcodeType,
831                             instructionClass,
832                             insn->opcode,
833                             insn->modRM);
834   } else {
835     *instructionID = decode(insn->opcodeType,
836                             instructionClass,
837                             insn->opcode,
838                             0);
839   }
840
841   return 0;
842 }
843
844 /*
845  * is16BitEquivalent - Determines whether two instruction names refer to
846  * equivalent instructions but one is 16-bit whereas the other is not.
847  *
848  * @param orig  - The instruction that is not 16-bit
849  * @param equiv - The instruction that is 16-bit
850  */
851 static BOOL is16BitEquivalent(const char* orig, const char* equiv) {
852   off_t i;
853
854   for (i = 0;; i++) {
855     if (orig[i] == '\0' && equiv[i] == '\0')
856       return TRUE;
857     if (orig[i] == '\0' || equiv[i] == '\0')
858       return FALSE;
859     if (orig[i] != equiv[i]) {
860       if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
861         continue;
862       if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
863         continue;
864       if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
865         continue;
866       return FALSE;
867     }
868   }
869 }
870
871 /*
872  * getID - Determines the ID of an instruction, consuming the ModR/M byte as
873  *   appropriate for extended and escape opcodes.  Determines the attributes and
874  *   context for the instruction before doing so.
875  *
876  * @param insn  - The instruction whose ID is to be determined.
877  * @return      - 0 if the ModR/M could be read when needed or was not needed;
878  *                nonzero otherwise.
879  */
880 static int getID(struct InternalInstruction* insn, const void *miiArg) {
881   uint16_t attrMask;
882   uint16_t instructionID;
883
884   dbgprintf(insn, "getID()");
885
886   attrMask = ATTR_NONE;
887
888   if (insn->mode == MODE_64BIT)
889     attrMask |= ATTR_64BIT;
890
891   if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
892     attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
893
894     if (insn->vectorExtensionType == TYPE_EVEX) {
895       switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
896       case VEX_PREFIX_66:
897         attrMask |= ATTR_OPSIZE;
898         break;
899       case VEX_PREFIX_F3:
900         attrMask |= ATTR_XS;
901         break;
902       case VEX_PREFIX_F2:
903         attrMask |= ATTR_XD;
904         break;
905       }
906
907       if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
908         attrMask |= ATTR_EVEXKZ;
909       if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
910         attrMask |= ATTR_EVEXB;
911       if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
912         attrMask |= ATTR_EVEXK;
913       if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
914         attrMask |= ATTR_EVEXL;
915       if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
916         attrMask |= ATTR_EVEXL2;
917     }
918     else if (insn->vectorExtensionType == TYPE_VEX_3B) {
919       switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
920       case VEX_PREFIX_66:
921         attrMask |= ATTR_OPSIZE;
922         break;
923       case VEX_PREFIX_F3:
924         attrMask |= ATTR_XS;
925         break;
926       case VEX_PREFIX_F2:
927         attrMask |= ATTR_XD;
928         break;
929       }
930
931       if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
932         attrMask |= ATTR_VEXL;
933     }
934     else if (insn->vectorExtensionType == TYPE_VEX_2B) {
935       switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
936       case VEX_PREFIX_66:
937         attrMask |= ATTR_OPSIZE;
938         break;
939       case VEX_PREFIX_F3:
940         attrMask |= ATTR_XS;
941         break;
942       case VEX_PREFIX_F2:
943         attrMask |= ATTR_XD;
944         break;
945       }
946
947       if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
948         attrMask |= ATTR_VEXL;
949     }
950     else if (insn->vectorExtensionType == TYPE_XOP) {
951       switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
952       case VEX_PREFIX_66:
953         attrMask |= ATTR_OPSIZE;
954         break;
955       case VEX_PREFIX_F3:
956         attrMask |= ATTR_XS;
957         break;
958       case VEX_PREFIX_F2:
959         attrMask |= ATTR_XD;
960         break;
961       }
962
963       if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
964         attrMask |= ATTR_VEXL;
965     }
966     else {
967       return -1;
968     }
969   }
970   else {
971     if (insn->mode != MODE_16BIT && isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
972       attrMask |= ATTR_OPSIZE;
973     else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
974       attrMask |= ATTR_ADSIZE;
975     else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
976       attrMask |= ATTR_XS;
977     else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
978       attrMask |= ATTR_XD;
979   }
980
981   if (insn->rexPrefix & 0x08)
982     attrMask |= ATTR_REXW;
983
984   if (getIDWithAttrMask(&instructionID, insn, attrMask))
985     return -1;
986
987   /*
988    * JCXZ/JECXZ need special handling for 16-bit mode because the meaning
989    * of the AdSize prefix is inverted w.r.t. 32-bit mode.
990    */
991   if (insn->mode == MODE_16BIT && insn->opcode == 0xE3) {
992     const struct InstructionSpecifier *spec;
993     spec = specifierForUID(instructionID);
994
995     /*
996      * Check for Ii8PCRel instructions. We could alternatively do a
997      * string-compare on the names, but this is probably cheaper.
998      */
999     if (x86OperandSets[spec->operands][0].type == TYPE_REL8) {
1000       attrMask ^= ATTR_ADSIZE;
1001       if (getIDWithAttrMask(&instructionID, insn, attrMask))
1002         return -1;
1003     }
1004   }
1005
1006   /* The following clauses compensate for limitations of the tables. */
1007
1008   if ((insn->mode == MODE_16BIT || insn->prefixPresent[0x66]) &&
1009       !(attrMask & ATTR_OPSIZE)) {
1010     /*
1011      * The instruction tables make no distinction between instructions that
1012      * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1013      * particular spot (i.e., many MMX operations).  In general we're
1014      * conservative, but in the specific case where OpSize is present but not
1015      * in the right place we check if there's a 16-bit operation.
1016      */
1017
1018     const struct InstructionSpecifier *spec;
1019     uint16_t instructionIDWithOpsize;
1020     const char *specName, *specWithOpSizeName;
1021
1022     spec = specifierForUID(instructionID);
1023
1024     if (getIDWithAttrMask(&instructionIDWithOpsize,
1025                           insn,
1026                           attrMask | ATTR_OPSIZE)) {
1027       /*
1028        * ModRM required with OpSize but not present; give up and return version
1029        * without OpSize set
1030        */
1031
1032       insn->instructionID = instructionID;
1033       insn->spec = spec;
1034       return 0;
1035     }
1036
1037     specName = GetInstrName(instructionID, miiArg);
1038     specWithOpSizeName = GetInstrName(instructionIDWithOpsize, miiArg);
1039
1040     if (is16BitEquivalent(specName, specWithOpSizeName) &&
1041         (insn->mode == MODE_16BIT) ^ insn->prefixPresent[0x66]) {
1042       insn->instructionID = instructionIDWithOpsize;
1043       insn->spec = specifierForUID(instructionIDWithOpsize);
1044     } else {
1045       insn->instructionID = instructionID;
1046       insn->spec = spec;
1047     }
1048     return 0;
1049   }
1050
1051   if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1052       insn->rexPrefix & 0x01) {
1053     /*
1054      * NOOP shouldn't decode as NOOP if REX.b is set. Instead
1055      * it should decode as XCHG %r8, %eax.
1056      */
1057
1058     const struct InstructionSpecifier *spec;
1059     uint16_t instructionIDWithNewOpcode;
1060     const struct InstructionSpecifier *specWithNewOpcode;
1061
1062     spec = specifierForUID(instructionID);
1063
1064     /* Borrow opcode from one of the other XCHGar opcodes */
1065     insn->opcode = 0x91;
1066
1067     if (getIDWithAttrMask(&instructionIDWithNewOpcode,
1068                           insn,
1069                           attrMask)) {
1070       insn->opcode = 0x90;
1071
1072       insn->instructionID = instructionID;
1073       insn->spec = spec;
1074       return 0;
1075     }
1076
1077     specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1078
1079     /* Change back */
1080     insn->opcode = 0x90;
1081
1082     insn->instructionID = instructionIDWithNewOpcode;
1083     insn->spec = specWithNewOpcode;
1084
1085     return 0;
1086   }
1087
1088   insn->instructionID = instructionID;
1089   insn->spec = specifierForUID(insn->instructionID);
1090
1091   return 0;
1092 }
1093
1094 /*
1095  * readSIB - Consumes the SIB byte to determine addressing information for an
1096  *   instruction.
1097  *
1098  * @param insn  - The instruction whose SIB byte is to be read.
1099  * @return      - 0 if the SIB byte was successfully read; nonzero otherwise.
1100  */
1101 static int readSIB(struct InternalInstruction* insn) {
1102   SIBIndex sibIndexBase = SIB_INDEX_NONE;
1103   SIBBase sibBaseBase = SIB_BASE_NONE;
1104   uint8_t index, base;
1105
1106   dbgprintf(insn, "readSIB()");
1107
1108   if (insn->consumedSIB)
1109     return 0;
1110
1111   insn->consumedSIB = TRUE;
1112
1113   switch (insn->addressSize) {
1114   case 2:
1115     dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1116     return -1;
1117   case 4:
1118     sibIndexBase = SIB_INDEX_EAX;
1119     sibBaseBase = SIB_BASE_EAX;
1120     break;
1121   case 8:
1122     sibIndexBase = SIB_INDEX_RAX;
1123     sibBaseBase = SIB_BASE_RAX;
1124     break;
1125   }
1126
1127   if (consumeByte(insn, &insn->sib))
1128     return -1;
1129
1130   index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1131   if (insn->vectorExtensionType == TYPE_EVEX)
1132     index |= v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4;
1133
1134   switch (index) {
1135   case 0x4:
1136     insn->sibIndex = SIB_INDEX_NONE;
1137     break;
1138   default:
1139     insn->sibIndex = (SIBIndex)(sibIndexBase + index);
1140     if (insn->sibIndex == SIB_INDEX_sib ||
1141         insn->sibIndex == SIB_INDEX_sib64)
1142       insn->sibIndex = SIB_INDEX_NONE;
1143     break;
1144   }
1145
1146   switch (scaleFromSIB(insn->sib)) {
1147   case 0:
1148     insn->sibScale = 1;
1149     break;
1150   case 1:
1151     insn->sibScale = 2;
1152     break;
1153   case 2:
1154     insn->sibScale = 4;
1155     break;
1156   case 3:
1157     insn->sibScale = 8;
1158     break;
1159   }
1160
1161   base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1162
1163   switch (base) {
1164   case 0x5:
1165   case 0xd:
1166     switch (modFromModRM(insn->modRM)) {
1167     case 0x0:
1168       insn->eaDisplacement = EA_DISP_32;
1169       insn->sibBase = SIB_BASE_NONE;
1170       break;
1171     case 0x1:
1172       insn->eaDisplacement = EA_DISP_8;
1173       insn->sibBase = (SIBBase)(sibBaseBase + base);
1174       break;
1175     case 0x2:
1176       insn->eaDisplacement = EA_DISP_32;
1177       insn->sibBase = (SIBBase)(sibBaseBase + base);
1178       break;
1179     case 0x3:
1180       debug("Cannot have Mod = 0b11 and a SIB byte");
1181       return -1;
1182     }
1183     break;
1184   default:
1185     insn->sibBase = (SIBBase)(sibBaseBase + base);
1186     break;
1187   }
1188
1189   return 0;
1190 }
1191
1192 /*
1193  * readDisplacement - Consumes the displacement of an instruction.
1194  *
1195  * @param insn  - The instruction whose displacement is to be read.
1196  * @return      - 0 if the displacement byte was successfully read; nonzero
1197  *                otherwise.
1198  */
1199 static int readDisplacement(struct InternalInstruction* insn) {
1200   int8_t d8;
1201   int16_t d16;
1202   int32_t d32;
1203
1204   dbgprintf(insn, "readDisplacement()");
1205
1206   if (insn->consumedDisplacement)
1207     return 0;
1208
1209   insn->consumedDisplacement = TRUE;
1210   insn->displacementOffset = insn->readerCursor - insn->startLocation;
1211
1212   switch (insn->eaDisplacement) {
1213   case EA_DISP_NONE:
1214     insn->consumedDisplacement = FALSE;
1215     break;
1216   case EA_DISP_8:
1217     if (consumeInt8(insn, &d8))
1218       return -1;
1219     insn->displacement = d8;
1220     break;
1221   case EA_DISP_16:
1222     if (consumeInt16(insn, &d16))
1223       return -1;
1224     insn->displacement = d16;
1225     break;
1226   case EA_DISP_32:
1227     if (consumeInt32(insn, &d32))
1228       return -1;
1229     insn->displacement = d32;
1230     break;
1231   }
1232
1233   insn->consumedDisplacement = TRUE;
1234   return 0;
1235 }
1236
1237 /*
1238  * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1239  *   displacement) for an instruction and interprets it.
1240  *
1241  * @param insn  - The instruction whose addressing information is to be read.
1242  * @return      - 0 if the information was successfully read; nonzero otherwise.
1243  */
1244 static int readModRM(struct InternalInstruction* insn) {
1245   uint8_t mod, rm, reg;
1246
1247   dbgprintf(insn, "readModRM()");
1248
1249   if (insn->consumedModRM)
1250     return 0;
1251
1252   if (consumeByte(insn, &insn->modRM))
1253     return -1;
1254   insn->consumedModRM = TRUE;
1255
1256   mod     = modFromModRM(insn->modRM);
1257   rm      = rmFromModRM(insn->modRM);
1258   reg     = regFromModRM(insn->modRM);
1259
1260   /*
1261    * This goes by insn->registerSize to pick the correct register, which messes
1262    * up if we're using (say) XMM or 8-bit register operands.  That gets fixed in
1263    * fixupReg().
1264    */
1265   switch (insn->registerSize) {
1266   case 2:
1267     insn->regBase = MODRM_REG_AX;
1268     insn->eaRegBase = EA_REG_AX;
1269     break;
1270   case 4:
1271     insn->regBase = MODRM_REG_EAX;
1272     insn->eaRegBase = EA_REG_EAX;
1273     break;
1274   case 8:
1275     insn->regBase = MODRM_REG_RAX;
1276     insn->eaRegBase = EA_REG_RAX;
1277     break;
1278   }
1279
1280   reg |= rFromREX(insn->rexPrefix) << 3;
1281   rm  |= bFromREX(insn->rexPrefix) << 3;
1282   if (insn->vectorExtensionType == TYPE_EVEX) {
1283     reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1284     rm  |=  xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1285   }
1286
1287   insn->reg = (Reg)(insn->regBase + reg);
1288
1289   switch (insn->addressSize) {
1290   case 2:
1291     insn->eaBaseBase = EA_BASE_BX_SI;
1292
1293     switch (mod) {
1294     case 0x0:
1295       if (rm == 0x6) {
1296         insn->eaBase = EA_BASE_NONE;
1297         insn->eaDisplacement = EA_DISP_16;
1298         if (readDisplacement(insn))
1299           return -1;
1300       } else {
1301         insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1302         insn->eaDisplacement = EA_DISP_NONE;
1303       }
1304       break;
1305     case 0x1:
1306       insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1307       insn->eaDisplacement = EA_DISP_8;
1308       insn->displacementSize = 1;
1309       if (readDisplacement(insn))
1310         return -1;
1311       break;
1312     case 0x2:
1313       insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1314       insn->eaDisplacement = EA_DISP_16;
1315       if (readDisplacement(insn))
1316         return -1;
1317       break;
1318     case 0x3:
1319       insn->eaBase = (EABase)(insn->eaRegBase + rm);
1320       if (readDisplacement(insn))
1321         return -1;
1322       break;
1323     }
1324     break;
1325   case 4:
1326   case 8:
1327     insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1328
1329     switch (mod) {
1330     case 0x0:
1331       insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1332       switch (rm) {
1333       case 0x14:
1334       case 0x4:
1335       case 0xc:   /* in case REXW.b is set */
1336         insn->eaBase = (insn->addressSize == 4 ?
1337                         EA_BASE_sib : EA_BASE_sib64);
1338         if (readSIB(insn) || readDisplacement(insn))
1339           return -1;
1340         break;
1341       case 0x5:
1342         insn->eaBase = EA_BASE_NONE;
1343         insn->eaDisplacement = EA_DISP_32;
1344         if (readDisplacement(insn))
1345           return -1;
1346         break;
1347       default:
1348         insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1349         break;
1350       }
1351       break;
1352     case 0x1:
1353       insn->displacementSize = 1;
1354       /* FALLTHROUGH */
1355     case 0x2:
1356       insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1357       switch (rm) {
1358       case 0x14:
1359       case 0x4:
1360       case 0xc:   /* in case REXW.b is set */
1361         insn->eaBase = EA_BASE_sib;
1362         if (readSIB(insn) || readDisplacement(insn))
1363           return -1;
1364         break;
1365       default:
1366         insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1367         if (readDisplacement(insn))
1368           return -1;
1369         break;
1370       }
1371       break;
1372     case 0x3:
1373       insn->eaDisplacement = EA_DISP_NONE;
1374       insn->eaBase = (EABase)(insn->eaRegBase + rm);
1375       break;
1376     }
1377     break;
1378   } /* switch (insn->addressSize) */
1379
1380   return 0;
1381 }
1382
1383 #define GENERIC_FIXUP_FUNC(name, base, prefix)            \
1384   static uint8_t name(struct InternalInstruction *insn,   \
1385                       OperandType type,                   \
1386                       uint8_t index,                      \
1387                       uint8_t *valid) {                   \
1388     *valid = 1;                                           \
1389     switch (type) {                                       \
1390     default:                                              \
1391       debug("Unhandled register type");                   \
1392       *valid = 0;                                         \
1393       return 0;                                           \
1394     case TYPE_Rv:                                         \
1395       return base + index;                                \
1396     case TYPE_R8:                                         \
1397       if (insn->rexPrefix &&                              \
1398          index >= 4 && index <= 7) {                      \
1399         return prefix##_SPL + (index - 4);                \
1400       } else {                                            \
1401         return prefix##_AL + index;                       \
1402       }                                                   \
1403     case TYPE_R16:                                        \
1404       return prefix##_AX + index;                         \
1405     case TYPE_R32:                                        \
1406       return prefix##_EAX + index;                        \
1407     case TYPE_R64:                                        \
1408       return prefix##_RAX + index;                        \
1409     case TYPE_XMM512:                                     \
1410       return prefix##_ZMM0 + index;                       \
1411     case TYPE_XMM256:                                     \
1412       return prefix##_YMM0 + index;                       \
1413     case TYPE_XMM128:                                     \
1414     case TYPE_XMM64:                                      \
1415     case TYPE_XMM32:                                      \
1416     case TYPE_XMM:                                        \
1417       return prefix##_XMM0 + index;                       \
1418     case TYPE_VK1:                                        \
1419     case TYPE_VK8:                                        \
1420     case TYPE_VK16:                                       \
1421       return prefix##_K0 + index;                         \
1422     case TYPE_MM64:                                       \
1423     case TYPE_MM32:                                       \
1424     case TYPE_MM:                                         \
1425       if (index > 7)                                      \
1426         *valid = 0;                                       \
1427       return prefix##_MM0 + index;                        \
1428     case TYPE_SEGMENTREG:                                 \
1429       if (index > 5)                                      \
1430         *valid = 0;                                       \
1431       return prefix##_ES + index;                         \
1432     case TYPE_DEBUGREG:                                   \
1433       if (index > 7)                                      \
1434         *valid = 0;                                       \
1435       return prefix##_DR0 + index;                        \
1436     case TYPE_CONTROLREG:                                 \
1437       if (index > 8)                                      \
1438         *valid = 0;                                       \
1439       return prefix##_CR0 + index;                        \
1440     }                                                     \
1441   }
1442
1443 /*
1444  * fixup*Value - Consults an operand type to determine the meaning of the
1445  *   reg or R/M field.  If the operand is an XMM operand, for example, an
1446  *   operand would be XMM0 instead of AX, which readModRM() would otherwise
1447  *   misinterpret it as.
1448  *
1449  * @param insn  - The instruction containing the operand.
1450  * @param type  - The operand type.
1451  * @param index - The existing value of the field as reported by readModRM().
1452  * @param valid - The address of a uint8_t.  The target is set to 1 if the
1453  *                field is valid for the register class; 0 if not.
1454  * @return      - The proper value.
1455  */
1456 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase,    MODRM_REG)
1457 GENERIC_FIXUP_FUNC(fixupRMValue,  insn->eaRegBase,  EA_REG)
1458
1459 /*
1460  * fixupReg - Consults an operand specifier to determine which of the
1461  *   fixup*Value functions to use in correcting readModRM()'ss interpretation.
1462  *
1463  * @param insn  - See fixup*Value().
1464  * @param op    - The operand specifier.
1465  * @return      - 0 if fixup was successful; -1 if the register returned was
1466  *                invalid for its class.
1467  */
1468 static int fixupReg(struct InternalInstruction *insn,
1469                     const struct OperandSpecifier *op) {
1470   uint8_t valid;
1471
1472   dbgprintf(insn, "fixupReg()");
1473
1474   switch ((OperandEncoding)op->encoding) {
1475   default:
1476     debug("Expected a REG or R/M encoding in fixupReg");
1477     return -1;
1478   case ENCODING_VVVV:
1479     insn->vvvv = (Reg)fixupRegValue(insn,
1480                                     (OperandType)op->type,
1481                                     insn->vvvv,
1482                                     &valid);
1483     if (!valid)
1484       return -1;
1485     break;
1486   case ENCODING_REG:
1487     insn->reg = (Reg)fixupRegValue(insn,
1488                                    (OperandType)op->type,
1489                                    insn->reg - insn->regBase,
1490                                    &valid);
1491     if (!valid)
1492       return -1;
1493     break;
1494   case ENCODING_RM:
1495     if (insn->eaBase >= insn->eaRegBase) {
1496       insn->eaBase = (EABase)fixupRMValue(insn,
1497                                           (OperandType)op->type,
1498                                           insn->eaBase - insn->eaRegBase,
1499                                           &valid);
1500       if (!valid)
1501         return -1;
1502     }
1503     break;
1504   }
1505
1506   return 0;
1507 }
1508
1509 /*
1510  * readOpcodeRegister - Reads an operand from the opcode field of an
1511  *   instruction and interprets it appropriately given the operand width.
1512  *   Handles AddRegFrm instructions.
1513  *
1514  * @param insn  - the instruction whose opcode field is to be read.
1515  * @param size  - The width (in bytes) of the register being specified.
1516  *                1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1517  *                RAX.
1518  * @return      - 0 on success; nonzero otherwise.
1519  */
1520 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1521   dbgprintf(insn, "readOpcodeRegister()");
1522
1523   if (size == 0)
1524     size = insn->registerSize;
1525
1526   switch (size) {
1527   case 1:
1528     insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1529                                                   | (insn->opcode & 7)));
1530     if (insn->rexPrefix &&
1531         insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1532         insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1533       insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1534                                    + (insn->opcodeRegister - MODRM_REG_AL - 4));
1535     }
1536
1537     break;
1538   case 2:
1539     insn->opcodeRegister = (Reg)(MODRM_REG_AX
1540                                  + ((bFromREX(insn->rexPrefix) << 3)
1541                                     | (insn->opcode & 7)));
1542     break;
1543   case 4:
1544     insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1545                                  + ((bFromREX(insn->rexPrefix) << 3)
1546                                     | (insn->opcode & 7)));
1547     break;
1548   case 8:
1549     insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1550                                  + ((bFromREX(insn->rexPrefix) << 3)
1551                                     | (insn->opcode & 7)));
1552     break;
1553   }
1554
1555   return 0;
1556 }
1557
1558 /*
1559  * readImmediate - Consumes an immediate operand from an instruction, given the
1560  *   desired operand size.
1561  *
1562  * @param insn  - The instruction whose operand is to be read.
1563  * @param size  - The width (in bytes) of the operand.
1564  * @return      - 0 if the immediate was successfully consumed; nonzero
1565  *                otherwise.
1566  */
1567 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1568   uint8_t imm8;
1569   uint16_t imm16;
1570   uint32_t imm32;
1571   uint64_t imm64;
1572
1573   dbgprintf(insn, "readImmediate()");
1574
1575   if (insn->numImmediatesConsumed == 2) {
1576     debug("Already consumed two immediates");
1577     return -1;
1578   }
1579
1580   if (size == 0)
1581     size = insn->immediateSize;
1582   else
1583     insn->immediateSize = size;
1584   insn->immediateOffset = insn->readerCursor - insn->startLocation;
1585
1586   switch (size) {
1587   case 1:
1588     if (consumeByte(insn, &imm8))
1589       return -1;
1590     insn->immediates[insn->numImmediatesConsumed] = imm8;
1591     break;
1592   case 2:
1593     if (consumeUInt16(insn, &imm16))
1594       return -1;
1595     insn->immediates[insn->numImmediatesConsumed] = imm16;
1596     break;
1597   case 4:
1598     if (consumeUInt32(insn, &imm32))
1599       return -1;
1600     insn->immediates[insn->numImmediatesConsumed] = imm32;
1601     break;
1602   case 8:
1603     if (consumeUInt64(insn, &imm64))
1604       return -1;
1605     insn->immediates[insn->numImmediatesConsumed] = imm64;
1606     break;
1607   }
1608
1609   insn->numImmediatesConsumed++;
1610
1611   return 0;
1612 }
1613
1614 /*
1615  * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1616  *
1617  * @param insn  - The instruction whose operand is to be read.
1618  * @return      - 0 if the vvvv was successfully consumed; nonzero
1619  *                otherwise.
1620  */
1621 static int readVVVV(struct InternalInstruction* insn) {
1622   dbgprintf(insn, "readVVVV()");
1623
1624   int vvvv;
1625   if (insn->vectorExtensionType == TYPE_EVEX)
1626     vvvv = vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]);
1627   else if (insn->vectorExtensionType == TYPE_VEX_3B)
1628     vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1629   else if (insn->vectorExtensionType == TYPE_VEX_2B)
1630     vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1631   else if (insn->vectorExtensionType == TYPE_XOP)
1632     vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1633   else
1634     return -1;
1635
1636   if (insn->mode != MODE_64BIT)
1637     vvvv &= 0x7;
1638
1639   insn->vvvv = static_cast<Reg>(vvvv);
1640   return 0;
1641 }
1642
1643 /*
1644  * readMaskRegister - Reads an mask register from the opcode field of an
1645  *   instruction.
1646  *
1647  * @param insn    - The instruction whose opcode field is to be read.
1648  * @return        - 0 on success; nonzero otherwise.
1649  */
1650 static int readMaskRegister(struct InternalInstruction* insn) {
1651   dbgprintf(insn, "readMaskRegister()");
1652
1653   if (insn->vectorExtensionType != TYPE_EVEX)
1654     return -1;
1655
1656   insn->writemask =
1657       static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1658   return 0;
1659 }
1660
1661 /*
1662  * readOperands - Consults the specifier for an instruction and consumes all
1663  *   operands for that instruction, interpreting them as it goes.
1664  *
1665  * @param insn  - The instruction whose operands are to be read and interpreted.
1666  * @return      - 0 if all operands could be read; nonzero otherwise.
1667  */
1668 static int readOperands(struct InternalInstruction* insn) {
1669   int index;
1670   int hasVVVV, needVVVV;
1671   int sawRegImm = 0;
1672
1673   dbgprintf(insn, "readOperands()");
1674
1675   /* If non-zero vvvv specified, need to make sure one of the operands
1676      uses it. */
1677   hasVVVV = !readVVVV(insn);
1678   needVVVV = hasVVVV && (insn->vvvv != 0);
1679
1680   for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1681     switch (x86OperandSets[insn->spec->operands][index].encoding) {
1682     case ENCODING_NONE:
1683     case ENCODING_SI:
1684     case ENCODING_DI:
1685       break;
1686     case ENCODING_REG:
1687     case ENCODING_RM:
1688       if (readModRM(insn))
1689         return -1;
1690       if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
1691         return -1;
1692       break;
1693     case ENCODING_CB:
1694     case ENCODING_CW:
1695     case ENCODING_CD:
1696     case ENCODING_CP:
1697     case ENCODING_CO:
1698     case ENCODING_CT:
1699       dbgprintf(insn, "We currently don't hande code-offset encodings");
1700       return -1;
1701     case ENCODING_IB:
1702       if (sawRegImm) {
1703         /* Saw a register immediate so don't read again and instead split the
1704            previous immediate.  FIXME: This is a hack. */
1705         insn->immediates[insn->numImmediatesConsumed] =
1706           insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1707         ++insn->numImmediatesConsumed;
1708         break;
1709       }
1710       if (readImmediate(insn, 1))
1711         return -1;
1712       if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM3 &&
1713           insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1714         return -1;
1715       if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM5 &&
1716           insn->immediates[insn->numImmediatesConsumed - 1] > 31)
1717         return -1;
1718       if (x86OperandSets[insn->spec->operands][index].type == TYPE_XMM128 ||
1719           x86OperandSets[insn->spec->operands][index].type == TYPE_XMM256)
1720         sawRegImm = 1;
1721       break;
1722     case ENCODING_IW:
1723       if (readImmediate(insn, 2))
1724         return -1;
1725       break;
1726     case ENCODING_ID:
1727       if (readImmediate(insn, 4))
1728         return -1;
1729       break;
1730     case ENCODING_IO:
1731       if (readImmediate(insn, 8))
1732         return -1;
1733       break;
1734     case ENCODING_Iv:
1735       if (readImmediate(insn, insn->immediateSize))
1736         return -1;
1737       break;
1738     case ENCODING_Ia:
1739       if (readImmediate(insn, insn->addressSize))
1740         return -1;
1741       break;
1742     case ENCODING_RB:
1743       if (readOpcodeRegister(insn, 1))
1744         return -1;
1745       break;
1746     case ENCODING_RW:
1747       if (readOpcodeRegister(insn, 2))
1748         return -1;
1749       break;
1750     case ENCODING_RD:
1751       if (readOpcodeRegister(insn, 4))
1752         return -1;
1753       break;
1754     case ENCODING_RO:
1755       if (readOpcodeRegister(insn, 8))
1756         return -1;
1757       break;
1758     case ENCODING_Rv:
1759       if (readOpcodeRegister(insn, 0))
1760         return -1;
1761       break;
1762     case ENCODING_FP:
1763       break;
1764     case ENCODING_VVVV:
1765       needVVVV = 0; /* Mark that we have found a VVVV operand. */
1766       if (!hasVVVV)
1767         return -1;
1768       if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
1769         return -1;
1770       break;
1771     case ENCODING_WRITEMASK:
1772       if (readMaskRegister(insn))
1773         return -1;
1774       break;
1775     case ENCODING_DUP:
1776       break;
1777     default:
1778       dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1779       return -1;
1780     }
1781   }
1782
1783   /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1784   if (needVVVV) return -1;
1785
1786   return 0;
1787 }
1788
1789 /*
1790  * decodeInstruction - Reads and interprets a full instruction provided by the
1791  *   user.
1792  *
1793  * @param insn      - A pointer to the instruction to be populated.  Must be
1794  *                    pre-allocated.
1795  * @param reader    - The function to be used to read the instruction's bytes.
1796  * @param readerArg - A generic argument to be passed to the reader to store
1797  *                    any internal state.
1798  * @param logger    - If non-NULL, the function to be used to write log messages
1799  *                    and warnings.
1800  * @param loggerArg - A generic argument to be passed to the logger to store
1801  *                    any internal state.
1802  * @param startLoc  - The address (in the reader's address space) of the first
1803  *                    byte in the instruction.
1804  * @param mode      - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1805  *                    decode the instruction in.
1806  * @return          - 0 if the instruction's memory could be read; nonzero if
1807  *                    not.
1808  */
1809 int llvm::X86Disassembler::decodeInstruction(
1810     struct InternalInstruction *insn, byteReader_t reader,
1811     const void *readerArg, dlog_t logger, void *loggerArg, const void *miiArg,
1812     uint64_t startLoc, DisassemblerMode mode) {
1813   memset(insn, 0, sizeof(struct InternalInstruction));
1814
1815   insn->reader = reader;
1816   insn->readerArg = readerArg;
1817   insn->dlog = logger;
1818   insn->dlogArg = loggerArg;
1819   insn->startLocation = startLoc;
1820   insn->readerCursor = startLoc;
1821   insn->mode = mode;
1822   insn->numImmediatesConsumed = 0;
1823
1824   if (readPrefixes(insn)       ||
1825       readOpcode(insn)         ||
1826       getID(insn, miiArg)      ||
1827       insn->instructionID == 0 ||
1828       readOperands(insn))
1829     return -1;
1830
1831   insn->operands = &x86OperandSets[insn->spec->operands][0];
1832
1833   insn->length = insn->readerCursor - insn->startLocation;
1834
1835   dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1836             startLoc, insn->readerCursor, insn->length);
1837
1838   if (insn->length > 15)
1839     dbgprintf(insn, "Instruction exceeds 15-byte limit");
1840
1841   return 0;
1842 }