1 //===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is part of the X86 Disassembler.
11 // It contains code to translate the data produced by the decoder into
13 // Documentation for the disassembler can be found in X86Disassembler.h.
15 //===----------------------------------------------------------------------===//
17 #include "X86Disassembler.h"
18 #include "X86DisassemblerDecoder.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDisassembler.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/MemoryObject.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
30 #define GET_REGINFO_ENUM
31 #include "X86GenRegisterInfo.inc"
32 #define GET_INSTRINFO_ENUM
33 #include "X86GenInstrInfo.inc"
34 #define GET_SUBTARGETINFO_ENUM
35 #include "X86GenSubtargetInfo.inc"
38 using namespace llvm::X86Disassembler;
40 void x86DisassemblerDebug(const char *file,
43 dbgs() << file << ":" << line << ": " << s;
46 const char *x86DisassemblerGetInstrName(unsigned Opcode, const void *mii) {
47 const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
48 return MII->getName(Opcode);
51 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
55 // Fill-ins to make the compiler happy. These constants are never actually
56 // assigned; they are just filler to make an automatically-generated switch
69 extern Target TheX86_32Target, TheX86_64Target;
73 static bool translateInstruction(MCInst &target,
74 InternalInstruction &source,
75 const MCDisassembler *Dis);
77 X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
78 const MCInstrInfo *MII)
79 : MCDisassembler(STI), MII(MII) {
80 switch (STI.getFeatureBits() &
81 (X86::Mode16Bit | X86::Mode32Bit | X86::Mode64Bit)) {
92 llvm_unreachable("Invalid CPU mode");
96 X86GenericDisassembler::~X86GenericDisassembler() {
100 /// regionReader - a callback function that wraps the readByte method from
103 /// @param arg - The generic callback parameter. In this case, this should
104 /// be a pointer to a MemoryObject.
105 /// @param byte - A pointer to the byte to be read.
106 /// @param address - The address to be read.
107 static int regionReader(const void* arg, uint8_t* byte, uint64_t address) {
108 const MemoryObject* region = static_cast<const MemoryObject*>(arg);
109 return region->readByte(address, byte);
112 /// logger - a callback function that wraps the operator<< method from
115 /// @param arg - The generic callback parameter. This should be a pointe
116 /// to a raw_ostream.
117 /// @param log - A string to be logged. logger() adds a newline.
118 static void logger(void* arg, const char* log) {
122 raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
123 vStream << log << "\n";
127 // Public interface for the disassembler
130 MCDisassembler::DecodeStatus
131 X86GenericDisassembler::getInstruction(MCInst &instr,
133 const MemoryObject ®ion,
135 raw_ostream &vStream,
136 raw_ostream &cStream) const {
137 CommentStream = &cStream;
139 InternalInstruction internalInstr;
141 dlog_t loggerFn = logger;
142 if (&vStream == &nulls())
143 loggerFn = 0; // Disable logging completely if it's going to nulls().
145 int ret = decodeInstruction(&internalInstr,
147 (const void*)®ion,
155 size = internalInstr.readerCursor - address;
159 size = internalInstr.length;
160 return (!translateInstruction(instr, internalInstr, this)) ?
166 // Private code that translates from struct InternalInstructions to MCInsts.
169 /// translateRegister - Translates an internal register to the appropriate LLVM
170 /// register, and appends it as an operand to an MCInst.
172 /// @param mcInst - The MCInst to append to.
173 /// @param reg - The Reg to append.
174 static void translateRegister(MCInst &mcInst, Reg reg) {
175 #define ENTRY(x) X86::x,
176 uint8_t llvmRegnums[] = {
182 uint8_t llvmRegnum = llvmRegnums[reg];
183 mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
186 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
187 /// immediate Value in the MCInst.
189 /// @param Value - The immediate Value, has had any PC adjustment made by
191 /// @param isBranch - If the instruction is a branch instruction
192 /// @param Address - The starting address of the instruction
193 /// @param Offset - The byte offset to this immediate in the instruction
194 /// @param Width - The byte width of this immediate in the instruction
196 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
197 /// called then that function is called to get any symbolic information for the
198 /// immediate in the instruction using the Address, Offset and Width. If that
199 /// returns non-zero then the symbolic information it returns is used to create
200 /// an MCExpr and that is added as an operand to the MCInst. If getOpInfo()
201 /// returns zero and isBranch is true then a symbol look up for immediate Value
202 /// is done and if a symbol is found an MCExpr is created with that, else
203 /// an MCExpr with the immediate Value is created. This function returns true
204 /// if it adds an operand to the MCInst and false otherwise.
205 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
206 uint64_t Address, uint64_t Offset,
207 uint64_t Width, MCInst &MI,
208 const MCDisassembler *Dis) {
209 return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
213 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
214 /// referenced by a load instruction with the base register that is the rip.
215 /// These can often be addresses in a literal pool. The Address of the
216 /// instruction and its immediate Value are used to determine the address
217 /// being referenced in the literal pool entry. The SymbolLookUp call back will
218 /// return a pointer to a literal 'C' string if the referenced address is an
219 /// address into a section with 'C' string literals.
220 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
221 const void *Decoder) {
222 const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
223 Dis->tryAddingPcLoadReferenceComment(Value, Address);
226 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
227 0, // SEG_OVERRIDE_NONE
236 /// translateSrcIndex - Appends a source index operand to an MCInst.
238 /// @param mcInst - The MCInst to append to.
239 /// @param insn - The internal instruction.
240 static bool translateSrcIndex(MCInst &mcInst, InternalInstruction &insn) {
243 if (insn.mode == MODE_64BIT)
244 baseRegNo = insn.prefixPresent[0x67] ? X86::ESI : X86::RSI;
245 else if (insn.mode == MODE_32BIT)
246 baseRegNo = insn.prefixPresent[0x67] ? X86::SI : X86::ESI;
248 assert(insn.mode == MODE_16BIT);
249 baseRegNo = insn.prefixPresent[0x67] ? X86::ESI : X86::SI;
251 MCOperand baseReg = MCOperand::CreateReg(baseRegNo);
252 mcInst.addOperand(baseReg);
254 MCOperand segmentReg;
255 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
256 mcInst.addOperand(segmentReg);
260 /// translateDstIndex - Appends a destination index operand to an MCInst.
262 /// @param mcInst - The MCInst to append to.
263 /// @param operand - The operand, as stored in the descriptor table.
264 /// @param insn - The internal instruction.
266 static bool translateDstIndex(MCInst &mcInst, InternalInstruction &insn) {
269 if (insn.mode == MODE_64BIT)
270 baseRegNo = insn.prefixPresent[0x67] ? X86::EDI : X86::RDI;
271 else if (insn.mode == MODE_32BIT)
272 baseRegNo = insn.prefixPresent[0x67] ? X86::DI : X86::EDI;
274 assert(insn.mode == MODE_16BIT);
275 baseRegNo = insn.prefixPresent[0x67] ? X86::EDI : X86::DI;
277 MCOperand baseReg = MCOperand::CreateReg(baseRegNo);
278 mcInst.addOperand(baseReg);
282 /// translateImmediate - Appends an immediate operand to an MCInst.
284 /// @param mcInst - The MCInst to append to.
285 /// @param immediate - The immediate value to append.
286 /// @param operand - The operand, as stored in the descriptor table.
287 /// @param insn - The internal instruction.
288 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
289 const OperandSpecifier &operand,
290 InternalInstruction &insn,
291 const MCDisassembler *Dis) {
292 // Sign-extend the immediate if necessary.
294 OperandType type = (OperandType)operand.type;
296 bool isBranch = false;
298 if (type == TYPE_RELv) {
300 pcrel = insn.startLocation +
301 insn.immediateOffset + insn.immediateSize;
302 switch (insn.displacementSize) {
307 immediate |= ~(0xffull);
310 if(immediate & 0x8000)
311 immediate |= ~(0xffffull);
314 if(immediate & 0x80000000)
315 immediate |= ~(0xffffffffull);
321 // By default sign-extend all X86 immediates based on their encoding.
322 else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
323 type == TYPE_IMM64) {
324 uint32_t Opcode = mcInst.getOpcode();
325 switch (operand.encoding) {
329 // Special case those X86 instructions that use the imm8 as a set of
330 // bits, bit count, etc. and are not sign-extend.
331 if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
332 Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
333 Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
334 Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
335 Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
336 Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
337 Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
338 Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
339 Opcode != X86::VINSERTPSrr)
341 immediate |= ~(0xffull);
344 if(immediate & 0x8000)
345 immediate |= ~(0xffffull);
348 if(immediate & 0x80000000)
349 immediate |= ~(0xffffffffull);
360 mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
363 mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
366 mcInst.addOperand(MCOperand::CreateReg(X86::ZMM0 + (immediate >> 4)));
370 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
372 immediate |= ~(0xffull);
377 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
378 if(immediate & 0x80000000)
379 immediate |= ~(0xffffffffull);
382 // operand is 64 bits wide. Do nothing.
386 if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
387 insn.immediateOffset, insn.immediateSize,
389 mcInst.addOperand(MCOperand::CreateImm(immediate));
391 if (type == TYPE_MOFFS8 || type == TYPE_MOFFS16 ||
392 type == TYPE_MOFFS32 || type == TYPE_MOFFS64) {
393 MCOperand segmentReg;
394 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
395 mcInst.addOperand(segmentReg);
399 /// translateRMRegister - Translates a register stored in the R/M field of the
400 /// ModR/M byte to its LLVM equivalent and appends it to an MCInst.
401 /// @param mcInst - The MCInst to append to.
402 /// @param insn - The internal instruction to extract the R/M field
404 /// @return - 0 on success; -1 otherwise
405 static bool translateRMRegister(MCInst &mcInst,
406 InternalInstruction &insn) {
407 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
408 debug("A R/M register operand may not have a SIB byte");
412 switch (insn.eaBase) {
414 debug("Unexpected EA base register");
417 debug("EA_BASE_NONE for ModR/M base");
419 #define ENTRY(x) case EA_BASE_##x:
422 debug("A R/M register operand may not have a base; "
423 "the operand must be a register.");
427 mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
435 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
436 /// fields of an internal instruction (and possibly its SIB byte) to a memory
437 /// operand in LLVM's format, and appends it to an MCInst.
439 /// @param mcInst - The MCInst to append to.
440 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
442 /// @return - 0 on success; nonzero otherwise
443 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
444 const MCDisassembler *Dis) {
445 // Addresses in an MCInst are represented as five operands:
446 // 1. basereg (register) The R/M base, or (if there is a SIB) the
448 // 2. scaleamount (immediate) 1, or (if there is a SIB) the specified
450 // 3. indexreg (register) x86_registerNONE, or (if there is a SIB)
451 // the index (which is multiplied by the
453 // 4. displacement (immediate) 0, or the displacement if there is one
454 // 5. segmentreg (register) x86_registerNONE for now, but could be set
455 // if we have segment overrides
458 MCOperand scaleAmount;
460 MCOperand displacement;
461 MCOperand segmentReg;
464 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
465 if (insn.sibBase != SIB_BASE_NONE) {
466 switch (insn.sibBase) {
468 debug("Unexpected sibBase");
472 baseReg = MCOperand::CreateReg(X86::x); break;
477 baseReg = MCOperand::CreateReg(0);
480 // Check whether we are handling VSIB addressing mode for GATHER.
481 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
482 // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
483 // I don't see a way to get the correct IndexReg in readSIB:
484 // We can tell whether it is VSIB or SIB after instruction ID is decoded,
485 // but instruction ID may not be decoded yet when calling readSIB.
486 uint32_t Opcode = mcInst.getOpcode();
487 bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
488 Opcode == X86::VGATHERDPDYrm ||
489 Opcode == X86::VGATHERQPDrm ||
490 Opcode == X86::VGATHERDPSrm ||
491 Opcode == X86::VGATHERQPSrm ||
492 Opcode == X86::VPGATHERDQrm ||
493 Opcode == X86::VPGATHERDQYrm ||
494 Opcode == X86::VPGATHERQQrm ||
495 Opcode == X86::VPGATHERDDrm ||
496 Opcode == X86::VPGATHERQDrm);
497 bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
498 Opcode == X86::VGATHERDPSYrm ||
499 Opcode == X86::VGATHERQPSYrm ||
500 Opcode == X86::VGATHERDPDZrm ||
501 Opcode == X86::VPGATHERDQZrm ||
502 Opcode == X86::VPGATHERQQYrm ||
503 Opcode == X86::VPGATHERDDYrm ||
504 Opcode == X86::VPGATHERQDYrm);
505 bool IndexIs512 = (Opcode == X86::VGATHERQPDZrm ||
506 Opcode == X86::VGATHERDPSZrm ||
507 Opcode == X86::VGATHERQPSZrm ||
508 Opcode == X86::VPGATHERQQZrm ||
509 Opcode == X86::VPGATHERDDZrm ||
510 Opcode == X86::VPGATHERQDZrm);
511 if (IndexIs128 || IndexIs256 || IndexIs512) {
512 unsigned IndexOffset = insn.sibIndex -
513 (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
514 SIBIndex IndexBase = IndexIs512 ? SIB_INDEX_ZMM0 :
515 IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
516 insn.sibIndex = (SIBIndex)(IndexBase +
517 (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
520 if (insn.sibIndex != SIB_INDEX_NONE) {
521 switch (insn.sibIndex) {
523 debug("Unexpected sibIndex");
526 case SIB_INDEX_##x: \
527 indexReg = MCOperand::CreateReg(X86::x); break;
536 indexReg = MCOperand::CreateReg(0);
539 scaleAmount = MCOperand::CreateImm(insn.sibScale);
541 switch (insn.eaBase) {
543 if (insn.eaDisplacement == EA_DISP_NONE) {
544 debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
547 if (insn.mode == MODE_64BIT){
548 pcrel = insn.startLocation +
549 insn.displacementOffset + insn.displacementSize;
550 tryAddingPcLoadReferenceComment(insn.startLocation +
551 insn.displacementOffset,
552 insn.displacement + pcrel, Dis);
553 baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
556 baseReg = MCOperand::CreateReg(0);
558 indexReg = MCOperand::CreateReg(0);
561 baseReg = MCOperand::CreateReg(X86::BX);
562 indexReg = MCOperand::CreateReg(X86::SI);
565 baseReg = MCOperand::CreateReg(X86::BX);
566 indexReg = MCOperand::CreateReg(X86::DI);
569 baseReg = MCOperand::CreateReg(X86::BP);
570 indexReg = MCOperand::CreateReg(X86::SI);
573 baseReg = MCOperand::CreateReg(X86::BP);
574 indexReg = MCOperand::CreateReg(X86::DI);
577 indexReg = MCOperand::CreateReg(0);
578 switch (insn.eaBase) {
580 debug("Unexpected eaBase");
582 // Here, we will use the fill-ins defined above. However,
583 // BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
584 // sib and sib64 were handled in the top-level if, so they're only
585 // placeholders to keep the compiler happy.
588 baseReg = MCOperand::CreateReg(X86::x); break;
591 #define ENTRY(x) case EA_REG_##x:
594 debug("A R/M memory operand may not be a register; "
595 "the base field must be a base.");
600 scaleAmount = MCOperand::CreateImm(1);
603 displacement = MCOperand::CreateImm(insn.displacement);
605 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
607 mcInst.addOperand(baseReg);
608 mcInst.addOperand(scaleAmount);
609 mcInst.addOperand(indexReg);
610 if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
611 insn.startLocation, insn.displacementOffset,
612 insn.displacementSize, mcInst, Dis))
613 mcInst.addOperand(displacement);
614 mcInst.addOperand(segmentReg);
618 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
619 /// byte of an instruction to LLVM form, and appends it to an MCInst.
621 /// @param mcInst - The MCInst to append to.
622 /// @param operand - The operand, as stored in the descriptor table.
623 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
625 /// @return - 0 on success; nonzero otherwise
626 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
627 InternalInstruction &insn, const MCDisassembler *Dis) {
628 switch (operand.type) {
630 debug("Unexpected type for a R/M operand");
650 case TYPE_CONTROLREG:
651 return translateRMRegister(mcInst, insn);
671 return translateRMMemory(mcInst, insn, Dis);
675 /// translateFPRegister - Translates a stack position on the FPU stack to its
676 /// LLVM form, and appends it to an MCInst.
678 /// @param mcInst - The MCInst to append to.
679 /// @param stackPos - The stack position to translate.
680 static void translateFPRegister(MCInst &mcInst,
682 mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
685 /// translateMaskRegister - Translates a 3-bit mask register number to
686 /// LLVM form, and appends it to an MCInst.
688 /// @param mcInst - The MCInst to append to.
689 /// @param maskRegNum - Number of mask register from 0 to 7.
690 /// @return - false on success; true otherwise.
691 static bool translateMaskRegister(MCInst &mcInst,
692 uint8_t maskRegNum) {
693 if (maskRegNum >= 8) {
694 debug("Invalid mask register number");
698 mcInst.addOperand(MCOperand::CreateReg(X86::K0 + maskRegNum));
702 /// translateOperand - Translates an operand stored in an internal instruction
703 /// to LLVM's format and appends it to an MCInst.
705 /// @param mcInst - The MCInst to append to.
706 /// @param operand - The operand, as stored in the descriptor table.
707 /// @param insn - The internal instruction.
708 /// @return - false on success; true otherwise.
709 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
710 InternalInstruction &insn,
711 const MCDisassembler *Dis) {
712 switch (operand.encoding) {
714 debug("Unhandled operand encoding during translation");
717 translateRegister(mcInst, insn.reg);
719 case ENCODING_WRITEMASK:
720 return translateMaskRegister(mcInst, insn.writemask);
722 return translateRM(mcInst, operand, insn, Dis);
729 debug("Translation of code offsets isn't supported.");
737 translateImmediate(mcInst,
738 insn.immediates[insn.numImmediatesTranslated++],
744 return translateSrcIndex(mcInst, insn);
746 return translateDstIndex(mcInst, insn);
752 translateRegister(mcInst, insn.opcodeRegister);
755 translateFPRegister(mcInst, insn.modRM & 7);
758 translateRegister(mcInst, insn.vvvv);
761 return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
766 /// translateInstruction - Translates an internal instruction and all its
767 /// operands to an MCInst.
769 /// @param mcInst - The MCInst to populate with the instruction's data.
770 /// @param insn - The internal instruction.
771 /// @return - false on success; true otherwise.
772 static bool translateInstruction(MCInst &mcInst,
773 InternalInstruction &insn,
774 const MCDisassembler *Dis) {
776 debug("Instruction has no specification");
780 mcInst.setOpcode(insn.instructionID);
781 // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
782 // prefix bytes should be disassembled as xrelease and xacquire then set the
783 // opcode to those instead of the rep and repne opcodes.
784 if (insn.xAcquireRelease) {
785 if(mcInst.getOpcode() == X86::REP_PREFIX)
786 mcInst.setOpcode(X86::XRELEASE_PREFIX);
787 else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
788 mcInst.setOpcode(X86::XACQUIRE_PREFIX);
793 insn.numImmediatesTranslated = 0;
795 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
796 if (insn.operands[index].encoding != ENCODING_NONE) {
797 if (translateOperand(mcInst, insn.operands[index], insn, Dis)) {
806 static MCDisassembler *createX86Disassembler(const Target &T,
807 const MCSubtargetInfo &STI) {
808 return new X86Disassembler::X86GenericDisassembler(STI,
809 T.createMCInstrInfo());
812 extern "C" void LLVMInitializeX86Disassembler() {
813 // Register the disassembler.
814 TargetRegistry::RegisterMCDisassembler(TheX86_32Target,
815 createX86Disassembler);
816 TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
817 createX86Disassembler);