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