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/TargetRegistry.h"
88 #include "llvm/Support/raw_ostream.h"
89 
90 using namespace llvm;
91 using namespace llvm::X86Disassembler;
92 
93 #define DEBUG_TYPE "x86-disassembler"
94 
95 void llvm::X86Disassembler::Debug(const char *file, unsigned line,
96                                   const char *s) {
97   dbgs() << file << ":" << line << ": " << s;
98 }
99 
100 StringRef llvm::X86Disassembler::GetInstrName(unsigned Opcode,
101                                                 const void *mii) {
102   const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
103   return MII->getName(Opcode);
104 }
105 
106 #define debug(s) LLVM_DEBUG(Debug(__FILE__, __LINE__, s));
107 
108 namespace llvm {
109 
110 // Fill-ins to make the compiler happy.  These constants are never actually
111 //   assigned; they are just filler to make an automatically-generated switch
112 //   statement work.
113 namespace X86 {
114   enum {
115     BX_SI = 500,
116     BX_DI = 501,
117     BP_SI = 502,
118     BP_DI = 503,
119     sib   = 504,
120     sib64 = 505
121   };
122 }
123 
124 }
125 
126 static bool translateInstruction(MCInst &target,
127                                 InternalInstruction &source,
128                                 const MCDisassembler *Dis);
129 
130 namespace {
131 
132 /// Generic disassembler for all X86 platforms. All each platform class should
133 /// have to do is subclass the constructor, and provide a different
134 /// disassemblerMode value.
135 class X86GenericDisassembler : public MCDisassembler {
136   std::unique_ptr<const MCInstrInfo> MII;
137 public:
138   X86GenericDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
139                          std::unique_ptr<const MCInstrInfo> MII);
140 public:
141   DecodeStatus getInstruction(MCInst &instr, uint64_t &size,
142                               ArrayRef<uint8_t> Bytes, uint64_t Address,
143                               raw_ostream &vStream,
144                               raw_ostream &cStream) const override;
145 
146 private:
147   DisassemblerMode              fMode;
148 };
149 
150 }
151 
152 X86GenericDisassembler::X86GenericDisassembler(
153                                          const MCSubtargetInfo &STI,
154                                          MCContext &Ctx,
155                                          std::unique_ptr<const MCInstrInfo> MII)
156   : MCDisassembler(STI, Ctx), MII(std::move(MII)) {
157   const FeatureBitset &FB = STI.getFeatureBits();
158   if (FB[X86::Mode16Bit]) {
159     fMode = MODE_16BIT;
160     return;
161   } else if (FB[X86::Mode32Bit]) {
162     fMode = MODE_32BIT;
163     return;
164   } else if (FB[X86::Mode64Bit]) {
165     fMode = MODE_64BIT;
166     return;
167   }
168 
169   llvm_unreachable("Invalid CPU mode");
170 }
171 
172 //
173 // Public interface for the disassembler
174 //
175 
176 MCDisassembler::DecodeStatus X86GenericDisassembler::getInstruction(
177     MCInst &Instr, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t Address,
178     raw_ostream &VStream, raw_ostream &CStream) const {
179   CommentStream = &CStream;
180 
181   InternalInstruction InternalInstr;
182 
183   std::pair<ArrayRef<uint8_t>, uint64_t> R(Bytes, Address);
184 
185   int Ret = decodeInstruction(&InternalInstr, &R, (const void *)MII.get(),
186                               Address, fMode);
187 
188   if (Ret) {
189     Size = InternalInstr.readerCursor - Address;
190     return Fail;
191   } else {
192     Size = InternalInstr.length;
193     bool Ret = translateInstruction(Instr, InternalInstr, this);
194     if (!Ret) {
195       unsigned Flags = X86::IP_NO_PREFIX;
196       if (InternalInstr.hasAdSize)
197         Flags |= X86::IP_HAS_AD_SIZE;
198       if (!InternalInstr.mandatoryPrefix) {
199         if (InternalInstr.hasOpSize)
200           Flags |= X86::IP_HAS_OP_SIZE;
201         if (InternalInstr.repeatPrefix == 0xf2)
202           Flags |= X86::IP_HAS_REPEAT_NE;
203         else if (InternalInstr.repeatPrefix == 0xf3 &&
204                  // It should not be 'pause' f3 90
205                  InternalInstr.opcode != 0x90)
206           Flags |= X86::IP_HAS_REPEAT;
207         if (InternalInstr.hasLockPrefix)
208           Flags |= X86::IP_HAS_LOCK;
209       }
210       Instr.setFlags(Flags);
211     }
212     return (!Ret) ? Success : Fail;
213   }
214 }
215 
216 //
217 // Private code that translates from struct InternalInstructions to MCInsts.
218 //
219 
220 /// translateRegister - Translates an internal register to the appropriate LLVM
221 ///   register, and appends it as an operand to an MCInst.
222 ///
223 /// @param mcInst     - The MCInst to append to.
224 /// @param reg        - The Reg to append.
225 static void translateRegister(MCInst &mcInst, Reg reg) {
226 #define ENTRY(x) X86::x,
227   static constexpr MCPhysReg llvmRegnums[] = {ALL_REGS};
228 #undef ENTRY
229 
230   MCPhysReg llvmRegnum = llvmRegnums[reg];
231   mcInst.addOperand(MCOperand::createReg(llvmRegnum));
232 }
233 
234 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
235 /// immediate Value in the MCInst.
236 ///
237 /// @param Value      - The immediate Value, has had any PC adjustment made by
238 ///                     the caller.
239 /// @param isBranch   - If the instruction is a branch instruction
240 /// @param Address    - The starting address of the instruction
241 /// @param Offset     - The byte offset to this immediate in the instruction
242 /// @param Width      - The byte width of this immediate in the instruction
243 ///
244 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
245 /// called then that function is called to get any symbolic information for the
246 /// immediate in the instruction using the Address, Offset and Width.  If that
247 /// returns non-zero then the symbolic information it returns is used to create
248 /// an MCExpr and that is added as an operand to the MCInst.  If getOpInfo()
249 /// returns zero and isBranch is true then a symbol look up for immediate Value
250 /// is done and if a symbol is found an MCExpr is created with that, else
251 /// an MCExpr with the immediate Value is created.  This function returns true
252 /// if it adds an operand to the MCInst and false otherwise.
253 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
254                                      uint64_t Address, uint64_t Offset,
255                                      uint64_t Width, MCInst &MI,
256                                      const MCDisassembler *Dis) {
257   return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
258                                        Offset, Width);
259 }
260 
261 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
262 /// referenced by a load instruction with the base register that is the rip.
263 /// These can often be addresses in a literal pool.  The Address of the
264 /// instruction and its immediate Value are used to determine the address
265 /// being referenced in the literal pool entry.  The SymbolLookUp call back will
266 /// return a pointer to a literal 'C' string if the referenced address is an
267 /// address into a section with 'C' string literals.
268 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
269                                             const void *Decoder) {
270   const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
271   Dis->tryAddingPcLoadReferenceComment(Value, Address);
272 }
273 
274 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
275   0,        // SEG_OVERRIDE_NONE
276   X86::CS,
277   X86::SS,
278   X86::DS,
279   X86::ES,
280   X86::FS,
281   X86::GS
282 };
283 
284 /// translateSrcIndex   - Appends a source index operand to an MCInst.
285 ///
286 /// @param mcInst       - The MCInst to append to.
287 /// @param insn         - The internal instruction.
288 static bool translateSrcIndex(MCInst &mcInst, InternalInstruction &insn) {
289   unsigned baseRegNo;
290 
291   if (insn.mode == MODE_64BIT)
292     baseRegNo = insn.hasAdSize ? X86::ESI : X86::RSI;
293   else if (insn.mode == MODE_32BIT)
294     baseRegNo = insn.hasAdSize ? X86::SI : X86::ESI;
295   else {
296     assert(insn.mode == MODE_16BIT);
297     baseRegNo = insn.hasAdSize ? X86::ESI : X86::SI;
298   }
299   MCOperand baseReg = MCOperand::createReg(baseRegNo);
300   mcInst.addOperand(baseReg);
301 
302   MCOperand segmentReg;
303   segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
304   mcInst.addOperand(segmentReg);
305   return false;
306 }
307 
308 /// translateDstIndex   - Appends a destination index operand to an MCInst.
309 ///
310 /// @param mcInst       - The MCInst to append to.
311 /// @param insn         - The internal instruction.
312 
313 static bool translateDstIndex(MCInst &mcInst, InternalInstruction &insn) {
314   unsigned baseRegNo;
315 
316   if (insn.mode == MODE_64BIT)
317     baseRegNo = insn.hasAdSize ? X86::EDI : X86::RDI;
318   else if (insn.mode == MODE_32BIT)
319     baseRegNo = insn.hasAdSize ? X86::DI : X86::EDI;
320   else {
321     assert(insn.mode == MODE_16BIT);
322     baseRegNo = insn.hasAdSize ? X86::EDI : X86::DI;
323   }
324   MCOperand baseReg = MCOperand::createReg(baseRegNo);
325   mcInst.addOperand(baseReg);
326   return false;
327 }
328 
329 /// translateImmediate  - Appends an immediate operand to an MCInst.
330 ///
331 /// @param mcInst       - The MCInst to append to.
332 /// @param immediate    - The immediate value to append.
333 /// @param operand      - The operand, as stored in the descriptor table.
334 /// @param insn         - The internal instruction.
335 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
336                                const OperandSpecifier &operand,
337                                InternalInstruction &insn,
338                                const MCDisassembler *Dis) {
339   // Sign-extend the immediate if necessary.
340 
341   OperandType type = (OperandType)operand.type;
342 
343   bool isBranch = false;
344   uint64_t pcrel = 0;
345   if (type == TYPE_REL) {
346     isBranch = true;
347     pcrel = insn.startLocation +
348             insn.immediateOffset + insn.immediateSize;
349     switch (operand.encoding) {
350     default:
351       break;
352     case ENCODING_Iv:
353       switch (insn.displacementSize) {
354       default:
355         break;
356       case 1:
357         if(immediate & 0x80)
358           immediate |= ~(0xffull);
359         break;
360       case 2:
361         if(immediate & 0x8000)
362           immediate |= ~(0xffffull);
363         break;
364       case 4:
365         if(immediate & 0x80000000)
366           immediate |= ~(0xffffffffull);
367         break;
368       case 8:
369         break;
370       }
371       break;
372     case ENCODING_IB:
373       if(immediate & 0x80)
374         immediate |= ~(0xffull);
375       break;
376     case ENCODING_IW:
377       if(immediate & 0x8000)
378         immediate |= ~(0xffffull);
379       break;
380     case ENCODING_ID:
381       if(immediate & 0x80000000)
382         immediate |= ~(0xffffffffull);
383       break;
384     }
385   }
386   // By default sign-extend all X86 immediates based on their encoding.
387   else if (type == TYPE_IMM) {
388     switch (operand.encoding) {
389     default:
390       break;
391     case ENCODING_IB:
392       if(immediate & 0x80)
393         immediate |= ~(0xffull);
394       break;
395     case ENCODING_IW:
396       if(immediate & 0x8000)
397         immediate |= ~(0xffffull);
398       break;
399     case ENCODING_ID:
400       if(immediate & 0x80000000)
401         immediate |= ~(0xffffffffull);
402       break;
403     case ENCODING_IO:
404       break;
405     }
406   }
407 
408   switch (type) {
409   case TYPE_XMM:
410     mcInst.addOperand(MCOperand::createReg(X86::XMM0 + (immediate >> 4)));
411     return;
412   case TYPE_YMM:
413     mcInst.addOperand(MCOperand::createReg(X86::YMM0 + (immediate >> 4)));
414     return;
415   case TYPE_ZMM:
416     mcInst.addOperand(MCOperand::createReg(X86::ZMM0 + (immediate >> 4)));
417     return;
418   default:
419     // operand is 64 bits wide.  Do nothing.
420     break;
421   }
422 
423   if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
424                                insn.immediateOffset, insn.immediateSize,
425                                mcInst, Dis))
426     mcInst.addOperand(MCOperand::createImm(immediate));
427 
428   if (type == TYPE_MOFFS) {
429     MCOperand segmentReg;
430     segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
431     mcInst.addOperand(segmentReg);
432   }
433 }
434 
435 /// translateRMRegister - Translates a register stored in the R/M field of the
436 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
437 /// @param mcInst       - The MCInst to append to.
438 /// @param insn         - The internal instruction to extract the R/M field
439 ///                       from.
440 /// @return             - 0 on success; -1 otherwise
441 static bool translateRMRegister(MCInst &mcInst,
442                                 InternalInstruction &insn) {
443   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
444     debug("A R/M register operand may not have a SIB byte");
445     return true;
446   }
447 
448   switch (insn.eaBase) {
449   default:
450     debug("Unexpected EA base register");
451     return true;
452   case EA_BASE_NONE:
453     debug("EA_BASE_NONE for ModR/M base");
454     return true;
455 #define ENTRY(x) case EA_BASE_##x:
456   ALL_EA_BASES
457 #undef ENTRY
458     debug("A R/M register operand may not have a base; "
459           "the operand must be a register.");
460     return true;
461 #define ENTRY(x)                                                      \
462   case EA_REG_##x:                                                    \
463     mcInst.addOperand(MCOperand::createReg(X86::x)); break;
464   ALL_REGS
465 #undef ENTRY
466   }
467 
468   return false;
469 }
470 
471 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
472 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
473 ///   operand in LLVM's format, and appends it to an MCInst.
474 ///
475 /// @param mcInst       - The MCInst to append to.
476 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
477 ///                       from.
478 /// @return             - 0 on success; nonzero otherwise
479 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
480                               const MCDisassembler *Dis) {
481   // Addresses in an MCInst are represented as five operands:
482   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the
483   //                                SIB base
484   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified
485   //                                scale amount
486   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
487   //                                the index (which is multiplied by the
488   //                                scale amount)
489   //   4. displacement  (immediate) 0, or the displacement if there is one
490   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
491   //                                if we have segment overrides
492 
493   MCOperand baseReg;
494   MCOperand scaleAmount;
495   MCOperand indexReg;
496   MCOperand displacement;
497   MCOperand segmentReg;
498   uint64_t pcrel = 0;
499 
500   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
501     if (insn.sibBase != SIB_BASE_NONE) {
502       switch (insn.sibBase) {
503       default:
504         debug("Unexpected sibBase");
505         return true;
506 #define ENTRY(x)                                          \
507       case SIB_BASE_##x:                                  \
508         baseReg = MCOperand::createReg(X86::x); break;
509       ALL_SIB_BASES
510 #undef ENTRY
511       }
512     } else {
513       baseReg = MCOperand::createReg(X86::NoRegister);
514     }
515 
516     if (insn.sibIndex != SIB_INDEX_NONE) {
517       switch (insn.sibIndex) {
518       default:
519         debug("Unexpected sibIndex");
520         return true;
521 #define ENTRY(x)                                          \
522       case SIB_INDEX_##x:                                 \
523         indexReg = MCOperand::createReg(X86::x); break;
524       EA_BASES_32BIT
525       EA_BASES_64BIT
526       REGS_XMM
527       REGS_YMM
528       REGS_ZMM
529 #undef ENTRY
530       }
531     } else {
532       // Use EIZ/RIZ for a few ambiguous cases where the SIB byte is present,
533       // but no index is used and modrm alone should have been enough.
534       // -No base register in 32-bit mode. In 64-bit mode this is used to
535       //  avoid rip-relative addressing.
536       // -Any base register used other than ESP/RSP/R12D/R12. Using these as a
537       //  base always requires a SIB byte.
538       // -A scale other than 1 is used.
539       if (insn.sibScale != 1 ||
540           (insn.sibBase == SIB_BASE_NONE && insn.mode != MODE_64BIT) ||
541           (insn.sibBase != SIB_BASE_NONE &&
542            insn.sibBase != SIB_BASE_ESP && insn.sibBase != SIB_BASE_RSP &&
543            insn.sibBase != SIB_BASE_R12D && insn.sibBase != SIB_BASE_R12)) {
544         indexReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIZ :
545                                                                 X86::RIZ);
546       } else
547         indexReg = MCOperand::createReg(X86::NoRegister);
548     }
549 
550     scaleAmount = MCOperand::createImm(insn.sibScale);
551   } else {
552     switch (insn.eaBase) {
553     case EA_BASE_NONE:
554       if (insn.eaDisplacement == EA_DISP_NONE) {
555         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
556         return true;
557       }
558       if (insn.mode == MODE_64BIT){
559         pcrel = insn.startLocation +
560                 insn.displacementOffset + insn.displacementSize;
561         tryAddingPcLoadReferenceComment(insn.startLocation +
562                                         insn.displacementOffset,
563                                         insn.displacement + pcrel, Dis);
564         // Section 2.2.1.6
565         baseReg = MCOperand::createReg(insn.addressSize == 4 ? X86::EIP :
566                                                                X86::RIP);
567       }
568       else
569         baseReg = MCOperand::createReg(X86::NoRegister);
570 
571       indexReg = MCOperand::createReg(X86::NoRegister);
572       break;
573     case EA_BASE_BX_SI:
574       baseReg = MCOperand::createReg(X86::BX);
575       indexReg = MCOperand::createReg(X86::SI);
576       break;
577     case EA_BASE_BX_DI:
578       baseReg = MCOperand::createReg(X86::BX);
579       indexReg = MCOperand::createReg(X86::DI);
580       break;
581     case EA_BASE_BP_SI:
582       baseReg = MCOperand::createReg(X86::BP);
583       indexReg = MCOperand::createReg(X86::SI);
584       break;
585     case EA_BASE_BP_DI:
586       baseReg = MCOperand::createReg(X86::BP);
587       indexReg = MCOperand::createReg(X86::DI);
588       break;
589     default:
590       indexReg = MCOperand::createReg(X86::NoRegister);
591       switch (insn.eaBase) {
592       default:
593         debug("Unexpected eaBase");
594         return true;
595         // Here, we will use the fill-ins defined above.  However,
596         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
597         //   sib and sib64 were handled in the top-level if, so they're only
598         //   placeholders to keep the compiler happy.
599 #define ENTRY(x)                                        \
600       case EA_BASE_##x:                                 \
601         baseReg = MCOperand::createReg(X86::x); break;
602       ALL_EA_BASES
603 #undef ENTRY
604 #define ENTRY(x) case EA_REG_##x:
605       ALL_REGS
606 #undef ENTRY
607         debug("A R/M memory operand may not be a register; "
608               "the base field must be a base.");
609         return true;
610       }
611     }
612 
613     scaleAmount = MCOperand::createImm(1);
614   }
615 
616   displacement = MCOperand::createImm(insn.displacement);
617 
618   segmentReg = MCOperand::createReg(segmentRegnums[insn.segmentOverride]);
619 
620   mcInst.addOperand(baseReg);
621   mcInst.addOperand(scaleAmount);
622   mcInst.addOperand(indexReg);
623   if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
624                                insn.startLocation, insn.displacementOffset,
625                                insn.displacementSize, mcInst, Dis))
626     mcInst.addOperand(displacement);
627   mcInst.addOperand(segmentReg);
628   return false;
629 }
630 
631 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
632 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
633 ///
634 /// @param mcInst       - The MCInst to append to.
635 /// @param operand      - The operand, as stored in the descriptor table.
636 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
637 ///                       from.
638 /// @return             - 0 on success; nonzero otherwise
639 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
640                         InternalInstruction &insn, const MCDisassembler *Dis) {
641   switch (operand.type) {
642   default:
643     debug("Unexpected type for a R/M operand");
644     return true;
645   case TYPE_R8:
646   case TYPE_R16:
647   case TYPE_R32:
648   case TYPE_R64:
649   case TYPE_Rv:
650   case TYPE_MM64:
651   case TYPE_XMM:
652   case TYPE_YMM:
653   case TYPE_ZMM:
654   case TYPE_VK_PAIR:
655   case TYPE_VK:
656   case TYPE_DEBUGREG:
657   case TYPE_CONTROLREG:
658   case TYPE_BNDR:
659     return translateRMRegister(mcInst, insn);
660   case TYPE_M:
661   case TYPE_MVSIBX:
662   case TYPE_MVSIBY:
663   case TYPE_MVSIBZ:
664     return translateRMMemory(mcInst, insn, Dis);
665   }
666 }
667 
668 /// translateFPRegister - Translates a stack position on the FPU stack to its
669 ///   LLVM form, and appends it to an MCInst.
670 ///
671 /// @param mcInst       - The MCInst to append to.
672 /// @param stackPos     - The stack position to translate.
673 static void translateFPRegister(MCInst &mcInst,
674                                 uint8_t stackPos) {
675   mcInst.addOperand(MCOperand::createReg(X86::ST0 + stackPos));
676 }
677 
678 /// translateMaskRegister - Translates a 3-bit mask register number to
679 ///   LLVM form, and appends it to an MCInst.
680 ///
681 /// @param mcInst       - The MCInst to append to.
682 /// @param maskRegNum   - Number of mask register from 0 to 7.
683 /// @return             - false on success; true otherwise.
684 static bool translateMaskRegister(MCInst &mcInst,
685                                 uint8_t maskRegNum) {
686   if (maskRegNum >= 8) {
687     debug("Invalid mask register number");
688     return true;
689   }
690 
691   mcInst.addOperand(MCOperand::createReg(X86::K0 + maskRegNum));
692   return false;
693 }
694 
695 /// translateOperand - Translates an operand stored in an internal instruction
696 ///   to LLVM's format and appends it to an MCInst.
697 ///
698 /// @param mcInst       - The MCInst to append to.
699 /// @param operand      - The operand, as stored in the descriptor table.
700 /// @param insn         - The internal instruction.
701 /// @return             - false on success; true otherwise.
702 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
703                              InternalInstruction &insn,
704                              const MCDisassembler *Dis) {
705   switch (operand.encoding) {
706   default:
707     debug("Unhandled operand encoding during translation");
708     return true;
709   case ENCODING_REG:
710     translateRegister(mcInst, insn.reg);
711     return false;
712   case ENCODING_WRITEMASK:
713     return translateMaskRegister(mcInst, insn.writemask);
714   CASE_ENCODING_RM:
715   CASE_ENCODING_VSIB:
716     return translateRM(mcInst, operand, insn, Dis);
717   case ENCODING_IB:
718   case ENCODING_IW:
719   case ENCODING_ID:
720   case ENCODING_IO:
721   case ENCODING_Iv:
722   case ENCODING_Ia:
723     translateImmediate(mcInst,
724                        insn.immediates[insn.numImmediatesTranslated++],
725                        operand,
726                        insn,
727                        Dis);
728     return false;
729   case ENCODING_IRC:
730     mcInst.addOperand(MCOperand::createImm(insn.RC));
731     return false;
732   case ENCODING_SI:
733     return translateSrcIndex(mcInst, insn);
734   case ENCODING_DI:
735     return translateDstIndex(mcInst, insn);
736   case ENCODING_RB:
737   case ENCODING_RW:
738   case ENCODING_RD:
739   case ENCODING_RO:
740   case ENCODING_Rv:
741     translateRegister(mcInst, insn.opcodeRegister);
742     return false;
743   case ENCODING_CC:
744     mcInst.addOperand(MCOperand::createImm(insn.immediates[1]));
745     return false;
746   case ENCODING_FP:
747     translateFPRegister(mcInst, insn.modRM & 7);
748     return false;
749   case ENCODING_VVVV:
750     translateRegister(mcInst, insn.vvvv);
751     return false;
752   case ENCODING_DUP:
753     return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
754                             insn, Dis);
755   }
756 }
757 
758 /// translateInstruction - Translates an internal instruction and all its
759 ///   operands to an MCInst.
760 ///
761 /// @param mcInst       - The MCInst to populate with the instruction's data.
762 /// @param insn         - The internal instruction.
763 /// @return             - false on success; true otherwise.
764 static bool translateInstruction(MCInst &mcInst,
765                                 InternalInstruction &insn,
766                                 const MCDisassembler *Dis) {
767   if (!insn.spec) {
768     debug("Instruction has no specification");
769     return true;
770   }
771 
772   mcInst.clear();
773   mcInst.setOpcode(insn.instructionID);
774   // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
775   // prefix bytes should be disassembled as xrelease and xacquire then set the
776   // opcode to those instead of the rep and repne opcodes.
777   if (insn.xAcquireRelease) {
778     if(mcInst.getOpcode() == X86::REP_PREFIX)
779       mcInst.setOpcode(X86::XRELEASE_PREFIX);
780     else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
781       mcInst.setOpcode(X86::XACQUIRE_PREFIX);
782   }
783 
784   insn.numImmediatesTranslated = 0;
785 
786   for (const auto &Op : insn.operands) {
787     if (Op.encoding != ENCODING_NONE) {
788       if (translateOperand(mcInst, Op, insn, Dis)) {
789         return true;
790       }
791     }
792   }
793 
794   return false;
795 }
796 
797 static MCDisassembler *createX86Disassembler(const Target &T,
798                                              const MCSubtargetInfo &STI,
799                                              MCContext &Ctx) {
800   std::unique_ptr<const MCInstrInfo> MII(T.createMCInstrInfo());
801   return new X86GenericDisassembler(STI, Ctx, std::move(MII));
802 }
803 
804 extern "C" void LLVMInitializeX86Disassembler() {
805   // Register the disassembler.
806   TargetRegistry::RegisterMCDisassembler(getTheX86_32Target(),
807                                          createX86Disassembler);
808   TargetRegistry::RegisterMCDisassembler(getTheX86_64Target(),
809                                          createX86Disassembler);
810 }
811