1 //===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is part of the X86 Disassembler.
10 // It contains code to translate the data produced by the decoder into
11 //  MCInsts.
12 //
13 //
14 // The X86 disassembler is a table-driven disassembler for the 16-, 32-, and
15 // 64-bit X86 instruction sets.  The main decode sequence for an assembly
16 // instruction in this disassembler is:
17 //
18 // 1. Read the prefix bytes and determine the attributes of the instruction.
19 //    These attributes, recorded in enum attributeBits
20 //    (X86DisassemblerDecoderCommon.h), form a bitmask.  The table CONTEXTS_SYM
21 //    provides a mapping from bitmasks to contexts, which are represented by
22 //    enum InstructionContext (ibid.).
23 //
24 // 2. Read the opcode, and determine what kind of opcode it is.  The
25 //    disassembler distinguishes four kinds of opcodes, which are enumerated in
26 //    OpcodeType (X86DisassemblerDecoderCommon.h): one-byte (0xnn), two-byte
27 //    (0x0f 0xnn), three-byte-38 (0x0f 0x38 0xnn), or three-byte-3a
28 //    (0x0f 0x3a 0xnn).  Mandatory prefixes are treated as part of the context.
29 //
30 // 3. Depending on the opcode type, look in one of four ClassDecision structures
31 //    (X86DisassemblerDecoderCommon.h).  Use the opcode class to determine which
32 //    OpcodeDecision (ibid.) to look the opcode in.  Look up the opcode, to get
33 //    a ModRMDecision (ibid.).
34 //
35 // 4. Some instructions, such as escape opcodes or extended opcodes, or even
36 //    instructions that have ModRM*Reg / ModRM*Mem forms in LLVM, need the
37 //    ModR/M byte to complete decode.  The ModRMDecision's type is an entry from
38 //    ModRMDecisionType (X86DisassemblerDecoderCommon.h) that indicates if the
39 //    ModR/M byte is required and how to interpret it.
40 //
41 // 5. After resolving the ModRMDecision, the disassembler has a unique ID
42 //    of type InstrUID (X86DisassemblerDecoderCommon.h).  Looking this ID up in
43 //    INSTRUCTIONS_SYM yields the name of the instruction and the encodings and
44 //    meanings of its operands.
45 //
46 // 6. For each operand, its encoding is an entry from OperandEncoding
47 //    (X86DisassemblerDecoderCommon.h) and its type is an entry from
48 //    OperandType (ibid.).  The encoding indicates how to read it from the
49 //    instruction; the type indicates how to interpret the value once it has
50 //    been read.  For example, a register operand could be stored in the R/M
51 //    field of the ModR/M byte, the REG field of the ModR/M byte, or added to
52 //    the main opcode.  This is orthogonal from its meaning (an GPR or an XMM
53 //    register, for instance).  Given this information, the operands can be
54 //    extracted and interpreted.
55 //
56 // 7. As the last step, the disassembler translates the instruction information
57 //    and operands into a format understandable by the client - in this case, an
58 //    MCInst for use by the MC infrastructure.
59 //
60 // The disassembler is broken broadly into two parts: the table emitter that
61 // emits the instruction decode tables discussed above during compilation, and
62 // the disassembler itself.  The table emitter is documented in more detail in
63 // utils/TableGen/X86DisassemblerEmitter.h.
64 //
65 // X86Disassembler.cpp contains the code responsible for step 7, and for
66 //   invoking the decoder to execute steps 1-6.
67 // X86DisassemblerDecoderCommon.h contains the definitions needed by both the
68 //   table emitter and the disassembler.
69 // X86DisassemblerDecoder.h contains the public interface of the decoder,
70 //   factored out into C for possible use by other projects.
71 // X86DisassemblerDecoder.c contains the source code of the decoder, which is
72 //   responsible for steps 1-6.
73 //
74 //===----------------------------------------------------------------------===//
75 
76 #include "MCTargetDesc/X86BaseInfo.h"
77 #include "MCTargetDesc/X86MCTargetDesc.h"
78 #include "TargetInfo/X86TargetInfo.h"
79 #include "X86DisassemblerDecoder.h"
80 #include "llvm/MC/MCContext.h"
81 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
82 #include "llvm/MC/MCExpr.h"
83 #include "llvm/MC/MCInst.h"
84 #include "llvm/MC/MCInstrInfo.h"
85 #include "llvm/MC/MCSubtargetInfo.h"
86 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/TargetRegistry.h"
89 #include "llvm/Support/raw_ostream.h"
90 
91 using namespace llvm;
92 using namespace llvm::X86Disassembler;
93 
94 #define DEBUG_TYPE "x86-disassembler"
95 
96 #define debug(s) LLVM_DEBUG(dbgs() << __LINE__ << ": " << s);
97 
98 // Specifies whether a ModR/M byte is needed and (if so) which
99 // instruction each possible value of the ModR/M byte corresponds to.  Once
100 // this information is known, we have narrowed down to a single instruction.
101 struct ModRMDecision {
102   uint8_t modrm_type;
103   uint16_t instructionIDs;
104 };
105 
106 // Specifies which set of ModR/M->instruction tables to look at
107 // given a particular opcode.
108 struct OpcodeDecision {
109   ModRMDecision modRMDecisions[256];
110 };
111 
112 // Specifies which opcode->instruction tables to look at given
113 // a particular context (set of attributes).  Since there are many possible
114 // contexts, the decoder first uses CONTEXTS_SYM to determine which context
115 // applies given a specific set of attributes.  Hence there are only IC_max
116 // entries in this table, rather than 2^(ATTR_max).
117 struct ContextDecision {
118   OpcodeDecision opcodeDecisions[IC_max];
119 };
120 
121 #include "X86GenDisassemblerTables.inc"
122 
123 static InstrUID decode(OpcodeType type, InstructionContext insnContext,
124                        uint8_t opcode, uint8_t modRM) {
125   const struct ModRMDecision *dec;
126 
127   switch (type) {
128   case ONEBYTE:
129     dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
130     break;
131   case TWOBYTE:
132     dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
133     break;
134   case THREEBYTE_38:
135     dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
136     break;
137   case THREEBYTE_3A:
138     dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
139     break;
140   case XOP8_MAP:
141     dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
142     break;
143   case XOP9_MAP:
144     dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
145     break;
146   case XOPA_MAP:
147     dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
148     break;
149   case THREEDNOW_MAP:
150     dec =
151         &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
152     break;
153   }
154 
155   switch (dec->modrm_type) {
156   default:
157     llvm_unreachable("Corrupt table!  Unknown modrm_type");
158     return 0;
159   case MODRM_ONEENTRY:
160     return modRMTable[dec->instructionIDs];
161   case MODRM_SPLITRM:
162     if (modFromModRM(modRM) == 0x3)
163       return modRMTable[dec->instructionIDs + 1];
164     return modRMTable[dec->instructionIDs];
165   case MODRM_SPLITREG:
166     if (modFromModRM(modRM) == 0x3)
167       return modRMTable[dec->instructionIDs + ((modRM & 0x38) >> 3) + 8];
168     return modRMTable[dec->instructionIDs + ((modRM & 0x38) >> 3)];
169   case MODRM_SPLITMISC:
170     if (modFromModRM(modRM) == 0x3)
171       return modRMTable[dec->instructionIDs + (modRM & 0x3f) + 8];
172     return modRMTable[dec->instructionIDs + ((modRM & 0x38) >> 3)];
173   case MODRM_FULL:
174     return modRMTable[dec->instructionIDs + modRM];
175   }
176 }
177 
178 static bool peek(struct InternalInstruction *insn, uint8_t &byte) {
179   uint64_t offset = insn->readerCursor - insn->startLocation;
180   if (offset >= insn->bytes.size())
181     return true;
182   byte = insn->bytes[offset];
183   return false;
184 }
185 
186 template <typename T> static bool consume(InternalInstruction *insn, T &ptr) {
187   auto r = insn->bytes;
188   uint64_t offset = insn->readerCursor - insn->startLocation;
189   if (offset + sizeof(T) > r.size())
190     return true;
191   T ret = 0;
192   for (unsigned i = 0; i < sizeof(T); ++i)
193     ret |= (uint64_t)r[offset + i] << (i * 8);
194   ptr = ret;
195   insn->readerCursor += sizeof(T);
196   return false;
197 }
198 
199 static bool isREX(struct InternalInstruction *insn, uint8_t prefix) {
200   return insn->mode == MODE_64BIT && prefix >= 0x40 && prefix <= 0x4f;
201 }
202 
203 // Consumes all of an instruction's prefix bytes, and marks the
204 // instruction as having them.  Also sets the instruction's default operand,
205 // address, and other relevant data sizes to report operands correctly.
206 static int readPrefixes(struct InternalInstruction *insn) {
207   bool isPrefix = true;
208   uint8_t byte = 0;
209   uint8_t nextByte;
210 
211   LLVM_DEBUG(dbgs() << "readPrefixes()");
212 
213   while (isPrefix) {
214     // If we fail reading prefixes, just stop here and let the opcode reader
215     // deal with it.
216     if (consume(insn, byte))
217       break;
218 
219     // If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
220     // break and let it be disassembled as a normal "instruction".
221     if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0) // LOCK
222       break;
223 
224     if ((byte == 0xf2 || byte == 0xf3) && !peek(insn, nextByte)) {
225       // If the byte is 0xf2 or 0xf3, and any of the following conditions are
226       // met:
227       // - it is followed by a LOCK (0xf0) prefix
228       // - it is followed by an xchg instruction
229       // then it should be disassembled as a xacquire/xrelease not repne/rep.
230       if (((nextByte == 0xf0) ||
231            ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
232         insn->xAcquireRelease = true;
233         if (!(byte == 0xf3 && nextByte == 0x90)) // PAUSE instruction support
234           break;
235       }
236       // Also if the byte is 0xf3, and the following condition is met:
237       // - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
238       //                       "mov mem, imm" (opcode 0xc6/0xc7) instructions.
239       // then it should be disassembled as an xrelease not rep.
240       if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
241                            nextByte == 0xc6 || nextByte == 0xc7)) {
242         insn->xAcquireRelease = true;
243         break;
244       }
245       if (isREX(insn, nextByte)) {
246         uint8_t nnextByte;
247         // Go to REX prefix after the current one
248         if (consume(insn, nnextByte))
249           return -1;
250         // We should be able to read next byte after REX prefix
251         if (peek(insn, nnextByte))
252           return -1;
253         --insn->readerCursor;
254       }
255     }
256 
257     switch (byte) {
258     case 0xf0: // LOCK
259       insn->hasLockPrefix = true;
260       break;
261     case 0xf2: // REPNE/REPNZ
262     case 0xf3: { // REP or REPE/REPZ
263       uint8_t nextByte;
264       if (peek(insn, nextByte))
265         break;
266       // TODO:
267       //  1. There could be several 0x66
268       //  2. if (nextByte == 0x66) and nextNextByte != 0x0f then
269       //      it's not mandatory prefix
270       //  3. if (nextByte >= 0x40 && nextByte <= 0x4f) it's REX and we need
271       //     0x0f exactly after it to be mandatory prefix
272       if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
273         // The last of 0xf2 /0xf3 is mandatory prefix
274         insn->mandatoryPrefix = byte;
275       insn->repeatPrefix = byte;
276       break;
277     }
278     case 0x2e: // CS segment override -OR- Branch not taken
279       insn->segmentOverride = SEG_OVERRIDE_CS;
280       break;
281     case 0x36: // SS segment override -OR- Branch taken
282       insn->segmentOverride = SEG_OVERRIDE_SS;
283       break;
284     case 0x3e: // DS segment override
285       insn->segmentOverride = SEG_OVERRIDE_DS;
286       break;
287     case 0x26: // ES segment override
288       insn->segmentOverride = SEG_OVERRIDE_ES;
289       break;
290     case 0x64: // FS segment override
291       insn->segmentOverride = SEG_OVERRIDE_FS;
292       break;
293     case 0x65: // GS segment override
294       insn->segmentOverride = SEG_OVERRIDE_GS;
295       break;
296     case 0x66: { // Operand-size override {
297       uint8_t nextByte;
298       insn->hasOpSize = true;
299       if (peek(insn, nextByte))
300         break;
301       // 0x66 can't overwrite existing mandatory prefix and should be ignored
302       if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
303         insn->mandatoryPrefix = byte;
304       break;
305     }
306     case 0x67: // Address-size override
307       insn->hasAdSize = true;
308       break;
309     default: // Not a prefix byte
310       isPrefix = false;
311       break;
312     }
313 
314     if (isPrefix)
315       LLVM_DEBUG(dbgs() << format("Found prefix 0x%hhx", byte));
316   }
317 
318   insn->vectorExtensionType = TYPE_NO_VEX_XOP;
319 
320   if (byte == 0x62) {
321     uint8_t byte1, byte2;
322     if (consume(insn, byte1)) {
323       LLVM_DEBUG(dbgs() << "Couldn't read second byte of EVEX prefix");
324       return -1;
325     }
326 
327     if (peek(insn, byte2)) {
328       LLVM_DEBUG(dbgs() << "Couldn't read third byte of EVEX prefix");
329       return -1;
330     }
331 
332     if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
333         ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
334       insn->vectorExtensionType = TYPE_EVEX;
335     } else {
336       --insn->readerCursor; // unconsume byte1
337       --insn->readerCursor; // unconsume byte
338     }
339 
340     if (insn->vectorExtensionType == TYPE_EVEX) {
341       insn->vectorExtensionPrefix[0] = byte;
342       insn->vectorExtensionPrefix[1] = byte1;
343       if (consume(insn, insn->vectorExtensionPrefix[2])) {
344         LLVM_DEBUG(dbgs() << "Couldn't read third byte of EVEX prefix");
345         return -1;
346       }
347       if (consume(insn, insn->vectorExtensionPrefix[3])) {
348         LLVM_DEBUG(dbgs() << "Couldn't read fourth byte of EVEX prefix");
349         return -1;
350       }
351 
352       // We simulate the REX prefix for simplicity's sake
353       if (insn->mode == MODE_64BIT) {
354         insn->rexPrefix = 0x40 |
355                           (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3) |
356                           (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2) |
357                           (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1) |
358                           (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
359       }
360 
361       LLVM_DEBUG(
362           dbgs() << format(
363               "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
364               insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
365               insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]));
366     }
367   } else if (byte == 0xc4) {
368     uint8_t byte1;
369     if (peek(insn, byte1)) {
370       LLVM_DEBUG(dbgs() << "Couldn't read second byte of VEX");
371       return -1;
372     }
373 
374     if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
375       insn->vectorExtensionType = TYPE_VEX_3B;
376     else
377       --insn->readerCursor;
378 
379     if (insn->vectorExtensionType == TYPE_VEX_3B) {
380       insn->vectorExtensionPrefix[0] = byte;
381       consume(insn, insn->vectorExtensionPrefix[1]);
382       consume(insn, insn->vectorExtensionPrefix[2]);
383 
384       // We simulate the REX prefix for simplicity's sake
385 
386       if (insn->mode == MODE_64BIT)
387         insn->rexPrefix = 0x40 |
388                           (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3) |
389                           (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2) |
390                           (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1) |
391                           (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
392 
393       LLVM_DEBUG(dbgs() << format("Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
394                                   insn->vectorExtensionPrefix[0],
395                                   insn->vectorExtensionPrefix[1],
396                                   insn->vectorExtensionPrefix[2]));
397     }
398   } else if (byte == 0xc5) {
399     uint8_t byte1;
400     if (peek(insn, byte1)) {
401       LLVM_DEBUG(dbgs() << "Couldn't read second byte of VEX");
402       return -1;
403     }
404 
405     if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
406       insn->vectorExtensionType = TYPE_VEX_2B;
407     else
408       --insn->readerCursor;
409 
410     if (insn->vectorExtensionType == TYPE_VEX_2B) {
411       insn->vectorExtensionPrefix[0] = byte;
412       consume(insn, insn->vectorExtensionPrefix[1]);
413 
414       if (insn->mode == MODE_64BIT)
415         insn->rexPrefix =
416             0x40 | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
417 
418       switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
419       default:
420         break;
421       case VEX_PREFIX_66:
422         insn->hasOpSize = true;
423         break;
424       }
425 
426       LLVM_DEBUG(dbgs() << format("Found VEX prefix 0x%hhx 0x%hhx",
427                                   insn->vectorExtensionPrefix[0],
428                                   insn->vectorExtensionPrefix[1]));
429     }
430   } else if (byte == 0x8f) {
431     uint8_t byte1;
432     if (peek(insn, byte1)) {
433       LLVM_DEBUG(dbgs() << "Couldn't read second byte of XOP");
434       return -1;
435     }
436 
437     if ((byte1 & 0x38) != 0x0) // 0 in these 3 bits is a POP instruction.
438       insn->vectorExtensionType = TYPE_XOP;
439     else
440       --insn->readerCursor;
441 
442     if (insn->vectorExtensionType == TYPE_XOP) {
443       insn->vectorExtensionPrefix[0] = byte;
444       consume(insn, insn->vectorExtensionPrefix[1]);
445       consume(insn, insn->vectorExtensionPrefix[2]);
446 
447       // We simulate the REX prefix for simplicity's sake
448 
449       if (insn->mode == MODE_64BIT)
450         insn->rexPrefix = 0x40 |
451                           (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3) |
452                           (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2) |
453                           (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1) |
454                           (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
455 
456       switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
457       default:
458         break;
459       case VEX_PREFIX_66:
460         insn->hasOpSize = true;
461         break;
462       }
463 
464       LLVM_DEBUG(dbgs() << format("Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
465                                   insn->vectorExtensionPrefix[0],
466                                   insn->vectorExtensionPrefix[1],
467                                   insn->vectorExtensionPrefix[2]));
468     }
469   } else if (isREX(insn, byte)) {
470     if (peek(insn, nextByte))
471       return -1;
472     insn->rexPrefix = byte;
473     LLVM_DEBUG(dbgs() << format("Found REX prefix 0x%hhx", byte));
474   } else
475     --insn->readerCursor;
476 
477   if (insn->mode == MODE_16BIT) {
478     insn->registerSize = (insn->hasOpSize ? 4 : 2);
479     insn->addressSize = (insn->hasAdSize ? 4 : 2);
480     insn->displacementSize = (insn->hasAdSize ? 4 : 2);
481     insn->immediateSize = (insn->hasOpSize ? 4 : 2);
482   } else if (insn->mode == MODE_32BIT) {
483     insn->registerSize = (insn->hasOpSize ? 2 : 4);
484     insn->addressSize = (insn->hasAdSize ? 2 : 4);
485     insn->displacementSize = (insn->hasAdSize ? 2 : 4);
486     insn->immediateSize = (insn->hasOpSize ? 2 : 4);
487   } else if (insn->mode == MODE_64BIT) {
488     if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
489       insn->registerSize = 8;
490       insn->addressSize = (insn->hasAdSize ? 4 : 8);
491       insn->displacementSize = 4;
492       insn->immediateSize = 4;
493     } else {
494       insn->registerSize = (insn->hasOpSize ? 2 : 4);
495       insn->addressSize = (insn->hasAdSize ? 4 : 8);
496       insn->displacementSize = (insn->hasOpSize ? 2 : 4);
497       insn->immediateSize = (insn->hasOpSize ? 2 : 4);
498     }
499   }
500 
501   return 0;
502 }
503 
504 // Consumes the SIB byte to determine addressing information.
505 static int readSIB(struct InternalInstruction *insn) {
506   SIBBase sibBaseBase = SIB_BASE_NONE;
507   uint8_t index, base;
508 
509   LLVM_DEBUG(dbgs() << "readSIB()");
510   switch (insn->addressSize) {
511   case 2:
512   default:
513     llvm_unreachable("SIB-based addressing doesn't work in 16-bit mode");
514   case 4:
515     insn->sibIndexBase = SIB_INDEX_EAX;
516     sibBaseBase = SIB_BASE_EAX;
517     break;
518   case 8:
519     insn->sibIndexBase = SIB_INDEX_RAX;
520     sibBaseBase = SIB_BASE_RAX;
521     break;
522   }
523 
524   if (consume(insn, insn->sib))
525     return -1;
526 
527   index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
528 
529   if (index == 0x4) {
530     insn->sibIndex = SIB_INDEX_NONE;
531   } else {
532     insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
533   }
534 
535   insn->sibScale = 1 << scaleFromSIB(insn->sib);
536 
537   base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
538 
539   switch (base) {
540   case 0x5:
541   case 0xd:
542     switch (modFromModRM(insn->modRM)) {
543     case 0x0:
544       insn->eaDisplacement = EA_DISP_32;
545       insn->sibBase = SIB_BASE_NONE;
546       break;
547     case 0x1:
548       insn->eaDisplacement = EA_DISP_8;
549       insn->sibBase = (SIBBase)(sibBaseBase + base);
550       break;
551     case 0x2:
552       insn->eaDisplacement = EA_DISP_32;
553       insn->sibBase = (SIBBase)(sibBaseBase + base);
554       break;
555     default:
556       llvm_unreachable("Cannot have Mod = 0b11 and a SIB byte");
557     }
558     break;
559   default:
560     insn->sibBase = (SIBBase)(sibBaseBase + base);
561     break;
562   }
563 
564   return 0;
565 }
566 
567 static int readDisplacement(struct InternalInstruction *insn) {
568   int8_t d8;
569   int16_t d16;
570   int32_t d32;
571   LLVM_DEBUG(dbgs() << "readDisplacement()");
572 
573   insn->displacementOffset = insn->readerCursor - insn->startLocation;
574   switch (insn->eaDisplacement) {
575   case EA_DISP_NONE:
576     break;
577   case EA_DISP_8:
578     if (consume(insn, d8))
579       return -1;
580     insn->displacement = d8;
581     break;
582   case EA_DISP_16:
583     if (consume(insn, d16))
584       return -1;
585     insn->displacement = d16;
586     break;
587   case EA_DISP_32:
588     if (consume(insn, d32))
589       return -1;
590     insn->displacement = d32;
591     break;
592   }
593 
594   return 0;
595 }
596 
597 // Consumes all addressing information (ModR/M byte, SIB byte, and displacement.
598 static int readModRM(struct InternalInstruction *insn) {
599   uint8_t mod, rm, reg, evexrm;
600   LLVM_DEBUG(dbgs() << "readModRM()");
601 
602   if (insn->consumedModRM)
603     return 0;
604 
605   if (consume(insn, insn->modRM))
606     return -1;
607   insn->consumedModRM = true;
608 
609   mod = modFromModRM(insn->modRM);
610   rm = rmFromModRM(insn->modRM);
611   reg = regFromModRM(insn->modRM);
612 
613   // This goes by insn->registerSize to pick the correct register, which messes
614   // up if we're using (say) XMM or 8-bit register operands. That gets fixed in
615   // fixupReg().
616   switch (insn->registerSize) {
617   case 2:
618     insn->regBase = MODRM_REG_AX;
619     insn->eaRegBase = EA_REG_AX;
620     break;
621   case 4:
622     insn->regBase = MODRM_REG_EAX;
623     insn->eaRegBase = EA_REG_EAX;
624     break;
625   case 8:
626     insn->regBase = MODRM_REG_RAX;
627     insn->eaRegBase = EA_REG_RAX;
628     break;
629   }
630 
631   reg |= rFromREX(insn->rexPrefix) << 3;
632   rm |= bFromREX(insn->rexPrefix) << 3;
633 
634   evexrm = 0;
635   if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT) {
636     reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
637     evexrm = xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
638   }
639 
640   insn->reg = (Reg)(insn->regBase + reg);
641 
642   switch (insn->addressSize) {
643   case 2: {
644     EABase eaBaseBase = EA_BASE_BX_SI;
645 
646     switch (mod) {
647     case 0x0:
648       if (rm == 0x6) {
649         insn->eaBase = EA_BASE_NONE;
650         insn->eaDisplacement = EA_DISP_16;
651         if (readDisplacement(insn))
652           return -1;
653       } else {
654         insn->eaBase = (EABase)(eaBaseBase + rm);
655         insn->eaDisplacement = EA_DISP_NONE;
656       }
657       break;
658     case 0x1:
659       insn->eaBase = (EABase)(eaBaseBase + rm);
660       insn->eaDisplacement = EA_DISP_8;
661       insn->displacementSize = 1;
662       if (readDisplacement(insn))
663         return -1;
664       break;
665     case 0x2:
666       insn->eaBase = (EABase)(eaBaseBase + rm);
667       insn->eaDisplacement = EA_DISP_16;
668       if (readDisplacement(insn))
669         return -1;
670       break;
671     case 0x3:
672       insn->eaBase = (EABase)(insn->eaRegBase + rm);
673       if (readDisplacement(insn))
674         return -1;
675       break;
676     }
677     break;
678   }
679   case 4:
680   case 8: {
681     EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
682 
683     switch (mod) {
684     case 0x0:
685       insn->eaDisplacement = EA_DISP_NONE; // readSIB may override this
686       // In determining whether RIP-relative mode is used (rm=5),
687       // or whether a SIB byte is present (rm=4),
688       // the extension bits (REX.b and EVEX.x) are ignored.
689       switch (rm & 7) {
690       case 0x4: // SIB byte is present
691         insn->eaBase = (insn->addressSize == 4 ? EA_BASE_sib : EA_BASE_sib64);
692         if (readSIB(insn) || readDisplacement(insn))
693           return -1;
694         break;
695       case 0x5: // RIP-relative
696         insn->eaBase = EA_BASE_NONE;
697         insn->eaDisplacement = EA_DISP_32;
698         if (readDisplacement(insn))
699           return -1;
700         break;
701       default:
702         insn->eaBase = (EABase)(eaBaseBase + rm);
703         break;
704       }
705       break;
706     case 0x1:
707       insn->displacementSize = 1;
708       LLVM_FALLTHROUGH;
709     case 0x2:
710       insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
711       switch (rm & 7) {
712       case 0x4: // SIB byte is present
713         insn->eaBase = EA_BASE_sib;
714         if (readSIB(insn) || readDisplacement(insn))
715           return -1;
716         break;
717       default:
718         insn->eaBase = (EABase)(eaBaseBase + rm);
719         if (readDisplacement(insn))
720           return -1;
721         break;
722       }
723       break;
724     case 0x3:
725       insn->eaDisplacement = EA_DISP_NONE;
726       insn->eaBase = (EABase)(insn->eaRegBase + rm + evexrm);
727       break;
728     }
729     break;
730   }
731   } // switch (insn->addressSize)
732 
733   return 0;
734 }
735 
736 #define GENERIC_FIXUP_FUNC(name, base, prefix, mask)                           \
737   static uint16_t name(struct InternalInstruction *insn, OperandType type,     \
738                        uint8_t index, uint8_t *valid) {                        \
739     *valid = 1;                                                                \
740     switch (type) {                                                            \
741     default:                                                                   \
742       debug("Unhandled register type");                                        \
743       *valid = 0;                                                              \
744       return 0;                                                                \
745     case TYPE_Rv:                                                              \
746       return base + index;                                                     \
747     case TYPE_R8:                                                              \
748       index &= mask;                                                           \
749       if (index > 0xf)                                                         \
750         *valid = 0;                                                            \
751       if (insn->rexPrefix && index >= 4 && index <= 7) {                       \
752         return prefix##_SPL + (index - 4);                                     \
753       } else {                                                                 \
754         return prefix##_AL + index;                                            \
755       }                                                                        \
756     case TYPE_R16:                                                             \
757       index &= mask;                                                           \
758       if (index > 0xf)                                                         \
759         *valid = 0;                                                            \
760       return prefix##_AX + index;                                              \
761     case TYPE_R32:                                                             \
762       index &= mask;                                                           \
763       if (index > 0xf)                                                         \
764         *valid = 0;                                                            \
765       return prefix##_EAX + index;                                             \
766     case TYPE_R64:                                                             \
767       index &= mask;                                                           \
768       if (index > 0xf)                                                         \
769         *valid = 0;                                                            \
770       return prefix##_RAX + index;                                             \
771     case TYPE_ZMM:                                                             \
772       return prefix##_ZMM0 + index;                                            \
773     case TYPE_YMM:                                                             \
774       return prefix##_YMM0 + index;                                            \
775     case TYPE_XMM:                                                             \
776       return prefix##_XMM0 + index;                                            \
777     case TYPE_VK:                                                              \
778       index &= 0xf;                                                            \
779       if (index > 7)                                                           \
780         *valid = 0;                                                            \
781       return prefix##_K0 + index;                                              \
782     case TYPE_VK_PAIR:                                                         \
783       if (index > 7)                                                           \
784         *valid = 0;                                                            \
785       return prefix##_K0_K1 + (index / 2);                                     \
786     case TYPE_MM64:                                                            \
787       return prefix##_MM0 + (index & 0x7);                                     \
788     case TYPE_SEGMENTREG:                                                      \
789       if ((index & 7) > 5)                                                     \
790         *valid = 0;                                                            \
791       return prefix##_ES + (index & 7);                                        \
792     case TYPE_DEBUGREG:                                                        \
793       return prefix##_DR0 + index;                                             \
794     case TYPE_CONTROLREG:                                                      \
795       return prefix##_CR0 + index;                                             \
796     case TYPE_BNDR:                                                            \
797       if (index > 3)                                                           \
798         *valid = 0;                                                            \
799       return prefix##_BND0 + index;                                            \
800     case TYPE_MVSIBX:                                                          \
801       return prefix##_XMM0 + index;                                            \
802     case TYPE_MVSIBY:                                                          \
803       return prefix##_YMM0 + index;                                            \
804     case TYPE_MVSIBZ:                                                          \
805       return prefix##_ZMM0 + index;                                            \
806     }                                                                          \
807   }
808 
809 // Consult an operand type to determine the meaning of the reg or R/M field. If
810 // the operand is an XMM operand, for example, an operand would be XMM0 instead
811 // of AX, which readModRM() would otherwise misinterpret it as.
812 //
813 // @param insn  - The instruction containing the operand.
814 // @param type  - The operand type.
815 // @param index - The existing value of the field as reported by readModRM().
816 // @param valid - The address of a uint8_t.  The target is set to 1 if the
817 //                field is valid for the register class; 0 if not.
818 // @return      - The proper value.
819 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG, 0x1f)
820 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG, 0xf)
821 
822 // Consult an operand specifier to determine which of the fixup*Value functions
823 // to use in correcting readModRM()'ss interpretation.
824 //
825 // @param insn  - See fixup*Value().
826 // @param op    - The operand specifier.
827 // @return      - 0 if fixup was successful; -1 if the register returned was
828 //                invalid for its class.
829 static int fixupReg(struct InternalInstruction *insn,
830                     const struct OperandSpecifier *op) {
831   uint8_t valid;
832   LLVM_DEBUG(dbgs() << "fixupReg()");
833 
834   switch ((OperandEncoding)op->encoding) {
835   default:
836     debug("Expected a REG or R/M encoding in fixupReg");
837     return -1;
838   case ENCODING_VVVV:
839     insn->vvvv =
840         (Reg)fixupRegValue(insn, (OperandType)op->type, insn->vvvv, &valid);
841     if (!valid)
842       return -1;
843     break;
844   case ENCODING_REG:
845     insn->reg = (Reg)fixupRegValue(insn, (OperandType)op->type,
846                                    insn->reg - insn->regBase, &valid);
847     if (!valid)
848       return -1;
849     break;
850   CASE_ENCODING_RM:
851     if (insn->eaBase >= insn->eaRegBase) {
852       insn->eaBase = (EABase)fixupRMValue(
853           insn, (OperandType)op->type, insn->eaBase - insn->eaRegBase, &valid);
854       if (!valid)
855         return -1;
856     }
857     break;
858   }
859 
860   return 0;
861 }
862 
863 // Read the opcode (except the ModR/M byte in the case of extended or escape
864 // opcodes).
865 static bool readOpcode(struct InternalInstruction *insn) {
866   uint8_t current;
867   LLVM_DEBUG(dbgs() << "readOpcode()");
868 
869   insn->opcodeType = ONEBYTE;
870   if (insn->vectorExtensionType == TYPE_EVEX) {
871     switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
872     default:
873       LLVM_DEBUG(
874           dbgs() << format("Unhandled mm field for instruction (0x%hhx)",
875                            mmFromEVEX2of4(insn->vectorExtensionPrefix[1])));
876       return true;
877     case VEX_LOB_0F:
878       insn->opcodeType = TWOBYTE;
879       return consume(insn, insn->opcode);
880     case VEX_LOB_0F38:
881       insn->opcodeType = THREEBYTE_38;
882       return consume(insn, insn->opcode);
883     case VEX_LOB_0F3A:
884       insn->opcodeType = THREEBYTE_3A;
885       return consume(insn, insn->opcode);
886     }
887   } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
888     switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
889     default:
890       LLVM_DEBUG(
891           dbgs() << format("Unhandled m-mmmm field for instruction (0x%hhx)",
892                            mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])));
893       return true;
894     case VEX_LOB_0F:
895       insn->opcodeType = TWOBYTE;
896       return consume(insn, insn->opcode);
897     case VEX_LOB_0F38:
898       insn->opcodeType = THREEBYTE_38;
899       return consume(insn, insn->opcode);
900     case VEX_LOB_0F3A:
901       insn->opcodeType = THREEBYTE_3A;
902       return consume(insn, insn->opcode);
903     }
904   } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
905     insn->opcodeType = TWOBYTE;
906     return consume(insn, insn->opcode);
907   } else if (insn->vectorExtensionType == TYPE_XOP) {
908     switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
909     default:
910       LLVM_DEBUG(
911           dbgs() << format("Unhandled m-mmmm field for instruction (0x%hhx)",
912                            mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])));
913       return true;
914     case XOP_MAP_SELECT_8:
915       insn->opcodeType = XOP8_MAP;
916       return consume(insn, insn->opcode);
917     case XOP_MAP_SELECT_9:
918       insn->opcodeType = XOP9_MAP;
919       return consume(insn, insn->opcode);
920     case XOP_MAP_SELECT_A:
921       insn->opcodeType = XOPA_MAP;
922       return consume(insn, insn->opcode);
923     }
924   }
925 
926   if (consume(insn, current))
927     return true;
928 
929   if (current == 0x0f) {
930     LLVM_DEBUG(
931         dbgs() << format("Found a two-byte escape prefix (0x%hhx)", current));
932     if (consume(insn, current))
933       return true;
934 
935     if (current == 0x38) {
936       LLVM_DEBUG(dbgs() << format("Found a three-byte escape prefix (0x%hhx)",
937                                   current));
938       if (consume(insn, current))
939         return -1;
940 
941       insn->opcodeType = THREEBYTE_38;
942     } else if (current == 0x3a) {
943       LLVM_DEBUG(dbgs() << format("Found a three-byte escape prefix (0x%hhx)",
944                                   current));
945       if (consume(insn, current))
946         return -1;
947 
948       insn->opcodeType = THREEBYTE_3A;
949     } else if (current == 0x0f) {
950       LLVM_DEBUG(
951           dbgs() << format("Found a 3dnow escape prefix (0x%hhx)", current));
952 
953       // Consume operands before the opcode to comply with the 3DNow encoding
954       if (readModRM(insn))
955         return true;
956 
957       if (consume(insn, current))
958         return true;
959 
960       insn->opcodeType = THREEDNOW_MAP;
961     } else {
962       LLVM_DEBUG(dbgs() << "Didn't find a three-byte escape prefix");
963       insn->opcodeType = TWOBYTE;
964     }
965   } else if (insn->mandatoryPrefix)
966     // The opcode with mandatory prefix must start with opcode escape.
967     // If not it's legacy repeat prefix
968     insn->mandatoryPrefix = 0;
969 
970   // At this point we have consumed the full opcode.
971   // Anything we consume from here on must be unconsumed.
972   insn->opcode = current;
973 
974   return false;
975 }
976 
977 // Determine whether equiv is the 16-bit equivalent of orig (32-bit or 64-bit).
978 static bool is16BitEquivalent(const char *orig, const char *equiv) {
979   for (int i = 0;; i++) {
980     if (orig[i] == '\0' && equiv[i] == '\0')
981       return true;
982     if (orig[i] == '\0' || equiv[i] == '\0')
983       return false;
984     if (orig[i] != equiv[i]) {
985       if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
986         continue;
987       if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
988         continue;
989       if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
990         continue;
991       return false;
992     }
993   }
994 }
995 
996 // Determine whether this instruction is a 64-bit instruction.
997 static bool is64Bit(const char *name) {
998   for (int i = 0;; ++i) {
999     if (name[i] == '\0')
1000       return false;
1001     if (name[i] == '6' && name[i + 1] == '4')
1002       return true;
1003   }
1004 }
1005 
1006 // Determine the ID of an instruction, consuming the ModR/M byte as appropriate
1007 // for extended and escape opcodes, and using a supplied attribute mask.
1008 static int getInstructionIDWithAttrMask(uint16_t *instructionID,
1009                                         struct InternalInstruction *insn,
1010                                         uint16_t attrMask) {
1011   auto insnCtx = InstructionContext(x86DisassemblerContexts[attrMask]);
1012   const ContextDecision *decision;
1013   switch (insn->opcodeType) {
1014   case ONEBYTE:
1015     decision = &ONEBYTE_SYM;
1016     break;
1017   case TWOBYTE:
1018     decision = &TWOBYTE_SYM;
1019     break;
1020   case THREEBYTE_38:
1021     decision = &THREEBYTE38_SYM;
1022     break;
1023   case THREEBYTE_3A:
1024     decision = &THREEBYTE3A_SYM;
1025     break;
1026   case XOP8_MAP:
1027     decision = &XOP8_MAP_SYM;
1028     break;
1029   case XOP9_MAP:
1030     decision = &XOP9_MAP_SYM;
1031     break;
1032   case XOPA_MAP:
1033     decision = &XOPA_MAP_SYM;
1034     break;
1035   case THREEDNOW_MAP:
1036     decision = &THREEDNOW_MAP_SYM;
1037     break;
1038   }
1039 
1040   if (decision->opcodeDecisions[insnCtx]
1041           .modRMDecisions[insn->opcode]
1042           .modrm_type != MODRM_ONEENTRY) {
1043     if (readModRM(insn))
1044       return -1;
1045     *instructionID =
1046         decode(insn->opcodeType, insnCtx, insn->opcode, insn->modRM);
1047   } else {
1048     *instructionID = decode(insn->opcodeType, insnCtx, insn->opcode, 0);
1049   }
1050 
1051   return 0;
1052 }
1053 
1054 // Determine the ID of an instruction, consuming the ModR/M byte as appropriate
1055 // for extended and escape opcodes. Determines the attributes and context for
1056 // the instruction before doing so.
1057 static int getInstructionID(struct InternalInstruction *insn,
1058                             const MCInstrInfo *mii) {
1059   uint16_t attrMask;
1060   uint16_t instructionID;
1061 
1062   LLVM_DEBUG(dbgs() << "getID()");
1063 
1064   attrMask = ATTR_NONE;
1065 
1066   if (insn->mode == MODE_64BIT)
1067     attrMask |= ATTR_64BIT;
1068 
1069   if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1070     attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
1071 
1072     if (insn->vectorExtensionType == TYPE_EVEX) {
1073       switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
1074       case VEX_PREFIX_66:
1075         attrMask |= ATTR_OPSIZE;
1076         break;
1077       case VEX_PREFIX_F3:
1078         attrMask |= ATTR_XS;
1079         break;
1080       case VEX_PREFIX_F2:
1081         attrMask |= ATTR_XD;
1082         break;
1083       }
1084 
1085       if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1086         attrMask |= ATTR_EVEXKZ;
1087       if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1088         attrMask |= ATTR_EVEXB;
1089       if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1090         attrMask |= ATTR_EVEXK;
1091       if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1092         attrMask |= ATTR_VEXL;
1093       if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1094         attrMask |= ATTR_EVEXL2;
1095     } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
1096       switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
1097       case VEX_PREFIX_66:
1098         attrMask |= ATTR_OPSIZE;
1099         break;
1100       case VEX_PREFIX_F3:
1101         attrMask |= ATTR_XS;
1102         break;
1103       case VEX_PREFIX_F2:
1104         attrMask |= ATTR_XD;
1105         break;
1106       }
1107 
1108       if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
1109         attrMask |= ATTR_VEXL;
1110     } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
1111       switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
1112       case VEX_PREFIX_66:
1113         attrMask |= ATTR_OPSIZE;
1114         break;
1115       case VEX_PREFIX_F3:
1116         attrMask |= ATTR_XS;
1117         break;
1118       case VEX_PREFIX_F2:
1119         attrMask |= ATTR_XD;
1120         break;
1121       }
1122 
1123       if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
1124         attrMask |= ATTR_VEXL;
1125     } else if (insn->vectorExtensionType == TYPE_XOP) {
1126       switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
1127       case VEX_PREFIX_66:
1128         attrMask |= ATTR_OPSIZE;
1129         break;
1130       case VEX_PREFIX_F3:
1131         attrMask |= ATTR_XS;
1132         break;
1133       case VEX_PREFIX_F2:
1134         attrMask |= ATTR_XD;
1135         break;
1136       }
1137 
1138       if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
1139         attrMask |= ATTR_VEXL;
1140     } else {
1141       return -1;
1142     }
1143   } else if (!insn->mandatoryPrefix) {
1144     // If we don't have mandatory prefix we should use legacy prefixes here
1145     if (insn->hasOpSize && (insn->mode != MODE_16BIT))
1146       attrMask |= ATTR_OPSIZE;
1147     if (insn->hasAdSize)
1148       attrMask |= ATTR_ADSIZE;
1149     if (insn->opcodeType == ONEBYTE) {
1150       if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
1151         // Special support for PAUSE
1152         attrMask |= ATTR_XS;
1153     } else {
1154       if (insn->repeatPrefix == 0xf2)
1155         attrMask |= ATTR_XD;
1156       else if (insn->repeatPrefix == 0xf3)
1157         attrMask |= ATTR_XS;
1158     }
1159   } else {
1160     switch (insn->mandatoryPrefix) {
1161     case 0xf2:
1162       attrMask |= ATTR_XD;
1163       break;
1164     case 0xf3:
1165       attrMask |= ATTR_XS;
1166       break;
1167     case 0x66:
1168       if (insn->mode != MODE_16BIT)
1169         attrMask |= ATTR_OPSIZE;
1170       break;
1171     case 0x67:
1172       attrMask |= ATTR_ADSIZE;
1173       break;
1174     }
1175   }
1176 
1177   if (insn->rexPrefix & 0x08) {
1178     attrMask |= ATTR_REXW;
1179     attrMask &= ~ATTR_ADSIZE;
1180   }
1181 
1182   if (insn->mode == MODE_16BIT) {
1183     // JCXZ/JECXZ need special handling for 16-bit mode because the meaning
1184     // of the AdSize prefix is inverted w.r.t. 32-bit mode.
1185     if (insn->opcodeType == ONEBYTE && insn->opcode == 0xE3)
1186       attrMask ^= ATTR_ADSIZE;
1187     // If we're in 16-bit mode and this is one of the relative jumps and opsize
1188     // prefix isn't present, we need to force the opsize attribute since the
1189     // prefix is inverted relative to 32-bit mode.
1190     if (!insn->hasOpSize && insn->opcodeType == ONEBYTE &&
1191         (insn->opcode == 0xE8 || insn->opcode == 0xE9))
1192       attrMask |= ATTR_OPSIZE;
1193 
1194     if (!insn->hasOpSize && insn->opcodeType == TWOBYTE &&
1195         insn->opcode >= 0x80 && insn->opcode <= 0x8F)
1196       attrMask |= ATTR_OPSIZE;
1197   }
1198 
1199 
1200   if (getInstructionIDWithAttrMask(&instructionID, insn, attrMask))
1201     return -1;
1202 
1203   // The following clauses compensate for limitations of the tables.
1204 
1205   if (insn->mode != MODE_64BIT &&
1206       insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1207     // The tables can't distinquish between cases where the W-bit is used to
1208     // select register size and cases where its a required part of the opcode.
1209     if ((insn->vectorExtensionType == TYPE_EVEX &&
1210          wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1211         (insn->vectorExtensionType == TYPE_VEX_3B &&
1212          wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1213         (insn->vectorExtensionType == TYPE_XOP &&
1214          wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1215 
1216       uint16_t instructionIDWithREXW;
1217       if (getInstructionIDWithAttrMask(&instructionIDWithREXW, insn,
1218                                        attrMask | ATTR_REXW)) {
1219         insn->instructionID = instructionID;
1220         insn->spec = &INSTRUCTIONS_SYM[instructionID];
1221         return 0;
1222       }
1223 
1224       auto SpecName = mii->getName(instructionIDWithREXW);
1225       // If not a 64-bit instruction. Switch the opcode.
1226       if (!is64Bit(SpecName.data())) {
1227         insn->instructionID = instructionIDWithREXW;
1228         insn->spec = &INSTRUCTIONS_SYM[instructionIDWithREXW];
1229         return 0;
1230       }
1231     }
1232   }
1233 
1234   // Absolute moves, umonitor, and movdir64b need special handling.
1235   // -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1236   //  inverted w.r.t.
1237   // -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1238   //  any position.
1239   if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1240       (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1241       (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1242     // Make sure we observed the prefixes in any position.
1243     if (insn->hasAdSize)
1244       attrMask |= ATTR_ADSIZE;
1245     if (insn->hasOpSize)
1246       attrMask |= ATTR_OPSIZE;
1247 
1248     // In 16-bit, invert the attributes.
1249     if (insn->mode == MODE_16BIT) {
1250       attrMask ^= ATTR_ADSIZE;
1251 
1252       // The OpSize attribute is only valid with the absolute moves.
1253       if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1254         attrMask ^= ATTR_OPSIZE;
1255     }
1256 
1257     if (getInstructionIDWithAttrMask(&instructionID, insn, attrMask))
1258       return -1;
1259 
1260     insn->instructionID = instructionID;
1261     insn->spec = &INSTRUCTIONS_SYM[instructionID];
1262     return 0;
1263   }
1264 
1265   if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1266       !(attrMask & ATTR_OPSIZE)) {
1267     // The instruction tables make no distinction between instructions that
1268     // allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1269     // particular spot (i.e., many MMX operations). In general we're
1270     // conservative, but in the specific case where OpSize is present but not in
1271     // the right place we check if there's a 16-bit operation.
1272     const struct InstructionSpecifier *spec;
1273     uint16_t instructionIDWithOpsize;
1274     llvm::StringRef specName, specWithOpSizeName;
1275 
1276     spec = &INSTRUCTIONS_SYM[instructionID];
1277 
1278     if (getInstructionIDWithAttrMask(&instructionIDWithOpsize, insn,
1279                                      attrMask | ATTR_OPSIZE)) {
1280       // ModRM required with OpSize but not present. Give up and return the
1281       // version without OpSize set.
1282       insn->instructionID = instructionID;
1283       insn->spec = spec;
1284       return 0;
1285     }
1286 
1287     specName = mii->getName(instructionID);
1288     specWithOpSizeName = mii->getName(instructionIDWithOpsize);
1289 
1290     if (is16BitEquivalent(specName.data(), specWithOpSizeName.data()) &&
1291         (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1292       insn->instructionID = instructionIDWithOpsize;
1293       insn->spec = &INSTRUCTIONS_SYM[instructionIDWithOpsize];
1294     } else {
1295       insn->instructionID = instructionID;
1296       insn->spec = spec;
1297     }
1298     return 0;
1299   }
1300 
1301   if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1302       insn->rexPrefix & 0x01) {
1303     // NOOP shouldn't decode as NOOP if REX.b is set. Instead it should decode
1304     // as XCHG %r8, %eax.
1305     const struct InstructionSpecifier *spec;
1306     uint16_t instructionIDWithNewOpcode;
1307     const struct InstructionSpecifier *specWithNewOpcode;
1308 
1309     spec = &INSTRUCTIONS_SYM[instructionID];
1310 
1311     // Borrow opcode from one of the other XCHGar opcodes
1312     insn->opcode = 0x91;
1313 
1314     if (getInstructionIDWithAttrMask(&instructionIDWithNewOpcode, insn,
1315                                      attrMask)) {
1316       insn->opcode = 0x90;
1317 
1318       insn->instructionID = instructionID;
1319       insn->spec = spec;
1320       return 0;
1321     }
1322 
1323     specWithNewOpcode = &INSTRUCTIONS_SYM[instructionIDWithNewOpcode];
1324 
1325     // Change back
1326     insn->opcode = 0x90;
1327 
1328     insn->instructionID = instructionIDWithNewOpcode;
1329     insn->spec = specWithNewOpcode;
1330 
1331     return 0;
1332   }
1333 
1334   insn->instructionID = instructionID;
1335   insn->spec = &INSTRUCTIONS_SYM[insn->instructionID];
1336 
1337   return 0;
1338 }
1339 
1340 // Read an operand from the opcode field of an instruction and interprets it
1341 // appropriately given the operand width. Handles AddRegFrm instructions.
1342 //
1343 // @param insn  - the instruction whose opcode field is to be read.
1344 // @param size  - The width (in bytes) of the register being specified.
1345 //                1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1346 //                RAX.
1347 // @return      - 0 on success; nonzero otherwise.
1348 static int readOpcodeRegister(struct InternalInstruction *insn, uint8_t size) {
1349   LLVM_DEBUG(dbgs() << "readOpcodeRegister()");
1350 
1351   if (size == 0)
1352     size = insn->registerSize;
1353 
1354   switch (size) {
1355   case 1:
1356     insn->opcodeRegister = (Reg)(
1357         MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1358     if (insn->rexPrefix && insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1359         insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1360       insn->opcodeRegister =
1361           (Reg)(MODRM_REG_SPL + (insn->opcodeRegister - MODRM_REG_AL - 4));
1362     }
1363 
1364     break;
1365   case 2:
1366     insn->opcodeRegister = (Reg)(
1367         MODRM_REG_AX + ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1368     break;
1369   case 4:
1370     insn->opcodeRegister =
1371         (Reg)(MODRM_REG_EAX +
1372               ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1373     break;
1374   case 8:
1375     insn->opcodeRegister =
1376         (Reg)(MODRM_REG_RAX +
1377               ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1378     break;
1379   }
1380 
1381   return 0;
1382 }
1383 
1384 // Consume an immediate operand from an instruction, given the desired operand
1385 // size.
1386 //
1387 // @param insn  - The instruction whose operand is to be read.
1388 // @param size  - The width (in bytes) of the operand.
1389 // @return      - 0 if the immediate was successfully consumed; nonzero
1390 //                otherwise.
1391 static int readImmediate(struct InternalInstruction *insn, uint8_t size) {
1392   uint8_t imm8;
1393   uint16_t imm16;
1394   uint32_t imm32;
1395   uint64_t imm64;
1396 
1397   LLVM_DEBUG(dbgs() << "readImmediate()");
1398 
1399   assert(insn->numImmediatesConsumed < 2 && "Already consumed two immediates");
1400 
1401   insn->immediateSize = size;
1402   insn->immediateOffset = insn->readerCursor - insn->startLocation;
1403 
1404   switch (size) {
1405   case 1:
1406     if (consume(insn, imm8))
1407       return -1;
1408     insn->immediates[insn->numImmediatesConsumed] = imm8;
1409     break;
1410   case 2:
1411     if (consume(insn, imm16))
1412       return -1;
1413     insn->immediates[insn->numImmediatesConsumed] = imm16;
1414     break;
1415   case 4:
1416     if (consume(insn, imm32))
1417       return -1;
1418     insn->immediates[insn->numImmediatesConsumed] = imm32;
1419     break;
1420   case 8:
1421     if (consume(insn, imm64))
1422       return -1;
1423     insn->immediates[insn->numImmediatesConsumed] = imm64;
1424     break;
1425   default:
1426     llvm_unreachable("invalid size");
1427   }
1428 
1429   insn->numImmediatesConsumed++;
1430 
1431   return 0;
1432 }
1433 
1434 // Consume vvvv from an instruction if it has a VEX prefix.
1435 static int readVVVV(struct InternalInstruction *insn) {
1436   LLVM_DEBUG(dbgs() << "readVVVV()");
1437 
1438   int vvvv;
1439   if (insn->vectorExtensionType == TYPE_EVEX)
1440     vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1441             vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1442   else if (insn->vectorExtensionType == TYPE_VEX_3B)
1443     vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1444   else if (insn->vectorExtensionType == TYPE_VEX_2B)
1445     vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1446   else if (insn->vectorExtensionType == TYPE_XOP)
1447     vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1448   else
1449     return -1;
1450 
1451   if (insn->mode != MODE_64BIT)
1452     vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1453 
1454   insn->vvvv = static_cast<Reg>(vvvv);
1455   return 0;
1456 }
1457 
1458 // Read an mask register from the opcode field of an instruction.
1459 //
1460 // @param insn    - The instruction whose opcode field is to be read.
1461 // @return        - 0 on success; nonzero otherwise.
1462 static int readMaskRegister(struct InternalInstruction *insn) {
1463   LLVM_DEBUG(dbgs() << "readMaskRegister()");
1464 
1465   if (insn->vectorExtensionType != TYPE_EVEX)
1466     return -1;
1467 
1468   insn->writemask =
1469       static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1470   return 0;
1471 }
1472 
1473 // Consults the specifier for an instruction and consumes all
1474 // operands for that instruction, interpreting them as it goes.
1475 static int readOperands(struct InternalInstruction *insn) {
1476   int hasVVVV, needVVVV;
1477   int sawRegImm = 0;
1478 
1479   LLVM_DEBUG(dbgs() << "readOperands()");
1480 
1481   // If non-zero vvvv specified, make sure one of the operands uses it.
1482   hasVVVV = !readVVVV(insn);
1483   needVVVV = hasVVVV && (insn->vvvv != 0);
1484 
1485   for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1486     switch (Op.encoding) {
1487     case ENCODING_NONE:
1488     case ENCODING_SI:
1489     case ENCODING_DI:
1490       break;
1491     CASE_ENCODING_VSIB:
1492       // VSIB can use the V2 bit so check only the other bits.
1493       if (needVVVV)
1494         needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1495       if (readModRM(insn))
1496         return -1;
1497 
1498       // Reject if SIB wasn't used.
1499       if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1500         return -1;
1501 
1502       // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1503       if (insn->sibIndex == SIB_INDEX_NONE)
1504         insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1505 
1506       // If EVEX.v2 is set this is one of the 16-31 registers.
1507       if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1508           v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1509         insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1510 
1511       // Adjust the index register to the correct size.
1512       switch ((OperandType)Op.type) {
1513       default:
1514         debug("Unhandled VSIB index type");
1515         return -1;
1516       case TYPE_MVSIBX:
1517         insn->sibIndex =
1518             (SIBIndex)(SIB_INDEX_XMM0 + (insn->sibIndex - insn->sibIndexBase));
1519         break;
1520       case TYPE_MVSIBY:
1521         insn->sibIndex =
1522             (SIBIndex)(SIB_INDEX_YMM0 + (insn->sibIndex - insn->sibIndexBase));
1523         break;
1524       case TYPE_MVSIBZ:
1525         insn->sibIndex =
1526             (SIBIndex)(SIB_INDEX_ZMM0 + (insn->sibIndex - insn->sibIndexBase));
1527         break;
1528       }
1529 
1530       // Apply the AVX512 compressed displacement scaling factor.
1531       if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1532         insn->displacement *= 1 << (Op.encoding - ENCODING_VSIB);
1533       break;
1534     case ENCODING_REG:
1535     CASE_ENCODING_RM:
1536       if (readModRM(insn))
1537         return -1;
1538       if (fixupReg(insn, &Op))
1539         return -1;
1540       // Apply the AVX512 compressed displacement scaling factor.
1541       if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1542         insn->displacement *= 1 << (Op.encoding - ENCODING_RM);
1543       break;
1544     case ENCODING_IB:
1545       if (sawRegImm) {
1546         // Saw a register immediate so don't read again and instead split the
1547         // previous immediate. FIXME: This is a hack.
1548         insn->immediates[insn->numImmediatesConsumed] =
1549             insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1550         ++insn->numImmediatesConsumed;
1551         break;
1552       }
1553       if (readImmediate(insn, 1))
1554         return -1;
1555       if (Op.type == TYPE_XMM || Op.type == TYPE_YMM)
1556         sawRegImm = 1;
1557       break;
1558     case ENCODING_IW:
1559       if (readImmediate(insn, 2))
1560         return -1;
1561       break;
1562     case ENCODING_ID:
1563       if (readImmediate(insn, 4))
1564         return -1;
1565       break;
1566     case ENCODING_IO:
1567       if (readImmediate(insn, 8))
1568         return -1;
1569       break;
1570     case ENCODING_Iv:
1571       if (readImmediate(insn, insn->immediateSize))
1572         return -1;
1573       break;
1574     case ENCODING_Ia:
1575       if (readImmediate(insn, insn->addressSize))
1576         return -1;
1577       break;
1578     case ENCODING_IRC:
1579       insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
1580                  lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
1581       break;
1582     case ENCODING_RB:
1583       if (readOpcodeRegister(insn, 1))
1584         return -1;
1585       break;
1586     case ENCODING_RW:
1587       if (readOpcodeRegister(insn, 2))
1588         return -1;
1589       break;
1590     case ENCODING_RD:
1591       if (readOpcodeRegister(insn, 4))
1592         return -1;
1593       break;
1594     case ENCODING_RO:
1595       if (readOpcodeRegister(insn, 8))
1596         return -1;
1597       break;
1598     case ENCODING_Rv:
1599       if (readOpcodeRegister(insn, 0))
1600         return -1;
1601       break;
1602     case ENCODING_CC:
1603       insn->immediates[1] = insn->opcode & 0xf;
1604       break;
1605     case ENCODING_FP:
1606       break;
1607     case ENCODING_VVVV:
1608       needVVVV = 0; // Mark that we have found a VVVV operand.
1609       if (!hasVVVV)
1610         return -1;
1611       if (insn->mode != MODE_64BIT)
1612         insn->vvvv = static_cast<Reg>(insn->vvvv & 0x7);
1613       if (fixupReg(insn, &Op))
1614         return -1;
1615       break;
1616     case ENCODING_WRITEMASK:
1617       if (readMaskRegister(insn))
1618         return -1;
1619       break;
1620     case ENCODING_DUP:
1621       break;
1622     default:
1623       LLVM_DEBUG(dbgs() << "Encountered an operand with an unknown encoding.");
1624       return -1;
1625     }
1626   }
1627 
1628   // If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail
1629   if (needVVVV)
1630     return -1;
1631 
1632   return 0;
1633 }
1634 
1635 namespace llvm {
1636 
1637 // Fill-ins to make the compiler happy. These constants are never actually
1638 // assigned; they are just filler to make an automatically-generated switch
1639 // statement work.
1640 namespace X86 {
1641   enum {
1642     BX_SI = 500,
1643     BX_DI = 501,
1644     BP_SI = 502,
1645     BP_DI = 503,
1646     sib   = 504,
1647     sib64 = 505
1648   };
1649 }
1650 
1651 }
1652 
1653 static bool translateInstruction(MCInst &target,
1654                                 InternalInstruction &source,
1655                                 const MCDisassembler *Dis);
1656 
1657 namespace {
1658 
1659 /// Generic disassembler for all X86 platforms. All each platform class should
1660 /// have to do is subclass the constructor, and provide a different
1661 /// disassemblerMode value.
1662 class X86GenericDisassembler : public MCDisassembler {
1663   std::unique_ptr<const MCInstrInfo> MII;
1664 public:
1665   X86GenericDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
1666                          std::unique_ptr<const MCInstrInfo> MII);
1667 public:
1668   DecodeStatus getInstruction(MCInst &instr, uint64_t &size,
1669                               ArrayRef<uint8_t> Bytes, uint64_t Address,
1670                               raw_ostream &cStream) const override;
1671 
1672 private:
1673   DisassemblerMode              fMode;
1674 };
1675 
1676 }
1677 
1678 X86GenericDisassembler::X86GenericDisassembler(
1679                                          const MCSubtargetInfo &STI,
1680                                          MCContext &Ctx,
1681                                          std::unique_ptr<const MCInstrInfo> MII)
1682   : MCDisassembler(STI, Ctx), MII(std::move(MII)) {
1683   const FeatureBitset &FB = STI.getFeatureBits();
1684   if (FB[X86::Mode16Bit]) {
1685     fMode = MODE_16BIT;
1686     return;
1687   } else if (FB[X86::Mode32Bit]) {
1688     fMode = MODE_32BIT;
1689     return;
1690   } else if (FB[X86::Mode64Bit]) {
1691     fMode = MODE_64BIT;
1692     return;
1693   }
1694 
1695   llvm_unreachable("Invalid CPU mode");
1696 }
1697 
1698 MCDisassembler::DecodeStatus X86GenericDisassembler::getInstruction(
1699     MCInst &Instr, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t Address,
1700     raw_ostream &CStream) const {
1701   CommentStream = &CStream;
1702 
1703   InternalInstruction Insn;
1704   memset(&Insn, 0, sizeof(InternalInstruction));
1705   Insn.bytes = Bytes;
1706   Insn.startLocation = Address;
1707   Insn.readerCursor = Address;
1708   Insn.mode = fMode;
1709 
1710   if (readPrefixes(&Insn) || readOpcode(&Insn) ||
1711       getInstructionID(&Insn, MII.get()) || Insn.instructionID == 0 ||
1712       readOperands(&Insn)) {
1713     Size = Insn.readerCursor - Address;
1714     return Fail;
1715   }
1716 
1717   Insn.operands = x86OperandSets[Insn.spec->operands];
1718   Insn.length = Insn.readerCursor - Insn.startLocation;
1719   Size = Insn.length;
1720   if (Size > 15)
1721     LLVM_DEBUG(dbgs() << "Instruction exceeds 15-byte limit");
1722 
1723   bool Ret = translateInstruction(Instr, Insn, this);
1724   if (!Ret) {
1725     unsigned Flags = X86::IP_NO_PREFIX;
1726     if (Insn.hasAdSize)
1727       Flags |= X86::IP_HAS_AD_SIZE;
1728     if (!Insn.mandatoryPrefix) {
1729       if (Insn.hasOpSize)
1730         Flags |= X86::IP_HAS_OP_SIZE;
1731       if (Insn.repeatPrefix == 0xf2)
1732         Flags |= X86::IP_HAS_REPEAT_NE;
1733       else if (Insn.repeatPrefix == 0xf3 &&
1734                // It should not be 'pause' f3 90
1735                Insn.opcode != 0x90)
1736         Flags |= X86::IP_HAS_REPEAT;
1737       if (Insn.hasLockPrefix)
1738         Flags |= X86::IP_HAS_LOCK;
1739     }
1740     Instr.setFlags(Flags);
1741   }
1742   return (!Ret) ? Success : Fail;
1743 }
1744 
1745 //
1746 // Private code that translates from struct InternalInstructions to MCInsts.
1747 //
1748 
1749 /// translateRegister - Translates an internal register to the appropriate LLVM
1750 ///   register, and appends it as an operand to an MCInst.
1751 ///
1752 /// @param mcInst     - The MCInst to append to.
1753 /// @param reg        - The Reg to append.
1754 static void translateRegister(MCInst &mcInst, Reg reg) {
1755 #define ENTRY(x) X86::x,
1756   static constexpr MCPhysReg llvmRegnums[] = {ALL_REGS};
1757 #undef ENTRY
1758 
1759   MCPhysReg llvmRegnum = llvmRegnums[reg];
1760   mcInst.addOperand(MCOperand::createReg(llvmRegnum));
1761 }
1762 
1763 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
1764 /// immediate Value in the MCInst.
1765 ///
1766 /// @param Value      - The immediate Value, has had any PC adjustment made by
1767 ///                     the caller.
1768 /// @param isBranch   - If the instruction is a branch instruction
1769 /// @param Address    - The starting address of the instruction
1770 /// @param Offset     - The byte offset to this immediate in the instruction
1771 /// @param Width      - The byte width of this immediate in the instruction
1772 ///
1773 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
1774 /// called then that function is called to get any symbolic information for the
1775 /// immediate in the instruction using the Address, Offset and Width.  If that
1776 /// returns non-zero then the symbolic information it returns is used to create
1777 /// an MCExpr and that is added as an operand to the MCInst.  If getOpInfo()
1778 /// returns zero and isBranch is true then a symbol look up for immediate Value
1779 /// is done and if a symbol is found an MCExpr is created with that, else
1780 /// an MCExpr with the immediate Value is created.  This function returns true
1781 /// if it adds an operand to the MCInst and false otherwise.
1782 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
1783                                      uint64_t Address, uint64_t Offset,
1784                                      uint64_t Width, MCInst &MI,
1785                                      const MCDisassembler *Dis) {
1786   return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
1787                                        Offset, Width);
1788 }
1789 
1790 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
1791 /// referenced by a load instruction with the base register that is the rip.
1792 /// These can often be addresses in a literal pool.  The Address of the
1793 /// instruction and its immediate Value are used to determine the address
1794 /// being referenced in the literal pool entry.  The SymbolLookUp call back will
1795 /// return a pointer to a literal 'C' string if the referenced address is an
1796 /// address into a section with 'C' string literals.
1797 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
1798                                             const void *Decoder) {
1799   const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
1800   Dis->tryAddingPcLoadReferenceComment(Value, Address);
1801 }
1802 
1803 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
1804   0,        // SEG_OVERRIDE_NONE
1805   X86::CS,
1806   X86::SS,
1807   X86::DS,
1808   X86::ES,
1809   X86::FS,
1810   X86::GS
1811 };
1812 
1813 /// translateSrcIndex   - Appends a source index operand to an MCInst.
1814 ///
1815 /// @param mcInst       - The MCInst to append to.
1816 /// @param insn         - The internal instruction.
1817 static bool translateSrcIndex(MCInst &mcInst, InternalInstruction &insn) {
1818   unsigned baseRegNo;
1819 
1820   if (insn.mode == MODE_64BIT)
1821     baseRegNo = insn.hasAdSize ? X86::ESI : X86::RSI;
1822   else if (insn.mode == MODE_32BIT)
1823     baseRegNo = insn.hasAdSize ? X86::SI : X86::ESI;
1824   else {
1825     assert(insn.mode == MODE_16BIT);
1826     baseRegNo = insn.hasAdSize ? X86::ESI : X86::SI;
1827   }
1828   MCOperand baseReg = MCOperand::createReg(baseRegNo);
1829   mcInst.addOperand(baseReg);
1830 
1831   MCOperand segmentReg;
1832   segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
1833   mcInst.addOperand(segmentReg);
1834   return false;
1835 }
1836 
1837 /// translateDstIndex   - Appends a destination index operand to an MCInst.
1838 ///
1839 /// @param mcInst       - The MCInst to append to.
1840 /// @param insn         - The internal instruction.
1841 
1842 static bool translateDstIndex(MCInst &mcInst, InternalInstruction &insn) {
1843   unsigned baseRegNo;
1844 
1845   if (insn.mode == MODE_64BIT)
1846     baseRegNo = insn.hasAdSize ? X86::EDI : X86::RDI;
1847   else if (insn.mode == MODE_32BIT)
1848     baseRegNo = insn.hasAdSize ? X86::DI : X86::EDI;
1849   else {
1850     assert(insn.mode == MODE_16BIT);
1851     baseRegNo = insn.hasAdSize ? X86::EDI : X86::DI;
1852   }
1853   MCOperand baseReg = MCOperand::createReg(baseRegNo);
1854   mcInst.addOperand(baseReg);
1855   return false;
1856 }
1857 
1858 /// translateImmediate  - Appends an immediate operand to an MCInst.
1859 ///
1860 /// @param mcInst       - The MCInst to append to.
1861 /// @param immediate    - The immediate value to append.
1862 /// @param operand      - The operand, as stored in the descriptor table.
1863 /// @param insn         - The internal instruction.
1864 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
1865                                const OperandSpecifier &operand,
1866                                InternalInstruction &insn,
1867                                const MCDisassembler *Dis) {
1868   // Sign-extend the immediate if necessary.
1869 
1870   OperandType type = (OperandType)operand.type;
1871 
1872   bool isBranch = false;
1873   uint64_t pcrel = 0;
1874   if (type == TYPE_REL) {
1875     isBranch = true;
1876     pcrel = insn.startLocation +
1877             insn.immediateOffset + insn.immediateSize;
1878     switch (operand.encoding) {
1879     default:
1880       break;
1881     case ENCODING_Iv:
1882       switch (insn.displacementSize) {
1883       default:
1884         break;
1885       case 1:
1886         if(immediate & 0x80)
1887           immediate |= ~(0xffull);
1888         break;
1889       case 2:
1890         if(immediate & 0x8000)
1891           immediate |= ~(0xffffull);
1892         break;
1893       case 4:
1894         if(immediate & 0x80000000)
1895           immediate |= ~(0xffffffffull);
1896         break;
1897       case 8:
1898         break;
1899       }
1900       break;
1901     case ENCODING_IB:
1902       if(immediate & 0x80)
1903         immediate |= ~(0xffull);
1904       break;
1905     case ENCODING_IW:
1906       if(immediate & 0x8000)
1907         immediate |= ~(0xffffull);
1908       break;
1909     case ENCODING_ID:
1910       if(immediate & 0x80000000)
1911         immediate |= ~(0xffffffffull);
1912       break;
1913     }
1914   }
1915   // By default sign-extend all X86 immediates based on their encoding.
1916   else if (type == TYPE_IMM) {
1917     switch (operand.encoding) {
1918     default:
1919       break;
1920     case ENCODING_IB:
1921       if(immediate & 0x80)
1922         immediate |= ~(0xffull);
1923       break;
1924     case ENCODING_IW:
1925       if(immediate & 0x8000)
1926         immediate |= ~(0xffffull);
1927       break;
1928     case ENCODING_ID:
1929       if(immediate & 0x80000000)
1930         immediate |= ~(0xffffffffull);
1931       break;
1932     case ENCODING_IO:
1933       break;
1934     }
1935   }
1936 
1937   switch (type) {
1938   case TYPE_XMM:
1939     mcInst.addOperand(MCOperand::createReg(X86::XMM0 + (immediate >> 4)));
1940     return;
1941   case TYPE_YMM:
1942     mcInst.addOperand(MCOperand::createReg(X86::YMM0 + (immediate >> 4)));
1943     return;
1944   case TYPE_ZMM:
1945     mcInst.addOperand(MCOperand::createReg(X86::ZMM0 + (immediate >> 4)));
1946     return;
1947   default:
1948     // operand is 64 bits wide.  Do nothing.
1949     break;
1950   }
1951 
1952   if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
1953                                insn.immediateOffset, insn.immediateSize,
1954                                mcInst, Dis))
1955     mcInst.addOperand(MCOperand::createImm(immediate));
1956 
1957   if (type == TYPE_MOFFS) {
1958     MCOperand segmentReg;
1959     segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
1960     mcInst.addOperand(segmentReg);
1961   }
1962 }
1963 
1964 /// translateRMRegister - Translates a register stored in the R/M field of the
1965 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
1966 /// @param mcInst       - The MCInst to append to.
1967 /// @param insn         - The internal instruction to extract the R/M field
1968 ///                       from.
1969 /// @return             - 0 on success; -1 otherwise
1970 static bool translateRMRegister(MCInst &mcInst,
1971                                 InternalInstruction &insn) {
1972   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
1973     debug("A R/M register operand may not have a SIB byte");
1974     return true;
1975   }
1976 
1977   switch (insn.eaBase) {
1978   default:
1979     debug("Unexpected EA base register");
1980     return true;
1981   case EA_BASE_NONE:
1982     debug("EA_BASE_NONE for ModR/M base");
1983     return true;
1984 #define ENTRY(x) case EA_BASE_##x:
1985   ALL_EA_BASES
1986 #undef ENTRY
1987     debug("A R/M register operand may not have a base; "
1988           "the operand must be a register.");
1989     return true;
1990 #define ENTRY(x)                                                      \
1991   case EA_REG_##x:                                                    \
1992     mcInst.addOperand(MCOperand::createReg(X86::x)); break;
1993   ALL_REGS
1994 #undef ENTRY
1995   }
1996 
1997   return false;
1998 }
1999 
2000 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
2001 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
2002 ///   operand in LLVM's format, and appends it to an MCInst.
2003 ///
2004 /// @param mcInst       - The MCInst to append to.
2005 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
2006 ///                       from.
2007 /// @return             - 0 on success; nonzero otherwise
2008 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
2009                               const MCDisassembler *Dis) {
2010   // Addresses in an MCInst are represented as five operands:
2011   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the
2012   //                                SIB base
2013   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified
2014   //                                scale amount
2015   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
2016   //                                the index (which is multiplied by the
2017   //                                scale amount)
2018   //   4. displacement  (immediate) 0, or the displacement if there is one
2019   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
2020   //                                if we have segment overrides
2021 
2022   MCOperand baseReg;
2023   MCOperand scaleAmount;
2024   MCOperand indexReg;
2025   MCOperand displacement;
2026   MCOperand segmentReg;
2027   uint64_t pcrel = 0;
2028 
2029   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
2030     if (insn.sibBase != SIB_BASE_NONE) {
2031       switch (insn.sibBase) {
2032       default:
2033         debug("Unexpected sibBase");
2034         return true;
2035 #define ENTRY(x)                                          \
2036       case SIB_BASE_##x:                                  \
2037         baseReg = MCOperand::createReg(X86::x); break;
2038       ALL_SIB_BASES
2039 #undef ENTRY
2040       }
2041     } else {
2042       baseReg = MCOperand::createReg(X86::NoRegister);
2043     }
2044 
2045     if (insn.sibIndex != SIB_INDEX_NONE) {
2046       switch (insn.sibIndex) {
2047       default:
2048         debug("Unexpected sibIndex");
2049         return true;
2050 #define ENTRY(x)                                          \
2051       case SIB_INDEX_##x:                                 \
2052         indexReg = MCOperand::createReg(X86::x); break;
2053       EA_BASES_32BIT
2054       EA_BASES_64BIT
2055       REGS_XMM
2056       REGS_YMM
2057       REGS_ZMM
2058 #undef ENTRY
2059       }
2060     } else {
2061       // Use EIZ/RIZ for a few ambiguous cases where the SIB byte is present,
2062       // but no index is used and modrm alone should have been enough.
2063       // -No base register in 32-bit mode. In 64-bit mode this is used to
2064       //  avoid rip-relative addressing.
2065       // -Any base register used other than ESP/RSP/R12D/R12. Using these as a
2066       //  base always requires a SIB byte.
2067       // -A scale other than 1 is used.
2068       if (insn.sibScale != 1 ||
2069           (insn.sibBase == SIB_BASE_NONE && insn.mode != MODE_64BIT) ||
2070           (insn.sibBase != SIB_BASE_NONE &&
2071            insn.sibBase != SIB_BASE_ESP && insn.sibBase != SIB_BASE_RSP &&
2072            insn.sibBase != SIB_BASE_R12D && insn.sibBase != SIB_BASE_R12)) {
2073         indexReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIZ :
2074                                                                 X86::RIZ);
2075       } else
2076         indexReg = MCOperand::createReg(X86::NoRegister);
2077     }
2078 
2079     scaleAmount = MCOperand::createImm(insn.sibScale);
2080   } else {
2081     switch (insn.eaBase) {
2082     case EA_BASE_NONE:
2083       if (insn.eaDisplacement == EA_DISP_NONE) {
2084         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
2085         return true;
2086       }
2087       if (insn.mode == MODE_64BIT){
2088         pcrel = insn.startLocation +
2089                 insn.displacementOffset + insn.displacementSize;
2090         tryAddingPcLoadReferenceComment(insn.startLocation +
2091                                         insn.displacementOffset,
2092                                         insn.displacement + pcrel, Dis);
2093         // Section 2.2.1.6
2094         baseReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIP :
2095                                                                X86::RIP);
2096       }
2097       else
2098         baseReg = MCOperand::createReg(X86::NoRegister);
2099 
2100       indexReg = MCOperand::createReg(X86::NoRegister);
2101       break;
2102     case EA_BASE_BX_SI:
2103       baseReg = MCOperand::createReg(X86::BX);
2104       indexReg = MCOperand::createReg(X86::SI);
2105       break;
2106     case EA_BASE_BX_DI:
2107       baseReg = MCOperand::createReg(X86::BX);
2108       indexReg = MCOperand::createReg(X86::DI);
2109       break;
2110     case EA_BASE_BP_SI:
2111       baseReg = MCOperand::createReg(X86::BP);
2112       indexReg = MCOperand::createReg(X86::SI);
2113       break;
2114     case EA_BASE_BP_DI:
2115       baseReg = MCOperand::createReg(X86::BP);
2116       indexReg = MCOperand::createReg(X86::DI);
2117       break;
2118     default:
2119       indexReg = MCOperand::createReg(X86::NoRegister);
2120       switch (insn.eaBase) {
2121       default:
2122         debug("Unexpected eaBase");
2123         return true;
2124         // Here, we will use the fill-ins defined above.  However,
2125         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
2126         //   sib and sib64 were handled in the top-level if, so they're only
2127         //   placeholders to keep the compiler happy.
2128 #define ENTRY(x)                                        \
2129       case EA_BASE_##x:                                 \
2130         baseReg = MCOperand::createReg(X86::x); break;
2131       ALL_EA_BASES
2132 #undef ENTRY
2133 #define ENTRY(x) case EA_REG_##x:
2134       ALL_REGS
2135 #undef ENTRY
2136         debug("A R/M memory operand may not be a register; "
2137               "the base field must be a base.");
2138         return true;
2139       }
2140     }
2141 
2142     scaleAmount = MCOperand::createImm(1);
2143   }
2144 
2145   displacement = MCOperand::createImm(insn.displacement);
2146 
2147   segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
2148 
2149   mcInst.addOperand(baseReg);
2150   mcInst.addOperand(scaleAmount);
2151   mcInst.addOperand(indexReg);
2152   if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
2153                                insn.startLocation, insn.displacementOffset,
2154                                insn.displacementSize, mcInst, Dis))
2155     mcInst.addOperand(displacement);
2156   mcInst.addOperand(segmentReg);
2157   return false;
2158 }
2159 
2160 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
2161 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
2162 ///
2163 /// @param mcInst       - The MCInst to append to.
2164 /// @param operand      - The operand, as stored in the descriptor table.
2165 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
2166 ///                       from.
2167 /// @return             - 0 on success; nonzero otherwise
2168 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
2169                         InternalInstruction &insn, const MCDisassembler *Dis) {
2170   switch (operand.type) {
2171   default:
2172     debug("Unexpected type for a R/M operand");
2173     return true;
2174   case TYPE_R8:
2175   case TYPE_R16:
2176   case TYPE_R32:
2177   case TYPE_R64:
2178   case TYPE_Rv:
2179   case TYPE_MM64:
2180   case TYPE_XMM:
2181   case TYPE_YMM:
2182   case TYPE_ZMM:
2183   case TYPE_VK_PAIR:
2184   case TYPE_VK:
2185   case TYPE_DEBUGREG:
2186   case TYPE_CONTROLREG:
2187   case TYPE_BNDR:
2188     return translateRMRegister(mcInst, insn);
2189   case TYPE_M:
2190   case TYPE_MVSIBX:
2191   case TYPE_MVSIBY:
2192   case TYPE_MVSIBZ:
2193     return translateRMMemory(mcInst, insn, Dis);
2194   }
2195 }
2196 
2197 /// translateFPRegister - Translates a stack position on the FPU stack to its
2198 ///   LLVM form, and appends it to an MCInst.
2199 ///
2200 /// @param mcInst       - The MCInst to append to.
2201 /// @param stackPos     - The stack position to translate.
2202 static void translateFPRegister(MCInst &mcInst,
2203                                 uint8_t stackPos) {
2204   mcInst.addOperand(MCOperand::createReg(X86::ST0 + stackPos));
2205 }
2206 
2207 /// translateMaskRegister - Translates a 3-bit mask register number to
2208 ///   LLVM form, and appends it to an MCInst.
2209 ///
2210 /// @param mcInst       - The MCInst to append to.
2211 /// @param maskRegNum   - Number of mask register from 0 to 7.
2212 /// @return             - false on success; true otherwise.
2213 static bool translateMaskRegister(MCInst &mcInst,
2214                                 uint8_t maskRegNum) {
2215   if (maskRegNum >= 8) {
2216     debug("Invalid mask register number");
2217     return true;
2218   }
2219 
2220   mcInst.addOperand(MCOperand::createReg(X86::K0 + maskRegNum));
2221   return false;
2222 }
2223 
2224 /// translateOperand - Translates an operand stored in an internal instruction
2225 ///   to LLVM's format and appends it to an MCInst.
2226 ///
2227 /// @param mcInst       - The MCInst to append to.
2228 /// @param operand      - The operand, as stored in the descriptor table.
2229 /// @param insn         - The internal instruction.
2230 /// @return             - false on success; true otherwise.
2231 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
2232                              InternalInstruction &insn,
2233                              const MCDisassembler *Dis) {
2234   switch (operand.encoding) {
2235   default:
2236     debug("Unhandled operand encoding during translation");
2237     return true;
2238   case ENCODING_REG:
2239     translateRegister(mcInst, insn.reg);
2240     return false;
2241   case ENCODING_WRITEMASK:
2242     return translateMaskRegister(mcInst, insn.writemask);
2243   CASE_ENCODING_RM:
2244   CASE_ENCODING_VSIB:
2245     return translateRM(mcInst, operand, insn, Dis);
2246   case ENCODING_IB:
2247   case ENCODING_IW:
2248   case ENCODING_ID:
2249   case ENCODING_IO:
2250   case ENCODING_Iv:
2251   case ENCODING_Ia:
2252     translateImmediate(mcInst,
2253                        insn.immediates[insn.numImmediatesTranslated++],
2254                        operand,
2255                        insn,
2256                        Dis);
2257     return false;
2258   case ENCODING_IRC:
2259     mcInst.addOperand(MCOperand::createImm(insn.RC));
2260     return false;
2261   case ENCODING_SI:
2262     return translateSrcIndex(mcInst, insn);
2263   case ENCODING_DI:
2264     return translateDstIndex(mcInst, insn);
2265   case ENCODING_RB:
2266   case ENCODING_RW:
2267   case ENCODING_RD:
2268   case ENCODING_RO:
2269   case ENCODING_Rv:
2270     translateRegister(mcInst, insn.opcodeRegister);
2271     return false;
2272   case ENCODING_CC:
2273     mcInst.addOperand(MCOperand::createImm(insn.immediates[1]));
2274     return false;
2275   case ENCODING_FP:
2276     translateFPRegister(mcInst, insn.modRM & 7);
2277     return false;
2278   case ENCODING_VVVV:
2279     translateRegister(mcInst, insn.vvvv);
2280     return false;
2281   case ENCODING_DUP:
2282     return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
2283                             insn, Dis);
2284   }
2285 }
2286 
2287 /// translateInstruction - Translates an internal instruction and all its
2288 ///   operands to an MCInst.
2289 ///
2290 /// @param mcInst       - The MCInst to populate with the instruction's data.
2291 /// @param insn         - The internal instruction.
2292 /// @return             - false on success; true otherwise.
2293 static bool translateInstruction(MCInst &mcInst,
2294                                 InternalInstruction &insn,
2295                                 const MCDisassembler *Dis) {
2296   if (!insn.spec) {
2297     debug("Instruction has no specification");
2298     return true;
2299   }
2300 
2301   mcInst.clear();
2302   mcInst.setOpcode(insn.instructionID);
2303   // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
2304   // prefix bytes should be disassembled as xrelease and xacquire then set the
2305   // opcode to those instead of the rep and repne opcodes.
2306   if (insn.xAcquireRelease) {
2307     if(mcInst.getOpcode() == X86::REP_PREFIX)
2308       mcInst.setOpcode(X86::XRELEASE_PREFIX);
2309     else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
2310       mcInst.setOpcode(X86::XACQUIRE_PREFIX);
2311   }
2312 
2313   insn.numImmediatesTranslated = 0;
2314 
2315   for (const auto &Op : insn.operands) {
2316     if (Op.encoding != ENCODING_NONE) {
2317       if (translateOperand(mcInst, Op, insn, Dis)) {
2318         return true;
2319       }
2320     }
2321   }
2322 
2323   return false;
2324 }
2325 
2326 static MCDisassembler *createX86Disassembler(const Target &T,
2327                                              const MCSubtargetInfo &STI,
2328                                              MCContext &Ctx) {
2329   std::unique_ptr<const MCInstrInfo> MII(T.createMCInstrInfo());
2330   return new X86GenericDisassembler(STI, Ctx, std::move(MII));
2331 }
2332 
2333 extern "C" void LLVMInitializeX86Disassembler() {
2334   // Register the disassembler.
2335   TargetRegistry::RegisterMCDisassembler(getTheX86_32Target(),
2336                                          createX86Disassembler);
2337   TargetRegistry::RegisterMCDisassembler(getTheX86_64Target(),
2338                                          createX86Disassembler);
2339 }
2340