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/EDInstInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDisassembler.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MemoryObject.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
31 #define GET_REGINFO_ENUM
32 #include "X86GenRegisterInfo.inc"
33 #define GET_INSTRINFO_ENUM
34 #include "X86GenInstrInfo.inc"
35 #include "X86GenEDInfo.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 DisassemblerMode mode,
79 const MCInstrInfo *MII)
80 : MCDisassembler(STI), MII(MII), fMode(mode) {}
82 X86GenericDisassembler::~X86GenericDisassembler() {
86 const EDInstInfo *X86GenericDisassembler::getEDInfo() const {
90 /// regionReader - a callback function that wraps the readByte method from
93 /// @param arg - The generic callback parameter. In this case, this should
94 /// be a pointer to a MemoryObject.
95 /// @param byte - A pointer to the byte to be read.
96 /// @param address - The address to be read.
97 static int regionReader(const void* arg, uint8_t* byte, uint64_t address) {
98 const MemoryObject* region = static_cast<const MemoryObject*>(arg);
99 return region->readByte(address, byte);
102 /// logger - a callback function that wraps the operator<< method from
105 /// @param arg - The generic callback parameter. This should be a pointe
106 /// to a raw_ostream.
107 /// @param log - A string to be logged. logger() adds a newline.
108 static void logger(void* arg, const char* log) {
112 raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
113 vStream << log << "\n";
117 // Public interface for the disassembler
120 MCDisassembler::DecodeStatus
121 X86GenericDisassembler::getInstruction(MCInst &instr,
123 const MemoryObject ®ion,
125 raw_ostream &vStream,
126 raw_ostream &cStream) const {
127 CommentStream = &cStream;
129 InternalInstruction internalInstr;
131 dlog_t loggerFn = logger;
132 if (&vStream == &nulls())
133 loggerFn = 0; // Disable logging completely if it's going to nulls().
135 int ret = decodeInstruction(&internalInstr,
137 (const void*)®ion,
145 size = internalInstr.readerCursor - address;
149 size = internalInstr.length;
150 return (!translateInstruction(instr, internalInstr, this)) ?
156 // Private code that translates from struct InternalInstructions to MCInsts.
159 /// translateRegister - Translates an internal register to the appropriate LLVM
160 /// register, and appends it as an operand to an MCInst.
162 /// @param mcInst - The MCInst to append to.
163 /// @param reg - The Reg to append.
164 static void translateRegister(MCInst &mcInst, Reg reg) {
165 #define ENTRY(x) X86::x,
166 uint8_t llvmRegnums[] = {
172 uint8_t llvmRegnum = llvmRegnums[reg];
173 mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
176 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
177 /// immediate Value in the MCInst.
179 /// @param Value - The immediate Value, has had any PC adjustment made by
181 /// @param isBranch - If the instruction is a branch instruction
182 /// @param Address - The starting address of the instruction
183 /// @param Offset - The byte offset to this immediate in the instruction
184 /// @param Width - The byte width of this immediate in the instruction
186 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
187 /// called then that function is called to get any symbolic information for the
188 /// immediate in the instruction using the Address, Offset and Width. If that
189 /// returns non-zero then the symbolic information it returns is used to create
190 /// an MCExpr and that is added as an operand to the MCInst. If getOpInfo()
191 /// returns zero and isBranch is true then a symbol look up for immediate Value
192 /// is done and if a symbol is found an MCExpr is created with that, else
193 /// an MCExpr with the immediate Value is created. This function returns true
194 /// if it adds an operand to the MCInst and false otherwise.
195 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
196 uint64_t Address, uint64_t Offset,
197 uint64_t Width, MCInst &MI,
198 const MCDisassembler *Dis) {
199 LLVMOpInfoCallback getOpInfo = Dis->getLLVMOpInfoCallback();
200 struct LLVMOpInfo1 SymbolicOp;
201 memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
202 SymbolicOp.Value = Value;
203 void *DisInfo = Dis->getDisInfoBlock();
206 !getOpInfo(DisInfo, Address, Offset, Width, 1, &SymbolicOp)) {
207 // Clear SymbolicOp.Value from above and also all other fields.
208 memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
209 LLVMSymbolLookupCallback SymbolLookUp = Dis->getLLVMSymbolLookupCallback();
212 uint64_t ReferenceType;
214 ReferenceType = LLVMDisassembler_ReferenceType_In_Branch;
216 ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
217 const char *ReferenceName;
218 const char *Name = SymbolLookUp(DisInfo, Value, &ReferenceType, Address,
221 SymbolicOp.AddSymbol.Name = Name;
222 SymbolicOp.AddSymbol.Present = true;
224 // For branches always create an MCExpr so it gets printed as hex address.
226 SymbolicOp.Value = Value;
228 if(ReferenceType == LLVMDisassembler_ReferenceType_Out_SymbolStub)
229 (*Dis->CommentStream) << "symbol stub for: " << ReferenceName;
230 if (!Name && !isBranch)
234 MCContext *Ctx = Dis->getMCContext();
235 const MCExpr *Add = NULL;
236 if (SymbolicOp.AddSymbol.Present) {
237 if (SymbolicOp.AddSymbol.Name) {
238 StringRef Name(SymbolicOp.AddSymbol.Name);
239 MCSymbol *Sym = Ctx->GetOrCreateSymbol(Name);
240 Add = MCSymbolRefExpr::Create(Sym, *Ctx);
242 Add = MCConstantExpr::Create((int)SymbolicOp.AddSymbol.Value, *Ctx);
246 const MCExpr *Sub = NULL;
247 if (SymbolicOp.SubtractSymbol.Present) {
248 if (SymbolicOp.SubtractSymbol.Name) {
249 StringRef Name(SymbolicOp.SubtractSymbol.Name);
250 MCSymbol *Sym = Ctx->GetOrCreateSymbol(Name);
251 Sub = MCSymbolRefExpr::Create(Sym, *Ctx);
253 Sub = MCConstantExpr::Create((int)SymbolicOp.SubtractSymbol.Value, *Ctx);
257 const MCExpr *Off = NULL;
258 if (SymbolicOp.Value != 0)
259 Off = MCConstantExpr::Create(SymbolicOp.Value, *Ctx);
265 LHS = MCBinaryExpr::CreateSub(Add, Sub, *Ctx);
267 LHS = MCUnaryExpr::CreateMinus(Sub, *Ctx);
269 Expr = MCBinaryExpr::CreateAdd(LHS, Off, *Ctx);
274 Expr = MCBinaryExpr::CreateAdd(Add, Off, *Ctx);
281 Expr = MCConstantExpr::Create(0, *Ctx);
284 MI.addOperand(MCOperand::CreateExpr(Expr));
289 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
290 /// referenced by a load instruction with the base register that is the rip.
291 /// These can often be addresses in a literal pool. The Address of the
292 /// instruction and its immediate Value are used to determine the address
293 /// being referenced in the literal pool entry. The SymbolLookUp call back will
294 /// return a pointer to a literal 'C' string if the referenced address is an
295 /// address into a section with 'C' string literals.
296 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
297 const void *Decoder) {
298 const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
299 LLVMSymbolLookupCallback SymbolLookUp = Dis->getLLVMSymbolLookupCallback();
301 void *DisInfo = Dis->getDisInfoBlock();
302 uint64_t ReferenceType = LLVMDisassembler_ReferenceType_In_PCrel_Load;
303 const char *ReferenceName;
304 (void)SymbolLookUp(DisInfo, Value, &ReferenceType, Address, &ReferenceName);
305 if(ReferenceType == LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr)
306 (*Dis->CommentStream) << "literal pool for: " << ReferenceName;
310 /// translateImmediate - Appends an immediate operand to an MCInst.
312 /// @param mcInst - The MCInst to append to.
313 /// @param immediate - The immediate value to append.
314 /// @param operand - The operand, as stored in the descriptor table.
315 /// @param insn - The internal instruction.
316 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
317 const OperandSpecifier &operand,
318 InternalInstruction &insn,
319 const MCDisassembler *Dis) {
320 // Sign-extend the immediate if necessary.
322 OperandType type = (OperandType)operand.type;
324 bool isBranch = false;
326 if (type == TYPE_RELv) {
328 pcrel = insn.startLocation +
329 insn.immediateOffset + insn.immediateSize;
330 switch (insn.displacementSize) {
347 // By default sign-extend all X86 immediates based on their encoding.
348 else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
349 type == TYPE_IMM64) {
350 uint32_t Opcode = mcInst.getOpcode();
351 switch (operand.encoding) {
355 // Special case those X86 instructions that use the imm8 as a set of
356 // bits, bit count, etc. and are not sign-extend.
357 if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
358 Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
359 Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
360 Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
361 Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
362 Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
363 Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
364 Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
365 Opcode != X86::VINSERTPSrr)
384 mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
387 mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
391 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
392 // fall through to sign extend the immediate if needed.
395 immediate |= ~(0xffull);
398 if(immediate & 0x8000)
399 immediate |= ~(0xffffull);
404 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
405 // fall through to sign extend the immediate if needed.
407 if(immediate & 0x80000000)
408 immediate |= ~(0xffffffffull);
412 // operand is 64 bits wide. Do nothing.
416 if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
417 insn.immediateOffset, insn.immediateSize,
419 mcInst.addOperand(MCOperand::CreateImm(immediate));
422 /// translateRMRegister - Translates a register stored in the R/M field of the
423 /// ModR/M byte to its LLVM equivalent and appends it to an MCInst.
424 /// @param mcInst - The MCInst to append to.
425 /// @param insn - The internal instruction to extract the R/M field
427 /// @return - 0 on success; -1 otherwise
428 static bool translateRMRegister(MCInst &mcInst,
429 InternalInstruction &insn) {
430 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
431 debug("A R/M register operand may not have a SIB byte");
435 switch (insn.eaBase) {
437 debug("Unexpected EA base register");
440 debug("EA_BASE_NONE for ModR/M base");
442 #define ENTRY(x) case EA_BASE_##x:
445 debug("A R/M register operand may not have a base; "
446 "the operand must be a register.");
450 mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
458 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
459 /// fields of an internal instruction (and possibly its SIB byte) to a memory
460 /// operand in LLVM's format, and appends it to an MCInst.
462 /// @param mcInst - The MCInst to append to.
463 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
465 /// @return - 0 on success; nonzero otherwise
466 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
467 const MCDisassembler *Dis) {
468 // Addresses in an MCInst are represented as five operands:
469 // 1. basereg (register) The R/M base, or (if there is a SIB) the
471 // 2. scaleamount (immediate) 1, or (if there is a SIB) the specified
473 // 3. indexreg (register) x86_registerNONE, or (if there is a SIB)
474 // the index (which is multiplied by the
476 // 4. displacement (immediate) 0, or the displacement if there is one
477 // 5. segmentreg (register) x86_registerNONE for now, but could be set
478 // if we have segment overrides
481 MCOperand scaleAmount;
483 MCOperand displacement;
484 MCOperand segmentReg;
487 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
488 if (insn.sibBase != SIB_BASE_NONE) {
489 switch (insn.sibBase) {
491 debug("Unexpected sibBase");
495 baseReg = MCOperand::CreateReg(X86::x); break;
500 baseReg = MCOperand::CreateReg(0);
503 // Check whether we are handling VSIB addressing mode for GATHER.
504 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
505 // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
506 // I don't see a way to get the correct IndexReg in readSIB:
507 // We can tell whether it is VSIB or SIB after instruction ID is decoded,
508 // but instruction ID may not be decoded yet when calling readSIB.
509 uint32_t Opcode = mcInst.getOpcode();
510 bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
511 Opcode == X86::VGATHERDPDYrm ||
512 Opcode == X86::VGATHERQPDrm ||
513 Opcode == X86::VGATHERDPSrm ||
514 Opcode == X86::VGATHERQPSrm ||
515 Opcode == X86::VPGATHERDQrm ||
516 Opcode == X86::VPGATHERDQYrm ||
517 Opcode == X86::VPGATHERQQrm ||
518 Opcode == X86::VPGATHERDDrm ||
519 Opcode == X86::VPGATHERQDrm);
520 bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
521 Opcode == X86::VGATHERDPSYrm ||
522 Opcode == X86::VGATHERQPSYrm ||
523 Opcode == X86::VPGATHERQQYrm ||
524 Opcode == X86::VPGATHERDDYrm ||
525 Opcode == X86::VPGATHERQDYrm);
526 if (IndexIs128 || IndexIs256) {
527 unsigned IndexOffset = insn.sibIndex -
528 (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
529 SIBIndex IndexBase = IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
530 insn.sibIndex = (SIBIndex)(IndexBase +
531 (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
534 if (insn.sibIndex != SIB_INDEX_NONE) {
535 switch (insn.sibIndex) {
537 debug("Unexpected sibIndex");
540 case SIB_INDEX_##x: \
541 indexReg = MCOperand::CreateReg(X86::x); break;
549 indexReg = MCOperand::CreateReg(0);
552 scaleAmount = MCOperand::CreateImm(insn.sibScale);
554 switch (insn.eaBase) {
556 if (insn.eaDisplacement == EA_DISP_NONE) {
557 debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
560 if (insn.mode == MODE_64BIT){
561 pcrel = insn.startLocation +
562 insn.displacementOffset + insn.displacementSize;
563 tryAddingPcLoadReferenceComment(insn.startLocation +
564 insn.displacementOffset,
565 insn.displacement + pcrel, Dis);
566 baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
569 baseReg = MCOperand::CreateReg(0);
571 indexReg = MCOperand::CreateReg(0);
574 baseReg = MCOperand::CreateReg(X86::BX);
575 indexReg = MCOperand::CreateReg(X86::SI);
578 baseReg = MCOperand::CreateReg(X86::BX);
579 indexReg = MCOperand::CreateReg(X86::DI);
582 baseReg = MCOperand::CreateReg(X86::BP);
583 indexReg = MCOperand::CreateReg(X86::SI);
586 baseReg = MCOperand::CreateReg(X86::BP);
587 indexReg = MCOperand::CreateReg(X86::DI);
590 indexReg = MCOperand::CreateReg(0);
591 switch (insn.eaBase) {
593 debug("Unexpected eaBase");
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.
601 baseReg = MCOperand::CreateReg(X86::x); break;
604 #define ENTRY(x) case EA_REG_##x:
607 debug("A R/M memory operand may not be a register; "
608 "the base field must be a base.");
613 scaleAmount = MCOperand::CreateImm(1);
616 displacement = MCOperand::CreateImm(insn.displacement);
618 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
619 0, // SEG_OVERRIDE_NONE
628 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
630 mcInst.addOperand(baseReg);
631 mcInst.addOperand(scaleAmount);
632 mcInst.addOperand(indexReg);
633 if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
634 insn.startLocation, insn.displacementOffset,
635 insn.displacementSize, mcInst, Dis))
636 mcInst.addOperand(displacement);
637 mcInst.addOperand(segmentReg);
641 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
642 /// byte of an instruction to LLVM form, and appends it to an MCInst.
644 /// @param mcInst - The MCInst to append to.
645 /// @param operand - The operand, as stored in the descriptor table.
646 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
648 /// @return - 0 on success; nonzero otherwise
649 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
650 InternalInstruction &insn, const MCDisassembler *Dis) {
651 switch (operand.type) {
653 debug("Unexpected type for a R/M operand");
669 case TYPE_CONTROLREG:
670 return translateRMRegister(mcInst, insn);
690 return translateRMMemory(mcInst, insn, Dis);
694 /// translateFPRegister - Translates a stack position on the FPU stack to its
695 /// LLVM form, and appends it to an MCInst.
697 /// @param mcInst - The MCInst to append to.
698 /// @param stackPos - The stack position to translate.
699 /// @return - 0 on success; nonzero otherwise.
700 static bool translateFPRegister(MCInst &mcInst,
703 debug("Invalid FP stack position");
707 mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
712 /// translateOperand - Translates an operand stored in an internal instruction
713 /// to LLVM's format and appends it to an MCInst.
715 /// @param mcInst - The MCInst to append to.
716 /// @param operand - The operand, as stored in the descriptor table.
717 /// @param insn - The internal instruction.
718 /// @return - false on success; true otherwise.
719 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
720 InternalInstruction &insn,
721 const MCDisassembler *Dis) {
722 switch (operand.encoding) {
724 debug("Unhandled operand encoding during translation");
727 translateRegister(mcInst, insn.reg);
730 return translateRM(mcInst, operand, insn, Dis);
737 debug("Translation of code offsets isn't supported.");
745 translateImmediate(mcInst,
746 insn.immediates[insn.numImmediatesTranslated++],
755 translateRegister(mcInst, insn.opcodeRegister);
758 return translateFPRegister(mcInst, insn.opcodeModifier);
760 translateRegister(mcInst, insn.opcodeRegister);
763 translateRegister(mcInst, insn.vvvv);
766 return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
771 /// translateInstruction - Translates an internal instruction and all its
772 /// operands to an MCInst.
774 /// @param mcInst - The MCInst to populate with the instruction's data.
775 /// @param insn - The internal instruction.
776 /// @return - false on success; true otherwise.
777 static bool translateInstruction(MCInst &mcInst,
778 InternalInstruction &insn,
779 const MCDisassembler *Dis) {
781 debug("Instruction has no specification");
785 mcInst.setOpcode(insn.instructionID);
789 insn.numImmediatesTranslated = 0;
791 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
792 if (insn.operands[index].encoding != ENCODING_NONE) {
793 if (translateOperand(mcInst, insn.operands[index], insn, Dis)) {
802 static MCDisassembler *createX86_32Disassembler(const Target &T,
803 const MCSubtargetInfo &STI) {
804 return new X86Disassembler::X86GenericDisassembler(STI, MODE_32BIT,
805 T.createMCInstrInfo());
808 static MCDisassembler *createX86_64Disassembler(const Target &T,
809 const MCSubtargetInfo &STI) {
810 return new X86Disassembler::X86GenericDisassembler(STI, MODE_64BIT,
811 T.createMCInstrInfo());
814 extern "C" void LLVMInitializeX86Disassembler() {
815 // Register the disassembler.
816 TargetRegistry::RegisterMCDisassembler(TheX86_32Target,
817 createX86_32Disassembler);
818 TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
819 createX86_64Disassembler);