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