xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp (revision 6be3386466ab79a84b48429ae66244f21526d3df)
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_TMM:                                                             \
780       if (index > 7)                                                           \
781         *valid = 0;                                                            \
782       return prefix##_TMM0 + index;                                            \
783     case TYPE_VK:                                                              \
784       index &= 0xf;                                                            \
785       if (index > 7)                                                           \
786         *valid = 0;                                                            \
787       return prefix##_K0 + index;                                              \
788     case TYPE_VK_PAIR:                                                         \
789       if (index > 7)                                                           \
790         *valid = 0;                                                            \
791       return prefix##_K0_K1 + (index / 2);                                     \
792     case TYPE_MM64:                                                            \
793       return prefix##_MM0 + (index & 0x7);                                     \
794     case TYPE_SEGMENTREG:                                                      \
795       if ((index & 7) > 5)                                                     \
796         *valid = 0;                                                            \
797       return prefix##_ES + (index & 7);                                        \
798     case TYPE_DEBUGREG:                                                        \
799       return prefix##_DR0 + index;                                             \
800     case TYPE_CONTROLREG:                                                      \
801       return prefix##_CR0 + index;                                             \
802     case TYPE_BNDR:                                                            \
803       if (index > 3)                                                           \
804         *valid = 0;                                                            \
805       return prefix##_BND0 + index;                                            \
806     case TYPE_MVSIBX:                                                          \
807       return prefix##_XMM0 + index;                                            \
808     case TYPE_MVSIBY:                                                          \
809       return prefix##_YMM0 + index;                                            \
810     case TYPE_MVSIBZ:                                                          \
811       return prefix##_ZMM0 + index;                                            \
812     }                                                                          \
813   }
814 
815 // Consult an operand type to determine the meaning of the reg or R/M field. If
816 // the operand is an XMM operand, for example, an operand would be XMM0 instead
817 // of AX, which readModRM() would otherwise misinterpret it as.
818 //
819 // @param insn  - The instruction containing the operand.
820 // @param type  - The operand type.
821 // @param index - The existing value of the field as reported by readModRM().
822 // @param valid - The address of a uint8_t.  The target is set to 1 if the
823 //                field is valid for the register class; 0 if not.
824 // @return      - The proper value.
825 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG, 0x1f)
826 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG, 0xf)
827 
828 // Consult an operand specifier to determine which of the fixup*Value functions
829 // to use in correcting readModRM()'ss interpretation.
830 //
831 // @param insn  - See fixup*Value().
832 // @param op    - The operand specifier.
833 // @return      - 0 if fixup was successful; -1 if the register returned was
834 //                invalid for its class.
835 static int fixupReg(struct InternalInstruction *insn,
836                     const struct OperandSpecifier *op) {
837   uint8_t valid;
838   LLVM_DEBUG(dbgs() << "fixupReg()");
839 
840   switch ((OperandEncoding)op->encoding) {
841   default:
842     debug("Expected a REG or R/M encoding in fixupReg");
843     return -1;
844   case ENCODING_VVVV:
845     insn->vvvv =
846         (Reg)fixupRegValue(insn, (OperandType)op->type, insn->vvvv, &valid);
847     if (!valid)
848       return -1;
849     break;
850   case ENCODING_REG:
851     insn->reg = (Reg)fixupRegValue(insn, (OperandType)op->type,
852                                    insn->reg - insn->regBase, &valid);
853     if (!valid)
854       return -1;
855     break;
856   case ENCODING_SIB:
857   CASE_ENCODING_RM:
858     if (insn->eaBase >= insn->eaRegBase) {
859       insn->eaBase = (EABase)fixupRMValue(
860           insn, (OperandType)op->type, insn->eaBase - insn->eaRegBase, &valid);
861       if (!valid)
862         return -1;
863     }
864     break;
865   }
866 
867   return 0;
868 }
869 
870 // Read the opcode (except the ModR/M byte in the case of extended or escape
871 // opcodes).
872 static bool readOpcode(struct InternalInstruction *insn) {
873   uint8_t current;
874   LLVM_DEBUG(dbgs() << "readOpcode()");
875 
876   insn->opcodeType = ONEBYTE;
877   if (insn->vectorExtensionType == TYPE_EVEX) {
878     switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
879     default:
880       LLVM_DEBUG(
881           dbgs() << format("Unhandled mm field for instruction (0x%hhx)",
882                            mmFromEVEX2of4(insn->vectorExtensionPrefix[1])));
883       return true;
884     case VEX_LOB_0F:
885       insn->opcodeType = TWOBYTE;
886       return consume(insn, insn->opcode);
887     case VEX_LOB_0F38:
888       insn->opcodeType = THREEBYTE_38;
889       return consume(insn, insn->opcode);
890     case VEX_LOB_0F3A:
891       insn->opcodeType = THREEBYTE_3A;
892       return consume(insn, insn->opcode);
893     }
894   } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
895     switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
896     default:
897       LLVM_DEBUG(
898           dbgs() << format("Unhandled m-mmmm field for instruction (0x%hhx)",
899                            mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])));
900       return true;
901     case VEX_LOB_0F:
902       insn->opcodeType = TWOBYTE;
903       return consume(insn, insn->opcode);
904     case VEX_LOB_0F38:
905       insn->opcodeType = THREEBYTE_38;
906       return consume(insn, insn->opcode);
907     case VEX_LOB_0F3A:
908       insn->opcodeType = THREEBYTE_3A;
909       return consume(insn, insn->opcode);
910     }
911   } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
912     insn->opcodeType = TWOBYTE;
913     return consume(insn, insn->opcode);
914   } else if (insn->vectorExtensionType == TYPE_XOP) {
915     switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
916     default:
917       LLVM_DEBUG(
918           dbgs() << format("Unhandled m-mmmm field for instruction (0x%hhx)",
919                            mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])));
920       return true;
921     case XOP_MAP_SELECT_8:
922       insn->opcodeType = XOP8_MAP;
923       return consume(insn, insn->opcode);
924     case XOP_MAP_SELECT_9:
925       insn->opcodeType = XOP9_MAP;
926       return consume(insn, insn->opcode);
927     case XOP_MAP_SELECT_A:
928       insn->opcodeType = XOPA_MAP;
929       return consume(insn, insn->opcode);
930     }
931   }
932 
933   if (consume(insn, current))
934     return true;
935 
936   if (current == 0x0f) {
937     LLVM_DEBUG(
938         dbgs() << format("Found a two-byte escape prefix (0x%hhx)", current));
939     if (consume(insn, current))
940       return true;
941 
942     if (current == 0x38) {
943       LLVM_DEBUG(dbgs() << format("Found a three-byte escape prefix (0x%hhx)",
944                                   current));
945       if (consume(insn, current))
946         return true;
947 
948       insn->opcodeType = THREEBYTE_38;
949     } else if (current == 0x3a) {
950       LLVM_DEBUG(dbgs() << format("Found a three-byte escape prefix (0x%hhx)",
951                                   current));
952       if (consume(insn, current))
953         return true;
954 
955       insn->opcodeType = THREEBYTE_3A;
956     } else if (current == 0x0f) {
957       LLVM_DEBUG(
958           dbgs() << format("Found a 3dnow escape prefix (0x%hhx)", current));
959 
960       // Consume operands before the opcode to comply with the 3DNow encoding
961       if (readModRM(insn))
962         return true;
963 
964       if (consume(insn, current))
965         return true;
966 
967       insn->opcodeType = THREEDNOW_MAP;
968     } else {
969       LLVM_DEBUG(dbgs() << "Didn't find a three-byte escape prefix");
970       insn->opcodeType = TWOBYTE;
971     }
972   } else if (insn->mandatoryPrefix)
973     // The opcode with mandatory prefix must start with opcode escape.
974     // If not it's legacy repeat prefix
975     insn->mandatoryPrefix = 0;
976 
977   // At this point we have consumed the full opcode.
978   // Anything we consume from here on must be unconsumed.
979   insn->opcode = current;
980 
981   return false;
982 }
983 
984 // Determine whether equiv is the 16-bit equivalent of orig (32-bit or 64-bit).
985 static bool is16BitEquivalent(const char *orig, const char *equiv) {
986   for (int i = 0;; i++) {
987     if (orig[i] == '\0' && equiv[i] == '\0')
988       return true;
989     if (orig[i] == '\0' || equiv[i] == '\0')
990       return false;
991     if (orig[i] != equiv[i]) {
992       if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
993         continue;
994       if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
995         continue;
996       if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
997         continue;
998       return false;
999     }
1000   }
1001 }
1002 
1003 // Determine whether this instruction is a 64-bit instruction.
1004 static bool is64Bit(const char *name) {
1005   for (int i = 0;; ++i) {
1006     if (name[i] == '\0')
1007       return false;
1008     if (name[i] == '6' && name[i + 1] == '4')
1009       return true;
1010   }
1011 }
1012 
1013 // Determine the ID of an instruction, consuming the ModR/M byte as appropriate
1014 // for extended and escape opcodes, and using a supplied attribute mask.
1015 static int getInstructionIDWithAttrMask(uint16_t *instructionID,
1016                                         struct InternalInstruction *insn,
1017                                         uint16_t attrMask) {
1018   auto insnCtx = InstructionContext(x86DisassemblerContexts[attrMask]);
1019   const ContextDecision *decision;
1020   switch (insn->opcodeType) {
1021   case ONEBYTE:
1022     decision = &ONEBYTE_SYM;
1023     break;
1024   case TWOBYTE:
1025     decision = &TWOBYTE_SYM;
1026     break;
1027   case THREEBYTE_38:
1028     decision = &THREEBYTE38_SYM;
1029     break;
1030   case THREEBYTE_3A:
1031     decision = &THREEBYTE3A_SYM;
1032     break;
1033   case XOP8_MAP:
1034     decision = &XOP8_MAP_SYM;
1035     break;
1036   case XOP9_MAP:
1037     decision = &XOP9_MAP_SYM;
1038     break;
1039   case XOPA_MAP:
1040     decision = &XOPA_MAP_SYM;
1041     break;
1042   case THREEDNOW_MAP:
1043     decision = &THREEDNOW_MAP_SYM;
1044     break;
1045   }
1046 
1047   if (decision->opcodeDecisions[insnCtx]
1048           .modRMDecisions[insn->opcode]
1049           .modrm_type != MODRM_ONEENTRY) {
1050     if (readModRM(insn))
1051       return -1;
1052     *instructionID =
1053         decode(insn->opcodeType, insnCtx, insn->opcode, insn->modRM);
1054   } else {
1055     *instructionID = decode(insn->opcodeType, insnCtx, insn->opcode, 0);
1056   }
1057 
1058   return 0;
1059 }
1060 
1061 // Determine the ID of an instruction, consuming the ModR/M byte as appropriate
1062 // for extended and escape opcodes. Determines the attributes and context for
1063 // the instruction before doing so.
1064 static int getInstructionID(struct InternalInstruction *insn,
1065                             const MCInstrInfo *mii) {
1066   uint16_t attrMask;
1067   uint16_t instructionID;
1068 
1069   LLVM_DEBUG(dbgs() << "getID()");
1070 
1071   attrMask = ATTR_NONE;
1072 
1073   if (insn->mode == MODE_64BIT)
1074     attrMask |= ATTR_64BIT;
1075 
1076   if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1077     attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
1078 
1079     if (insn->vectorExtensionType == TYPE_EVEX) {
1080       switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
1081       case VEX_PREFIX_66:
1082         attrMask |= ATTR_OPSIZE;
1083         break;
1084       case VEX_PREFIX_F3:
1085         attrMask |= ATTR_XS;
1086         break;
1087       case VEX_PREFIX_F2:
1088         attrMask |= ATTR_XD;
1089         break;
1090       }
1091 
1092       if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1093         attrMask |= ATTR_EVEXKZ;
1094       if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1095         attrMask |= ATTR_EVEXB;
1096       if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1097         attrMask |= ATTR_EVEXK;
1098       if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1099         attrMask |= ATTR_VEXL;
1100       if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1101         attrMask |= ATTR_EVEXL2;
1102     } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
1103       switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
1104       case VEX_PREFIX_66:
1105         attrMask |= ATTR_OPSIZE;
1106         break;
1107       case VEX_PREFIX_F3:
1108         attrMask |= ATTR_XS;
1109         break;
1110       case VEX_PREFIX_F2:
1111         attrMask |= ATTR_XD;
1112         break;
1113       }
1114 
1115       if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
1116         attrMask |= ATTR_VEXL;
1117     } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
1118       switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
1119       case VEX_PREFIX_66:
1120         attrMask |= ATTR_OPSIZE;
1121         break;
1122       case VEX_PREFIX_F3:
1123         attrMask |= ATTR_XS;
1124         break;
1125       case VEX_PREFIX_F2:
1126         attrMask |= ATTR_XD;
1127         break;
1128       }
1129 
1130       if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
1131         attrMask |= ATTR_VEXL;
1132     } else if (insn->vectorExtensionType == TYPE_XOP) {
1133       switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
1134       case VEX_PREFIX_66:
1135         attrMask |= ATTR_OPSIZE;
1136         break;
1137       case VEX_PREFIX_F3:
1138         attrMask |= ATTR_XS;
1139         break;
1140       case VEX_PREFIX_F2:
1141         attrMask |= ATTR_XD;
1142         break;
1143       }
1144 
1145       if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
1146         attrMask |= ATTR_VEXL;
1147     } else {
1148       return -1;
1149     }
1150   } else if (!insn->mandatoryPrefix) {
1151     // If we don't have mandatory prefix we should use legacy prefixes here
1152     if (insn->hasOpSize && (insn->mode != MODE_16BIT))
1153       attrMask |= ATTR_OPSIZE;
1154     if (insn->hasAdSize)
1155       attrMask |= ATTR_ADSIZE;
1156     if (insn->opcodeType == ONEBYTE) {
1157       if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
1158         // Special support for PAUSE
1159         attrMask |= ATTR_XS;
1160     } else {
1161       if (insn->repeatPrefix == 0xf2)
1162         attrMask |= ATTR_XD;
1163       else if (insn->repeatPrefix == 0xf3)
1164         attrMask |= ATTR_XS;
1165     }
1166   } else {
1167     switch (insn->mandatoryPrefix) {
1168     case 0xf2:
1169       attrMask |= ATTR_XD;
1170       break;
1171     case 0xf3:
1172       attrMask |= ATTR_XS;
1173       break;
1174     case 0x66:
1175       if (insn->mode != MODE_16BIT)
1176         attrMask |= ATTR_OPSIZE;
1177       break;
1178     case 0x67:
1179       attrMask |= ATTR_ADSIZE;
1180       break;
1181     }
1182   }
1183 
1184   if (insn->rexPrefix & 0x08) {
1185     attrMask |= ATTR_REXW;
1186     attrMask &= ~ATTR_ADSIZE;
1187   }
1188 
1189   if (insn->mode == MODE_16BIT) {
1190     // JCXZ/JECXZ need special handling for 16-bit mode because the meaning
1191     // of the AdSize prefix is inverted w.r.t. 32-bit mode.
1192     if (insn->opcodeType == ONEBYTE && insn->opcode == 0xE3)
1193       attrMask ^= ATTR_ADSIZE;
1194     // If we're in 16-bit mode and this is one of the relative jumps and opsize
1195     // prefix isn't present, we need to force the opsize attribute since the
1196     // prefix is inverted relative to 32-bit mode.
1197     if (!insn->hasOpSize && insn->opcodeType == ONEBYTE &&
1198         (insn->opcode == 0xE8 || insn->opcode == 0xE9))
1199       attrMask |= ATTR_OPSIZE;
1200 
1201     if (!insn->hasOpSize && insn->opcodeType == TWOBYTE &&
1202         insn->opcode >= 0x80 && insn->opcode <= 0x8F)
1203       attrMask |= ATTR_OPSIZE;
1204   }
1205 
1206 
1207   if (getInstructionIDWithAttrMask(&instructionID, insn, attrMask))
1208     return -1;
1209 
1210   // The following clauses compensate for limitations of the tables.
1211 
1212   if (insn->mode != MODE_64BIT &&
1213       insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1214     // The tables can't distinquish between cases where the W-bit is used to
1215     // select register size and cases where its a required part of the opcode.
1216     if ((insn->vectorExtensionType == TYPE_EVEX &&
1217          wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1218         (insn->vectorExtensionType == TYPE_VEX_3B &&
1219          wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1220         (insn->vectorExtensionType == TYPE_XOP &&
1221          wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1222 
1223       uint16_t instructionIDWithREXW;
1224       if (getInstructionIDWithAttrMask(&instructionIDWithREXW, insn,
1225                                        attrMask | ATTR_REXW)) {
1226         insn->instructionID = instructionID;
1227         insn->spec = &INSTRUCTIONS_SYM[instructionID];
1228         return 0;
1229       }
1230 
1231       auto SpecName = mii->getName(instructionIDWithREXW);
1232       // If not a 64-bit instruction. Switch the opcode.
1233       if (!is64Bit(SpecName.data())) {
1234         insn->instructionID = instructionIDWithREXW;
1235         insn->spec = &INSTRUCTIONS_SYM[instructionIDWithREXW];
1236         return 0;
1237       }
1238     }
1239   }
1240 
1241   // Absolute moves, umonitor, and movdir64b need special handling.
1242   // -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1243   //  inverted w.r.t.
1244   // -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1245   //  any position.
1246   if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1247       (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1248       (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1249     // Make sure we observed the prefixes in any position.
1250     if (insn->hasAdSize)
1251       attrMask |= ATTR_ADSIZE;
1252     if (insn->hasOpSize)
1253       attrMask |= ATTR_OPSIZE;
1254 
1255     // In 16-bit, invert the attributes.
1256     if (insn->mode == MODE_16BIT) {
1257       attrMask ^= ATTR_ADSIZE;
1258 
1259       // The OpSize attribute is only valid with the absolute moves.
1260       if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1261         attrMask ^= ATTR_OPSIZE;
1262     }
1263 
1264     if (getInstructionIDWithAttrMask(&instructionID, insn, attrMask))
1265       return -1;
1266 
1267     insn->instructionID = instructionID;
1268     insn->spec = &INSTRUCTIONS_SYM[instructionID];
1269     return 0;
1270   }
1271 
1272   if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1273       !(attrMask & ATTR_OPSIZE)) {
1274     // The instruction tables make no distinction between instructions that
1275     // allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1276     // particular spot (i.e., many MMX operations). In general we're
1277     // conservative, but in the specific case where OpSize is present but not in
1278     // the right place we check if there's a 16-bit operation.
1279     const struct InstructionSpecifier *spec;
1280     uint16_t instructionIDWithOpsize;
1281     llvm::StringRef specName, specWithOpSizeName;
1282 
1283     spec = &INSTRUCTIONS_SYM[instructionID];
1284 
1285     if (getInstructionIDWithAttrMask(&instructionIDWithOpsize, insn,
1286                                      attrMask | ATTR_OPSIZE)) {
1287       // ModRM required with OpSize but not present. Give up and return the
1288       // version without OpSize set.
1289       insn->instructionID = instructionID;
1290       insn->spec = spec;
1291       return 0;
1292     }
1293 
1294     specName = mii->getName(instructionID);
1295     specWithOpSizeName = mii->getName(instructionIDWithOpsize);
1296 
1297     if (is16BitEquivalent(specName.data(), specWithOpSizeName.data()) &&
1298         (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1299       insn->instructionID = instructionIDWithOpsize;
1300       insn->spec = &INSTRUCTIONS_SYM[instructionIDWithOpsize];
1301     } else {
1302       insn->instructionID = instructionID;
1303       insn->spec = spec;
1304     }
1305     return 0;
1306   }
1307 
1308   if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1309       insn->rexPrefix & 0x01) {
1310     // NOOP shouldn't decode as NOOP if REX.b is set. Instead it should decode
1311     // as XCHG %r8, %eax.
1312     const struct InstructionSpecifier *spec;
1313     uint16_t instructionIDWithNewOpcode;
1314     const struct InstructionSpecifier *specWithNewOpcode;
1315 
1316     spec = &INSTRUCTIONS_SYM[instructionID];
1317 
1318     // Borrow opcode from one of the other XCHGar opcodes
1319     insn->opcode = 0x91;
1320 
1321     if (getInstructionIDWithAttrMask(&instructionIDWithNewOpcode, insn,
1322                                      attrMask)) {
1323       insn->opcode = 0x90;
1324 
1325       insn->instructionID = instructionID;
1326       insn->spec = spec;
1327       return 0;
1328     }
1329 
1330     specWithNewOpcode = &INSTRUCTIONS_SYM[instructionIDWithNewOpcode];
1331 
1332     // Change back
1333     insn->opcode = 0x90;
1334 
1335     insn->instructionID = instructionIDWithNewOpcode;
1336     insn->spec = specWithNewOpcode;
1337 
1338     return 0;
1339   }
1340 
1341   insn->instructionID = instructionID;
1342   insn->spec = &INSTRUCTIONS_SYM[insn->instructionID];
1343 
1344   return 0;
1345 }
1346 
1347 // Read an operand from the opcode field of an instruction and interprets it
1348 // appropriately given the operand width. Handles AddRegFrm instructions.
1349 //
1350 // @param insn  - the instruction whose opcode field is to be read.
1351 // @param size  - The width (in bytes) of the register being specified.
1352 //                1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1353 //                RAX.
1354 // @return      - 0 on success; nonzero otherwise.
1355 static int readOpcodeRegister(struct InternalInstruction *insn, uint8_t size) {
1356   LLVM_DEBUG(dbgs() << "readOpcodeRegister()");
1357 
1358   if (size == 0)
1359     size = insn->registerSize;
1360 
1361   switch (size) {
1362   case 1:
1363     insn->opcodeRegister = (Reg)(
1364         MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1365     if (insn->rexPrefix && insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1366         insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1367       insn->opcodeRegister =
1368           (Reg)(MODRM_REG_SPL + (insn->opcodeRegister - MODRM_REG_AL - 4));
1369     }
1370 
1371     break;
1372   case 2:
1373     insn->opcodeRegister = (Reg)(
1374         MODRM_REG_AX + ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1375     break;
1376   case 4:
1377     insn->opcodeRegister =
1378         (Reg)(MODRM_REG_EAX +
1379               ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1380     break;
1381   case 8:
1382     insn->opcodeRegister =
1383         (Reg)(MODRM_REG_RAX +
1384               ((bFromREX(insn->rexPrefix) << 3) | (insn->opcode & 7)));
1385     break;
1386   }
1387 
1388   return 0;
1389 }
1390 
1391 // Consume an immediate operand from an instruction, given the desired operand
1392 // size.
1393 //
1394 // @param insn  - The instruction whose operand is to be read.
1395 // @param size  - The width (in bytes) of the operand.
1396 // @return      - 0 if the immediate was successfully consumed; nonzero
1397 //                otherwise.
1398 static int readImmediate(struct InternalInstruction *insn, uint8_t size) {
1399   uint8_t imm8;
1400   uint16_t imm16;
1401   uint32_t imm32;
1402   uint64_t imm64;
1403 
1404   LLVM_DEBUG(dbgs() << "readImmediate()");
1405 
1406   assert(insn->numImmediatesConsumed < 2 && "Already consumed two immediates");
1407 
1408   insn->immediateSize = size;
1409   insn->immediateOffset = insn->readerCursor - insn->startLocation;
1410 
1411   switch (size) {
1412   case 1:
1413     if (consume(insn, imm8))
1414       return -1;
1415     insn->immediates[insn->numImmediatesConsumed] = imm8;
1416     break;
1417   case 2:
1418     if (consume(insn, imm16))
1419       return -1;
1420     insn->immediates[insn->numImmediatesConsumed] = imm16;
1421     break;
1422   case 4:
1423     if (consume(insn, imm32))
1424       return -1;
1425     insn->immediates[insn->numImmediatesConsumed] = imm32;
1426     break;
1427   case 8:
1428     if (consume(insn, imm64))
1429       return -1;
1430     insn->immediates[insn->numImmediatesConsumed] = imm64;
1431     break;
1432   default:
1433     llvm_unreachable("invalid size");
1434   }
1435 
1436   insn->numImmediatesConsumed++;
1437 
1438   return 0;
1439 }
1440 
1441 // Consume vvvv from an instruction if it has a VEX prefix.
1442 static int readVVVV(struct InternalInstruction *insn) {
1443   LLVM_DEBUG(dbgs() << "readVVVV()");
1444 
1445   int vvvv;
1446   if (insn->vectorExtensionType == TYPE_EVEX)
1447     vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1448             vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1449   else if (insn->vectorExtensionType == TYPE_VEX_3B)
1450     vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1451   else if (insn->vectorExtensionType == TYPE_VEX_2B)
1452     vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1453   else if (insn->vectorExtensionType == TYPE_XOP)
1454     vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1455   else
1456     return -1;
1457 
1458   if (insn->mode != MODE_64BIT)
1459     vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1460 
1461   insn->vvvv = static_cast<Reg>(vvvv);
1462   return 0;
1463 }
1464 
1465 // Read an mask register from the opcode field of an instruction.
1466 //
1467 // @param insn    - The instruction whose opcode field is to be read.
1468 // @return        - 0 on success; nonzero otherwise.
1469 static int readMaskRegister(struct InternalInstruction *insn) {
1470   LLVM_DEBUG(dbgs() << "readMaskRegister()");
1471 
1472   if (insn->vectorExtensionType != TYPE_EVEX)
1473     return -1;
1474 
1475   insn->writemask =
1476       static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1477   return 0;
1478 }
1479 
1480 // Consults the specifier for an instruction and consumes all
1481 // operands for that instruction, interpreting them as it goes.
1482 static int readOperands(struct InternalInstruction *insn) {
1483   int hasVVVV, needVVVV;
1484   int sawRegImm = 0;
1485 
1486   LLVM_DEBUG(dbgs() << "readOperands()");
1487 
1488   // If non-zero vvvv specified, make sure one of the operands uses it.
1489   hasVVVV = !readVVVV(insn);
1490   needVVVV = hasVVVV && (insn->vvvv != 0);
1491 
1492   for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1493     switch (Op.encoding) {
1494     case ENCODING_NONE:
1495     case ENCODING_SI:
1496     case ENCODING_DI:
1497       break;
1498     CASE_ENCODING_VSIB:
1499       // VSIB can use the V2 bit so check only the other bits.
1500       if (needVVVV)
1501         needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1502       if (readModRM(insn))
1503         return -1;
1504 
1505       // Reject if SIB wasn't used.
1506       if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1507         return -1;
1508 
1509       // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1510       if (insn->sibIndex == SIB_INDEX_NONE)
1511         insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1512 
1513       // If EVEX.v2 is set this is one of the 16-31 registers.
1514       if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1515           v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1516         insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1517 
1518       // Adjust the index register to the correct size.
1519       switch ((OperandType)Op.type) {
1520       default:
1521         debug("Unhandled VSIB index type");
1522         return -1;
1523       case TYPE_MVSIBX:
1524         insn->sibIndex =
1525             (SIBIndex)(SIB_INDEX_XMM0 + (insn->sibIndex - insn->sibIndexBase));
1526         break;
1527       case TYPE_MVSIBY:
1528         insn->sibIndex =
1529             (SIBIndex)(SIB_INDEX_YMM0 + (insn->sibIndex - insn->sibIndexBase));
1530         break;
1531       case TYPE_MVSIBZ:
1532         insn->sibIndex =
1533             (SIBIndex)(SIB_INDEX_ZMM0 + (insn->sibIndex - insn->sibIndexBase));
1534         break;
1535       }
1536 
1537       // Apply the AVX512 compressed displacement scaling factor.
1538       if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1539         insn->displacement *= 1 << (Op.encoding - ENCODING_VSIB);
1540       break;
1541     case ENCODING_SIB:
1542       // Reject if SIB wasn't used.
1543       if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1544         return -1;
1545       if (readModRM(insn))
1546         return -1;
1547       if (fixupReg(insn, &Op))
1548         return -1;
1549       break;
1550     case ENCODING_REG:
1551     CASE_ENCODING_RM:
1552       if (readModRM(insn))
1553         return -1;
1554       if (fixupReg(insn, &Op))
1555         return -1;
1556       // Apply the AVX512 compressed displacement scaling factor.
1557       if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1558         insn->displacement *= 1 << (Op.encoding - ENCODING_RM);
1559       break;
1560     case ENCODING_IB:
1561       if (sawRegImm) {
1562         // Saw a register immediate so don't read again and instead split the
1563         // previous immediate. FIXME: This is a hack.
1564         insn->immediates[insn->numImmediatesConsumed] =
1565             insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1566         ++insn->numImmediatesConsumed;
1567         break;
1568       }
1569       if (readImmediate(insn, 1))
1570         return -1;
1571       if (Op.type == TYPE_XMM || Op.type == TYPE_YMM)
1572         sawRegImm = 1;
1573       break;
1574     case ENCODING_IW:
1575       if (readImmediate(insn, 2))
1576         return -1;
1577       break;
1578     case ENCODING_ID:
1579       if (readImmediate(insn, 4))
1580         return -1;
1581       break;
1582     case ENCODING_IO:
1583       if (readImmediate(insn, 8))
1584         return -1;
1585       break;
1586     case ENCODING_Iv:
1587       if (readImmediate(insn, insn->immediateSize))
1588         return -1;
1589       break;
1590     case ENCODING_Ia:
1591       if (readImmediate(insn, insn->addressSize))
1592         return -1;
1593       break;
1594     case ENCODING_IRC:
1595       insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
1596                  lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
1597       break;
1598     case ENCODING_RB:
1599       if (readOpcodeRegister(insn, 1))
1600         return -1;
1601       break;
1602     case ENCODING_RW:
1603       if (readOpcodeRegister(insn, 2))
1604         return -1;
1605       break;
1606     case ENCODING_RD:
1607       if (readOpcodeRegister(insn, 4))
1608         return -1;
1609       break;
1610     case ENCODING_RO:
1611       if (readOpcodeRegister(insn, 8))
1612         return -1;
1613       break;
1614     case ENCODING_Rv:
1615       if (readOpcodeRegister(insn, 0))
1616         return -1;
1617       break;
1618     case ENCODING_CC:
1619       insn->immediates[1] = insn->opcode & 0xf;
1620       break;
1621     case ENCODING_FP:
1622       break;
1623     case ENCODING_VVVV:
1624       needVVVV = 0; // Mark that we have found a VVVV operand.
1625       if (!hasVVVV)
1626         return -1;
1627       if (insn->mode != MODE_64BIT)
1628         insn->vvvv = static_cast<Reg>(insn->vvvv & 0x7);
1629       if (fixupReg(insn, &Op))
1630         return -1;
1631       break;
1632     case ENCODING_WRITEMASK:
1633       if (readMaskRegister(insn))
1634         return -1;
1635       break;
1636     case ENCODING_DUP:
1637       break;
1638     default:
1639       LLVM_DEBUG(dbgs() << "Encountered an operand with an unknown encoding.");
1640       return -1;
1641     }
1642   }
1643 
1644   // If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail
1645   if (needVVVV)
1646     return -1;
1647 
1648   return 0;
1649 }
1650 
1651 namespace llvm {
1652 
1653 // Fill-ins to make the compiler happy. These constants are never actually
1654 // assigned; they are just filler to make an automatically-generated switch
1655 // statement work.
1656 namespace X86 {
1657   enum {
1658     BX_SI = 500,
1659     BX_DI = 501,
1660     BP_SI = 502,
1661     BP_DI = 503,
1662     sib   = 504,
1663     sib64 = 505
1664   };
1665 }
1666 
1667 }
1668 
1669 static bool translateInstruction(MCInst &target,
1670                                 InternalInstruction &source,
1671                                 const MCDisassembler *Dis);
1672 
1673 namespace {
1674 
1675 /// Generic disassembler for all X86 platforms. All each platform class should
1676 /// have to do is subclass the constructor, and provide a different
1677 /// disassemblerMode value.
1678 class X86GenericDisassembler : public MCDisassembler {
1679   std::unique_ptr<const MCInstrInfo> MII;
1680 public:
1681   X86GenericDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
1682                          std::unique_ptr<const MCInstrInfo> MII);
1683 public:
1684   DecodeStatus getInstruction(MCInst &instr, uint64_t &size,
1685                               ArrayRef<uint8_t> Bytes, uint64_t Address,
1686                               raw_ostream &cStream) const override;
1687 
1688 private:
1689   DisassemblerMode              fMode;
1690 };
1691 
1692 }
1693 
1694 X86GenericDisassembler::X86GenericDisassembler(
1695                                          const MCSubtargetInfo &STI,
1696                                          MCContext &Ctx,
1697                                          std::unique_ptr<const MCInstrInfo> MII)
1698   : MCDisassembler(STI, Ctx), MII(std::move(MII)) {
1699   const FeatureBitset &FB = STI.getFeatureBits();
1700   if (FB[X86::Mode16Bit]) {
1701     fMode = MODE_16BIT;
1702     return;
1703   } else if (FB[X86::Mode32Bit]) {
1704     fMode = MODE_32BIT;
1705     return;
1706   } else if (FB[X86::Mode64Bit]) {
1707     fMode = MODE_64BIT;
1708     return;
1709   }
1710 
1711   llvm_unreachable("Invalid CPU mode");
1712 }
1713 
1714 MCDisassembler::DecodeStatus X86GenericDisassembler::getInstruction(
1715     MCInst &Instr, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t Address,
1716     raw_ostream &CStream) const {
1717   CommentStream = &CStream;
1718 
1719   InternalInstruction Insn;
1720   memset(&Insn, 0, sizeof(InternalInstruction));
1721   Insn.bytes = Bytes;
1722   Insn.startLocation = Address;
1723   Insn.readerCursor = Address;
1724   Insn.mode = fMode;
1725 
1726   if (Bytes.empty() || readPrefixes(&Insn) || readOpcode(&Insn) ||
1727       getInstructionID(&Insn, MII.get()) || Insn.instructionID == 0 ||
1728       readOperands(&Insn)) {
1729     Size = Insn.readerCursor - Address;
1730     return Fail;
1731   }
1732 
1733   Insn.operands = x86OperandSets[Insn.spec->operands];
1734   Insn.length = Insn.readerCursor - Insn.startLocation;
1735   Size = Insn.length;
1736   if (Size > 15)
1737     LLVM_DEBUG(dbgs() << "Instruction exceeds 15-byte limit");
1738 
1739   bool Ret = translateInstruction(Instr, Insn, this);
1740   if (!Ret) {
1741     unsigned Flags = X86::IP_NO_PREFIX;
1742     if (Insn.hasAdSize)
1743       Flags |= X86::IP_HAS_AD_SIZE;
1744     if (!Insn.mandatoryPrefix) {
1745       if (Insn.hasOpSize)
1746         Flags |= X86::IP_HAS_OP_SIZE;
1747       if (Insn.repeatPrefix == 0xf2)
1748         Flags |= X86::IP_HAS_REPEAT_NE;
1749       else if (Insn.repeatPrefix == 0xf3 &&
1750                // It should not be 'pause' f3 90
1751                Insn.opcode != 0x90)
1752         Flags |= X86::IP_HAS_REPEAT;
1753       if (Insn.hasLockPrefix)
1754         Flags |= X86::IP_HAS_LOCK;
1755     }
1756     Instr.setFlags(Flags);
1757   }
1758   return (!Ret) ? Success : Fail;
1759 }
1760 
1761 //
1762 // Private code that translates from struct InternalInstructions to MCInsts.
1763 //
1764 
1765 /// translateRegister - Translates an internal register to the appropriate LLVM
1766 ///   register, and appends it as an operand to an MCInst.
1767 ///
1768 /// @param mcInst     - The MCInst to append to.
1769 /// @param reg        - The Reg to append.
1770 static void translateRegister(MCInst &mcInst, Reg reg) {
1771 #define ENTRY(x) X86::x,
1772   static constexpr MCPhysReg llvmRegnums[] = {ALL_REGS};
1773 #undef ENTRY
1774 
1775   MCPhysReg llvmRegnum = llvmRegnums[reg];
1776   mcInst.addOperand(MCOperand::createReg(llvmRegnum));
1777 }
1778 
1779 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
1780 /// immediate Value in the MCInst.
1781 ///
1782 /// @param Value      - The immediate Value, has had any PC adjustment made by
1783 ///                     the caller.
1784 /// @param isBranch   - If the instruction is a branch instruction
1785 /// @param Address    - The starting address of the instruction
1786 /// @param Offset     - The byte offset to this immediate in the instruction
1787 /// @param Width      - The byte width of this immediate in the instruction
1788 ///
1789 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
1790 /// called then that function is called to get any symbolic information for the
1791 /// immediate in the instruction using the Address, Offset and Width.  If that
1792 /// returns non-zero then the symbolic information it returns is used to create
1793 /// an MCExpr and that is added as an operand to the MCInst.  If getOpInfo()
1794 /// returns zero and isBranch is true then a symbol look up for immediate Value
1795 /// is done and if a symbol is found an MCExpr is created with that, else
1796 /// an MCExpr with the immediate Value is created.  This function returns true
1797 /// if it adds an operand to the MCInst and false otherwise.
1798 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
1799                                      uint64_t Address, uint64_t Offset,
1800                                      uint64_t Width, MCInst &MI,
1801                                      const MCDisassembler *Dis) {
1802   return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
1803                                        Offset, Width);
1804 }
1805 
1806 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
1807 /// referenced by a load instruction with the base register that is the rip.
1808 /// These can often be addresses in a literal pool.  The Address of the
1809 /// instruction and its immediate Value are used to determine the address
1810 /// being referenced in the literal pool entry.  The SymbolLookUp call back will
1811 /// return a pointer to a literal 'C' string if the referenced address is an
1812 /// address into a section with 'C' string literals.
1813 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
1814                                             const void *Decoder) {
1815   const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
1816   Dis->tryAddingPcLoadReferenceComment(Value, Address);
1817 }
1818 
1819 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
1820   0,        // SEG_OVERRIDE_NONE
1821   X86::CS,
1822   X86::SS,
1823   X86::DS,
1824   X86::ES,
1825   X86::FS,
1826   X86::GS
1827 };
1828 
1829 /// translateSrcIndex   - Appends a source index operand to an MCInst.
1830 ///
1831 /// @param mcInst       - The MCInst to append to.
1832 /// @param insn         - The internal instruction.
1833 static bool translateSrcIndex(MCInst &mcInst, InternalInstruction &insn) {
1834   unsigned baseRegNo;
1835 
1836   if (insn.mode == MODE_64BIT)
1837     baseRegNo = insn.hasAdSize ? X86::ESI : X86::RSI;
1838   else if (insn.mode == MODE_32BIT)
1839     baseRegNo = insn.hasAdSize ? X86::SI : X86::ESI;
1840   else {
1841     assert(insn.mode == MODE_16BIT);
1842     baseRegNo = insn.hasAdSize ? X86::ESI : X86::SI;
1843   }
1844   MCOperand baseReg = MCOperand::createReg(baseRegNo);
1845   mcInst.addOperand(baseReg);
1846 
1847   MCOperand segmentReg;
1848   segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
1849   mcInst.addOperand(segmentReg);
1850   return false;
1851 }
1852 
1853 /// translateDstIndex   - Appends a destination index operand to an MCInst.
1854 ///
1855 /// @param mcInst       - The MCInst to append to.
1856 /// @param insn         - The internal instruction.
1857 
1858 static bool translateDstIndex(MCInst &mcInst, InternalInstruction &insn) {
1859   unsigned baseRegNo;
1860 
1861   if (insn.mode == MODE_64BIT)
1862     baseRegNo = insn.hasAdSize ? X86::EDI : X86::RDI;
1863   else if (insn.mode == MODE_32BIT)
1864     baseRegNo = insn.hasAdSize ? X86::DI : X86::EDI;
1865   else {
1866     assert(insn.mode == MODE_16BIT);
1867     baseRegNo = insn.hasAdSize ? X86::EDI : X86::DI;
1868   }
1869   MCOperand baseReg = MCOperand::createReg(baseRegNo);
1870   mcInst.addOperand(baseReg);
1871   return false;
1872 }
1873 
1874 /// translateImmediate  - Appends an immediate operand to an MCInst.
1875 ///
1876 /// @param mcInst       - The MCInst to append to.
1877 /// @param immediate    - The immediate value to append.
1878 /// @param operand      - The operand, as stored in the descriptor table.
1879 /// @param insn         - The internal instruction.
1880 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
1881                                const OperandSpecifier &operand,
1882                                InternalInstruction &insn,
1883                                const MCDisassembler *Dis) {
1884   // Sign-extend the immediate if necessary.
1885 
1886   OperandType type = (OperandType)operand.type;
1887 
1888   bool isBranch = false;
1889   uint64_t pcrel = 0;
1890   if (type == TYPE_REL) {
1891     isBranch = true;
1892     pcrel = insn.startLocation +
1893             insn.immediateOffset + insn.immediateSize;
1894     switch (operand.encoding) {
1895     default:
1896       break;
1897     case ENCODING_Iv:
1898       switch (insn.displacementSize) {
1899       default:
1900         break;
1901       case 1:
1902         if(immediate & 0x80)
1903           immediate |= ~(0xffull);
1904         break;
1905       case 2:
1906         if(immediate & 0x8000)
1907           immediate |= ~(0xffffull);
1908         break;
1909       case 4:
1910         if(immediate & 0x80000000)
1911           immediate |= ~(0xffffffffull);
1912         break;
1913       case 8:
1914         break;
1915       }
1916       break;
1917     case ENCODING_IB:
1918       if(immediate & 0x80)
1919         immediate |= ~(0xffull);
1920       break;
1921     case ENCODING_IW:
1922       if(immediate & 0x8000)
1923         immediate |= ~(0xffffull);
1924       break;
1925     case ENCODING_ID:
1926       if(immediate & 0x80000000)
1927         immediate |= ~(0xffffffffull);
1928       break;
1929     }
1930   }
1931   // By default sign-extend all X86 immediates based on their encoding.
1932   else if (type == TYPE_IMM) {
1933     switch (operand.encoding) {
1934     default:
1935       break;
1936     case ENCODING_IB:
1937       if(immediate & 0x80)
1938         immediate |= ~(0xffull);
1939       break;
1940     case ENCODING_IW:
1941       if(immediate & 0x8000)
1942         immediate |= ~(0xffffull);
1943       break;
1944     case ENCODING_ID:
1945       if(immediate & 0x80000000)
1946         immediate |= ~(0xffffffffull);
1947       break;
1948     case ENCODING_IO:
1949       break;
1950     }
1951   }
1952 
1953   switch (type) {
1954   case TYPE_XMM:
1955     mcInst.addOperand(MCOperand::createReg(X86::XMM0 + (immediate >> 4)));
1956     return;
1957   case TYPE_YMM:
1958     mcInst.addOperand(MCOperand::createReg(X86::YMM0 + (immediate >> 4)));
1959     return;
1960   case TYPE_ZMM:
1961     mcInst.addOperand(MCOperand::createReg(X86::ZMM0 + (immediate >> 4)));
1962     return;
1963   default:
1964     // operand is 64 bits wide.  Do nothing.
1965     break;
1966   }
1967 
1968   if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
1969                                insn.immediateOffset, insn.immediateSize,
1970                                mcInst, Dis))
1971     mcInst.addOperand(MCOperand::createImm(immediate));
1972 
1973   if (type == TYPE_MOFFS) {
1974     MCOperand segmentReg;
1975     segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
1976     mcInst.addOperand(segmentReg);
1977   }
1978 }
1979 
1980 /// translateRMRegister - Translates a register stored in the R/M field of the
1981 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
1982 /// @param mcInst       - The MCInst to append to.
1983 /// @param insn         - The internal instruction to extract the R/M field
1984 ///                       from.
1985 /// @return             - 0 on success; -1 otherwise
1986 static bool translateRMRegister(MCInst &mcInst,
1987                                 InternalInstruction &insn) {
1988   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
1989     debug("A R/M register operand may not have a SIB byte");
1990     return true;
1991   }
1992 
1993   switch (insn.eaBase) {
1994   default:
1995     debug("Unexpected EA base register");
1996     return true;
1997   case EA_BASE_NONE:
1998     debug("EA_BASE_NONE for ModR/M base");
1999     return true;
2000 #define ENTRY(x) case EA_BASE_##x:
2001   ALL_EA_BASES
2002 #undef ENTRY
2003     debug("A R/M register operand may not have a base; "
2004           "the operand must be a register.");
2005     return true;
2006 #define ENTRY(x)                                                      \
2007   case EA_REG_##x:                                                    \
2008     mcInst.addOperand(MCOperand::createReg(X86::x)); break;
2009   ALL_REGS
2010 #undef ENTRY
2011   }
2012 
2013   return false;
2014 }
2015 
2016 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
2017 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
2018 ///   operand in LLVM's format, and appends it to an MCInst.
2019 ///
2020 /// @param mcInst       - The MCInst to append to.
2021 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
2022 ///                       from.
2023 /// @param ForceSIB     - The instruction must use SIB.
2024 /// @return             - 0 on success; nonzero otherwise
2025 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
2026                               const MCDisassembler *Dis,
2027                               bool ForceSIB = false) {
2028   // Addresses in an MCInst are represented as five operands:
2029   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the
2030   //                                SIB base
2031   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified
2032   //                                scale amount
2033   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
2034   //                                the index (which is multiplied by the
2035   //                                scale amount)
2036   //   4. displacement  (immediate) 0, or the displacement if there is one
2037   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
2038   //                                if we have segment overrides
2039 
2040   MCOperand baseReg;
2041   MCOperand scaleAmount;
2042   MCOperand indexReg;
2043   MCOperand displacement;
2044   MCOperand segmentReg;
2045   uint64_t pcrel = 0;
2046 
2047   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
2048     if (insn.sibBase != SIB_BASE_NONE) {
2049       switch (insn.sibBase) {
2050       default:
2051         debug("Unexpected sibBase");
2052         return true;
2053 #define ENTRY(x)                                          \
2054       case SIB_BASE_##x:                                  \
2055         baseReg = MCOperand::createReg(X86::x); break;
2056       ALL_SIB_BASES
2057 #undef ENTRY
2058       }
2059     } else {
2060       baseReg = MCOperand::createReg(X86::NoRegister);
2061     }
2062 
2063     if (insn.sibIndex != SIB_INDEX_NONE) {
2064       switch (insn.sibIndex) {
2065       default:
2066         debug("Unexpected sibIndex");
2067         return true;
2068 #define ENTRY(x)                                          \
2069       case SIB_INDEX_##x:                                 \
2070         indexReg = MCOperand::createReg(X86::x); break;
2071       EA_BASES_32BIT
2072       EA_BASES_64BIT
2073       REGS_XMM
2074       REGS_YMM
2075       REGS_ZMM
2076 #undef ENTRY
2077       }
2078     } else {
2079       // Use EIZ/RIZ for a few ambiguous cases where the SIB byte is present,
2080       // but no index is used and modrm alone should have been enough.
2081       // -No base register in 32-bit mode. In 64-bit mode this is used to
2082       //  avoid rip-relative addressing.
2083       // -Any base register used other than ESP/RSP/R12D/R12. Using these as a
2084       //  base always requires a SIB byte.
2085       // -A scale other than 1 is used.
2086       if (!ForceSIB &&
2087           (insn.sibScale != 1 ||
2088            (insn.sibBase == SIB_BASE_NONE && insn.mode != MODE_64BIT) ||
2089            (insn.sibBase != SIB_BASE_NONE &&
2090             insn.sibBase != SIB_BASE_ESP && insn.sibBase != SIB_BASE_RSP &&
2091             insn.sibBase != SIB_BASE_R12D && insn.sibBase != SIB_BASE_R12))) {
2092         indexReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIZ :
2093                                                                 X86::RIZ);
2094       } else
2095         indexReg = MCOperand::createReg(X86::NoRegister);
2096     }
2097 
2098     scaleAmount = MCOperand::createImm(insn.sibScale);
2099   } else {
2100     switch (insn.eaBase) {
2101     case EA_BASE_NONE:
2102       if (insn.eaDisplacement == EA_DISP_NONE) {
2103         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
2104         return true;
2105       }
2106       if (insn.mode == MODE_64BIT){
2107         pcrel = insn.startLocation +
2108                 insn.displacementOffset + insn.displacementSize;
2109         tryAddingPcLoadReferenceComment(insn.startLocation +
2110                                         insn.displacementOffset,
2111                                         insn.displacement + pcrel, Dis);
2112         // Section 2.2.1.6
2113         baseReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIP :
2114                                                                X86::RIP);
2115       }
2116       else
2117         baseReg = MCOperand::createReg(X86::NoRegister);
2118 
2119       indexReg = MCOperand::createReg(X86::NoRegister);
2120       break;
2121     case EA_BASE_BX_SI:
2122       baseReg = MCOperand::createReg(X86::BX);
2123       indexReg = MCOperand::createReg(X86::SI);
2124       break;
2125     case EA_BASE_BX_DI:
2126       baseReg = MCOperand::createReg(X86::BX);
2127       indexReg = MCOperand::createReg(X86::DI);
2128       break;
2129     case EA_BASE_BP_SI:
2130       baseReg = MCOperand::createReg(X86::BP);
2131       indexReg = MCOperand::createReg(X86::SI);
2132       break;
2133     case EA_BASE_BP_DI:
2134       baseReg = MCOperand::createReg(X86::BP);
2135       indexReg = MCOperand::createReg(X86::DI);
2136       break;
2137     default:
2138       indexReg = MCOperand::createReg(X86::NoRegister);
2139       switch (insn.eaBase) {
2140       default:
2141         debug("Unexpected eaBase");
2142         return true;
2143         // Here, we will use the fill-ins defined above.  However,
2144         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
2145         //   sib and sib64 were handled in the top-level if, so they're only
2146         //   placeholders to keep the compiler happy.
2147 #define ENTRY(x)                                        \
2148       case EA_BASE_##x:                                 \
2149         baseReg = MCOperand::createReg(X86::x); break;
2150       ALL_EA_BASES
2151 #undef ENTRY
2152 #define ENTRY(x) case EA_REG_##x:
2153       ALL_REGS
2154 #undef ENTRY
2155         debug("A R/M memory operand may not be a register; "
2156               "the base field must be a base.");
2157         return true;
2158       }
2159     }
2160 
2161     scaleAmount = MCOperand::createImm(1);
2162   }
2163 
2164   displacement = MCOperand::createImm(insn.displacement);
2165 
2166   segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
2167 
2168   mcInst.addOperand(baseReg);
2169   mcInst.addOperand(scaleAmount);
2170   mcInst.addOperand(indexReg);
2171   if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
2172                                insn.startLocation, insn.displacementOffset,
2173                                insn.displacementSize, mcInst, Dis))
2174     mcInst.addOperand(displacement);
2175   mcInst.addOperand(segmentReg);
2176   return false;
2177 }
2178 
2179 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
2180 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
2181 ///
2182 /// @param mcInst       - The MCInst to append to.
2183 /// @param operand      - The operand, as stored in the descriptor table.
2184 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
2185 ///                       from.
2186 /// @return             - 0 on success; nonzero otherwise
2187 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
2188                         InternalInstruction &insn, const MCDisassembler *Dis) {
2189   switch (operand.type) {
2190   default:
2191     debug("Unexpected type for a R/M operand");
2192     return true;
2193   case TYPE_R8:
2194   case TYPE_R16:
2195   case TYPE_R32:
2196   case TYPE_R64:
2197   case TYPE_Rv:
2198   case TYPE_MM64:
2199   case TYPE_XMM:
2200   case TYPE_YMM:
2201   case TYPE_ZMM:
2202   case TYPE_TMM:
2203   case TYPE_VK_PAIR:
2204   case TYPE_VK:
2205   case TYPE_DEBUGREG:
2206   case TYPE_CONTROLREG:
2207   case TYPE_BNDR:
2208     return translateRMRegister(mcInst, insn);
2209   case TYPE_M:
2210   case TYPE_MVSIBX:
2211   case TYPE_MVSIBY:
2212   case TYPE_MVSIBZ:
2213     return translateRMMemory(mcInst, insn, Dis);
2214   case TYPE_MSIB:
2215     return translateRMMemory(mcInst, insn, Dis, true);
2216   }
2217 }
2218 
2219 /// translateFPRegister - Translates a stack position on the FPU stack to its
2220 ///   LLVM form, and appends it to an MCInst.
2221 ///
2222 /// @param mcInst       - The MCInst to append to.
2223 /// @param stackPos     - The stack position to translate.
2224 static void translateFPRegister(MCInst &mcInst,
2225                                 uint8_t stackPos) {
2226   mcInst.addOperand(MCOperand::createReg(X86::ST0 + stackPos));
2227 }
2228 
2229 /// translateMaskRegister - Translates a 3-bit mask register number to
2230 ///   LLVM form, and appends it to an MCInst.
2231 ///
2232 /// @param mcInst       - The MCInst to append to.
2233 /// @param maskRegNum   - Number of mask register from 0 to 7.
2234 /// @return             - false on success; true otherwise.
2235 static bool translateMaskRegister(MCInst &mcInst,
2236                                 uint8_t maskRegNum) {
2237   if (maskRegNum >= 8) {
2238     debug("Invalid mask register number");
2239     return true;
2240   }
2241 
2242   mcInst.addOperand(MCOperand::createReg(X86::K0 + maskRegNum));
2243   return false;
2244 }
2245 
2246 /// translateOperand - Translates an operand stored in an internal instruction
2247 ///   to LLVM's format and appends it to an MCInst.
2248 ///
2249 /// @param mcInst       - The MCInst to append to.
2250 /// @param operand      - The operand, as stored in the descriptor table.
2251 /// @param insn         - The internal instruction.
2252 /// @return             - false on success; true otherwise.
2253 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
2254                              InternalInstruction &insn,
2255                              const MCDisassembler *Dis) {
2256   switch (operand.encoding) {
2257   default:
2258     debug("Unhandled operand encoding during translation");
2259     return true;
2260   case ENCODING_REG:
2261     translateRegister(mcInst, insn.reg);
2262     return false;
2263   case ENCODING_WRITEMASK:
2264     return translateMaskRegister(mcInst, insn.writemask);
2265   case ENCODING_SIB:
2266   CASE_ENCODING_RM:
2267   CASE_ENCODING_VSIB:
2268     return translateRM(mcInst, operand, insn, Dis);
2269   case ENCODING_IB:
2270   case ENCODING_IW:
2271   case ENCODING_ID:
2272   case ENCODING_IO:
2273   case ENCODING_Iv:
2274   case ENCODING_Ia:
2275     translateImmediate(mcInst,
2276                        insn.immediates[insn.numImmediatesTranslated++],
2277                        operand,
2278                        insn,
2279                        Dis);
2280     return false;
2281   case ENCODING_IRC:
2282     mcInst.addOperand(MCOperand::createImm(insn.RC));
2283     return false;
2284   case ENCODING_SI:
2285     return translateSrcIndex(mcInst, insn);
2286   case ENCODING_DI:
2287     return translateDstIndex(mcInst, insn);
2288   case ENCODING_RB:
2289   case ENCODING_RW:
2290   case ENCODING_RD:
2291   case ENCODING_RO:
2292   case ENCODING_Rv:
2293     translateRegister(mcInst, insn.opcodeRegister);
2294     return false;
2295   case ENCODING_CC:
2296     mcInst.addOperand(MCOperand::createImm(insn.immediates[1]));
2297     return false;
2298   case ENCODING_FP:
2299     translateFPRegister(mcInst, insn.modRM & 7);
2300     return false;
2301   case ENCODING_VVVV:
2302     translateRegister(mcInst, insn.vvvv);
2303     return false;
2304   case ENCODING_DUP:
2305     return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
2306                             insn, Dis);
2307   }
2308 }
2309 
2310 /// translateInstruction - Translates an internal instruction and all its
2311 ///   operands to an MCInst.
2312 ///
2313 /// @param mcInst       - The MCInst to populate with the instruction's data.
2314 /// @param insn         - The internal instruction.
2315 /// @return             - false on success; true otherwise.
2316 static bool translateInstruction(MCInst &mcInst,
2317                                 InternalInstruction &insn,
2318                                 const MCDisassembler *Dis) {
2319   if (!insn.spec) {
2320     debug("Instruction has no specification");
2321     return true;
2322   }
2323 
2324   mcInst.clear();
2325   mcInst.setOpcode(insn.instructionID);
2326   // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
2327   // prefix bytes should be disassembled as xrelease and xacquire then set the
2328   // opcode to those instead of the rep and repne opcodes.
2329   if (insn.xAcquireRelease) {
2330     if(mcInst.getOpcode() == X86::REP_PREFIX)
2331       mcInst.setOpcode(X86::XRELEASE_PREFIX);
2332     else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
2333       mcInst.setOpcode(X86::XACQUIRE_PREFIX);
2334   }
2335 
2336   insn.numImmediatesTranslated = 0;
2337 
2338   for (const auto &Op : insn.operands) {
2339     if (Op.encoding != ENCODING_NONE) {
2340       if (translateOperand(mcInst, Op, insn, Dis)) {
2341         return true;
2342       }
2343     }
2344   }
2345 
2346   return false;
2347 }
2348 
2349 static MCDisassembler *createX86Disassembler(const Target &T,
2350                                              const MCSubtargetInfo &STI,
2351                                              MCContext &Ctx) {
2352   std::unique_ptr<const MCInstrInfo> MII(T.createMCInstrInfo());
2353   return new X86GenericDisassembler(STI, Ctx, std::move(MII));
2354 }
2355 
2356 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeX86Disassembler() {
2357   // Register the disassembler.
2358   TargetRegistry::RegisterMCDisassembler(getTheX86_32Target(),
2359                                          createX86Disassembler);
2360   TargetRegistry::RegisterMCDisassembler(getTheX86_64Target(),
2361                                          createX86Disassembler);
2362 }
2363