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"
36 using namespace llvm::X86Disassembler;
38 void x86DisassemblerDebug(const char *file,
41 dbgs() << file << ":" << line << ": " << s;
44 const char *x86DisassemblerGetInstrName(unsigned Opcode, const void *mii) {
45 const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
46 return MII->getName(Opcode);
49 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
53 // Fill-ins to make the compiler happy. These constants are never actually
54 // assigned; they are just filler to make an automatically-generated switch
67 extern Target TheX86_32Target, TheX86_64Target;
71 static bool translateInstruction(MCInst &target,
72 InternalInstruction &source,
73 const MCDisassembler *Dis);
75 X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
76 DisassemblerMode mode,
77 const MCInstrInfo *MII)
78 : MCDisassembler(STI), MII(MII), fMode(mode) {}
80 X86GenericDisassembler::~X86GenericDisassembler() {
84 /// regionReader - a callback function that wraps the readByte method from
87 /// @param arg - The generic callback parameter. In this case, this should
88 /// be a pointer to a MemoryObject.
89 /// @param byte - A pointer to the byte to be read.
90 /// @param address - The address to be read.
91 static int regionReader(const void* arg, uint8_t* byte, uint64_t address) {
92 const MemoryObject* region = static_cast<const MemoryObject*>(arg);
93 return region->readByte(address, byte);
96 /// logger - a callback function that wraps the operator<< method from
99 /// @param arg - The generic callback parameter. This should be a pointe
100 /// to a raw_ostream.
101 /// @param log - A string to be logged. logger() adds a newline.
102 static void logger(void* arg, const char* log) {
106 raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
107 vStream << log << "\n";
111 // Public interface for the disassembler
114 MCDisassembler::DecodeStatus
115 X86GenericDisassembler::getInstruction(MCInst &instr,
117 const MemoryObject ®ion,
119 raw_ostream &vStream,
120 raw_ostream &cStream) const {
121 CommentStream = &cStream;
123 InternalInstruction internalInstr;
125 dlog_t loggerFn = logger;
126 if (&vStream == &nulls())
127 loggerFn = 0; // Disable logging completely if it's going to nulls().
129 int ret = decodeInstruction(&internalInstr,
131 (const void*)®ion,
139 size = internalInstr.readerCursor - address;
143 size = internalInstr.length;
144 return (!translateInstruction(instr, internalInstr, this)) ?
150 // Private code that translates from struct InternalInstructions to MCInsts.
153 /// translateRegister - Translates an internal register to the appropriate LLVM
154 /// register, and appends it as an operand to an MCInst.
156 /// @param mcInst - The MCInst to append to.
157 /// @param reg - The Reg to append.
158 static void translateRegister(MCInst &mcInst, Reg reg) {
159 #define ENTRY(x) X86::x,
160 uint8_t llvmRegnums[] = {
166 uint8_t llvmRegnum = llvmRegnums[reg];
167 mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
170 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
171 /// immediate Value in the MCInst.
173 /// @param Value - The immediate Value, has had any PC adjustment made by
175 /// @param isBranch - If the instruction is a branch instruction
176 /// @param Address - The starting address of the instruction
177 /// @param Offset - The byte offset to this immediate in the instruction
178 /// @param Width - The byte width of this immediate in the instruction
180 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
181 /// called then that function is called to get any symbolic information for the
182 /// immediate in the instruction using the Address, Offset and Width. If that
183 /// returns non-zero then the symbolic information it returns is used to create
184 /// an MCExpr and that is added as an operand to the MCInst. If getOpInfo()
185 /// returns zero and isBranch is true then a symbol look up for immediate Value
186 /// is done and if a symbol is found an MCExpr is created with that, else
187 /// an MCExpr with the immediate Value is created. This function returns true
188 /// if it adds an operand to the MCInst and false otherwise.
189 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
190 uint64_t Address, uint64_t Offset,
191 uint64_t Width, MCInst &MI,
192 const MCDisassembler *Dis) {
193 LLVMOpInfoCallback getOpInfo = Dis->getLLVMOpInfoCallback();
194 struct LLVMOpInfo1 SymbolicOp;
195 memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
196 SymbolicOp.Value = Value;
197 void *DisInfo = Dis->getDisInfoBlock();
200 !getOpInfo(DisInfo, Address, Offset, Width, 1, &SymbolicOp)) {
201 // Clear SymbolicOp.Value from above and also all other fields.
202 memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
203 LLVMSymbolLookupCallback SymbolLookUp = Dis->getLLVMSymbolLookupCallback();
206 uint64_t ReferenceType;
208 ReferenceType = LLVMDisassembler_ReferenceType_In_Branch;
210 ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
211 const char *ReferenceName;
212 const char *Name = SymbolLookUp(DisInfo, Value, &ReferenceType, Address,
215 SymbolicOp.AddSymbol.Name = Name;
216 SymbolicOp.AddSymbol.Present = true;
218 // For branches always create an MCExpr so it gets printed as hex address.
220 SymbolicOp.Value = Value;
222 if(ReferenceType == LLVMDisassembler_ReferenceType_Out_SymbolStub)
223 (*Dis->CommentStream) << "symbol stub for: " << ReferenceName;
224 if (!Name && !isBranch)
228 MCContext *Ctx = Dis->getMCContext();
229 const MCExpr *Add = NULL;
230 if (SymbolicOp.AddSymbol.Present) {
231 if (SymbolicOp.AddSymbol.Name) {
232 StringRef Name(SymbolicOp.AddSymbol.Name);
233 MCSymbol *Sym = Ctx->GetOrCreateSymbol(Name);
234 Add = MCSymbolRefExpr::Create(Sym, *Ctx);
236 Add = MCConstantExpr::Create((int)SymbolicOp.AddSymbol.Value, *Ctx);
240 const MCExpr *Sub = NULL;
241 if (SymbolicOp.SubtractSymbol.Present) {
242 if (SymbolicOp.SubtractSymbol.Name) {
243 StringRef Name(SymbolicOp.SubtractSymbol.Name);
244 MCSymbol *Sym = Ctx->GetOrCreateSymbol(Name);
245 Sub = MCSymbolRefExpr::Create(Sym, *Ctx);
247 Sub = MCConstantExpr::Create((int)SymbolicOp.SubtractSymbol.Value, *Ctx);
251 const MCExpr *Off = NULL;
252 if (SymbolicOp.Value != 0)
253 Off = MCConstantExpr::Create(SymbolicOp.Value, *Ctx);
259 LHS = MCBinaryExpr::CreateSub(Add, Sub, *Ctx);
261 LHS = MCUnaryExpr::CreateMinus(Sub, *Ctx);
263 Expr = MCBinaryExpr::CreateAdd(LHS, Off, *Ctx);
268 Expr = MCBinaryExpr::CreateAdd(Add, Off, *Ctx);
275 Expr = MCConstantExpr::Create(0, *Ctx);
278 MI.addOperand(MCOperand::CreateExpr(Expr));
283 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
284 /// referenced by a load instruction with the base register that is the rip.
285 /// These can often be addresses in a literal pool. The Address of the
286 /// instruction and its immediate Value are used to determine the address
287 /// being referenced in the literal pool entry. The SymbolLookUp call back will
288 /// return a pointer to a literal 'C' string if the referenced address is an
289 /// address into a section with 'C' string literals.
290 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
291 const void *Decoder) {
292 const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
293 LLVMSymbolLookupCallback SymbolLookUp = Dis->getLLVMSymbolLookupCallback();
295 void *DisInfo = Dis->getDisInfoBlock();
296 uint64_t ReferenceType = LLVMDisassembler_ReferenceType_In_PCrel_Load;
297 const char *ReferenceName;
298 (void)SymbolLookUp(DisInfo, Value, &ReferenceType, Address, &ReferenceName);
299 if(ReferenceType == LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr)
300 (*Dis->CommentStream) << "literal pool for: " << ReferenceName;
304 /// translateImmediate - Appends an immediate operand to an MCInst.
306 /// @param mcInst - The MCInst to append to.
307 /// @param immediate - The immediate value to append.
308 /// @param operand - The operand, as stored in the descriptor table.
309 /// @param insn - The internal instruction.
310 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
311 const OperandSpecifier &operand,
312 InternalInstruction &insn,
313 const MCDisassembler *Dis) {
314 // Sign-extend the immediate if necessary.
316 OperandType type = (OperandType)operand.type;
318 bool isBranch = false;
320 if (type == TYPE_RELv) {
322 pcrel = insn.startLocation +
323 insn.immediateOffset + insn.immediateSize;
324 switch (insn.displacementSize) {
341 // By default sign-extend all X86 immediates based on their encoding.
342 else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
343 type == TYPE_IMM64) {
344 uint32_t Opcode = mcInst.getOpcode();
345 switch (operand.encoding) {
349 // Special case those X86 instructions that use the imm8 as a set of
350 // bits, bit count, etc. and are not sign-extend.
351 if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
352 Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
353 Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
354 Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
355 Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
356 Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
357 Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
358 Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
359 Opcode != X86::VINSERTPSrr)
378 mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
381 mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
385 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
386 // fall through to sign extend the immediate if needed.
389 immediate |= ~(0xffull);
392 if(immediate & 0x8000)
393 immediate |= ~(0xffffull);
398 pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
399 // fall through to sign extend the immediate if needed.
401 if(immediate & 0x80000000)
402 immediate |= ~(0xffffffffull);
406 // operand is 64 bits wide. Do nothing.
410 if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
411 insn.immediateOffset, insn.immediateSize,
413 mcInst.addOperand(MCOperand::CreateImm(immediate));
416 /// translateRMRegister - Translates a register stored in the R/M field of the
417 /// ModR/M byte to its LLVM equivalent and appends it to an MCInst.
418 /// @param mcInst - The MCInst to append to.
419 /// @param insn - The internal instruction to extract the R/M field
421 /// @return - 0 on success; -1 otherwise
422 static bool translateRMRegister(MCInst &mcInst,
423 InternalInstruction &insn) {
424 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
425 debug("A R/M register operand may not have a SIB byte");
429 switch (insn.eaBase) {
431 debug("Unexpected EA base register");
434 debug("EA_BASE_NONE for ModR/M base");
436 #define ENTRY(x) case EA_BASE_##x:
439 debug("A R/M register operand may not have a base; "
440 "the operand must be a register.");
444 mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
452 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
453 /// fields of an internal instruction (and possibly its SIB byte) to a memory
454 /// operand in LLVM's format, and appends it to an MCInst.
456 /// @param mcInst - The MCInst to append to.
457 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
459 /// @return - 0 on success; nonzero otherwise
460 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
461 const MCDisassembler *Dis) {
462 // Addresses in an MCInst are represented as five operands:
463 // 1. basereg (register) The R/M base, or (if there is a SIB) the
465 // 2. scaleamount (immediate) 1, or (if there is a SIB) the specified
467 // 3. indexreg (register) x86_registerNONE, or (if there is a SIB)
468 // the index (which is multiplied by the
470 // 4. displacement (immediate) 0, or the displacement if there is one
471 // 5. segmentreg (register) x86_registerNONE for now, but could be set
472 // if we have segment overrides
475 MCOperand scaleAmount;
477 MCOperand displacement;
478 MCOperand segmentReg;
481 if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
482 if (insn.sibBase != SIB_BASE_NONE) {
483 switch (insn.sibBase) {
485 debug("Unexpected sibBase");
489 baseReg = MCOperand::CreateReg(X86::x); break;
494 baseReg = MCOperand::CreateReg(0);
497 // Check whether we are handling VSIB addressing mode for GATHER.
498 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
499 // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
500 // I don't see a way to get the correct IndexReg in readSIB:
501 // We can tell whether it is VSIB or SIB after instruction ID is decoded,
502 // but instruction ID may not be decoded yet when calling readSIB.
503 uint32_t Opcode = mcInst.getOpcode();
504 bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
505 Opcode == X86::VGATHERDPDYrm ||
506 Opcode == X86::VGATHERQPDrm ||
507 Opcode == X86::VGATHERDPSrm ||
508 Opcode == X86::VGATHERQPSrm ||
509 Opcode == X86::VPGATHERDQrm ||
510 Opcode == X86::VPGATHERDQYrm ||
511 Opcode == X86::VPGATHERQQrm ||
512 Opcode == X86::VPGATHERDDrm ||
513 Opcode == X86::VPGATHERQDrm);
514 bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
515 Opcode == X86::VGATHERDPSYrm ||
516 Opcode == X86::VGATHERQPSYrm ||
517 Opcode == X86::VPGATHERQQYrm ||
518 Opcode == X86::VPGATHERDDYrm ||
519 Opcode == X86::VPGATHERQDYrm);
520 if (IndexIs128 || IndexIs256) {
521 unsigned IndexOffset = insn.sibIndex -
522 (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
523 SIBIndex IndexBase = IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
524 insn.sibIndex = (SIBIndex)(IndexBase +
525 (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
528 if (insn.sibIndex != SIB_INDEX_NONE) {
529 switch (insn.sibIndex) {
531 debug("Unexpected sibIndex");
534 case SIB_INDEX_##x: \
535 indexReg = MCOperand::CreateReg(X86::x); break;
543 indexReg = MCOperand::CreateReg(0);
546 scaleAmount = MCOperand::CreateImm(insn.sibScale);
548 switch (insn.eaBase) {
550 if (insn.eaDisplacement == EA_DISP_NONE) {
551 debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
554 if (insn.mode == MODE_64BIT){
555 pcrel = insn.startLocation +
556 insn.displacementOffset + insn.displacementSize;
557 tryAddingPcLoadReferenceComment(insn.startLocation +
558 insn.displacementOffset,
559 insn.displacement + pcrel, Dis);
560 baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
563 baseReg = MCOperand::CreateReg(0);
565 indexReg = MCOperand::CreateReg(0);
568 baseReg = MCOperand::CreateReg(X86::BX);
569 indexReg = MCOperand::CreateReg(X86::SI);
572 baseReg = MCOperand::CreateReg(X86::BX);
573 indexReg = MCOperand::CreateReg(X86::DI);
576 baseReg = MCOperand::CreateReg(X86::BP);
577 indexReg = MCOperand::CreateReg(X86::SI);
580 baseReg = MCOperand::CreateReg(X86::BP);
581 indexReg = MCOperand::CreateReg(X86::DI);
584 indexReg = MCOperand::CreateReg(0);
585 switch (insn.eaBase) {
587 debug("Unexpected eaBase");
589 // Here, we will use the fill-ins defined above. However,
590 // BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
591 // sib and sib64 were handled in the top-level if, so they're only
592 // placeholders to keep the compiler happy.
595 baseReg = MCOperand::CreateReg(X86::x); break;
598 #define ENTRY(x) case EA_REG_##x:
601 debug("A R/M memory operand may not be a register; "
602 "the base field must be a base.");
607 scaleAmount = MCOperand::CreateImm(1);
610 displacement = MCOperand::CreateImm(insn.displacement);
612 static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
613 0, // SEG_OVERRIDE_NONE
622 segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
624 mcInst.addOperand(baseReg);
625 mcInst.addOperand(scaleAmount);
626 mcInst.addOperand(indexReg);
627 if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
628 insn.startLocation, insn.displacementOffset,
629 insn.displacementSize, mcInst, Dis))
630 mcInst.addOperand(displacement);
631 mcInst.addOperand(segmentReg);
635 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
636 /// byte of an instruction to LLVM form, and appends it to an MCInst.
638 /// @param mcInst - The MCInst to append to.
639 /// @param operand - The operand, as stored in the descriptor table.
640 /// @param insn - The instruction to extract Mod, R/M, and SIB fields
642 /// @return - 0 on success; nonzero otherwise
643 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
644 InternalInstruction &insn, const MCDisassembler *Dis) {
645 switch (operand.type) {
647 debug("Unexpected type for a R/M operand");
663 case TYPE_CONTROLREG:
664 return translateRMRegister(mcInst, insn);
684 return translateRMMemory(mcInst, insn, Dis);
688 /// translateFPRegister - Translates a stack position on the FPU stack to its
689 /// LLVM form, and appends it to an MCInst.
691 /// @param mcInst - The MCInst to append to.
692 /// @param stackPos - The stack position to translate.
693 /// @return - 0 on success; nonzero otherwise.
694 static bool translateFPRegister(MCInst &mcInst,
697 debug("Invalid FP stack position");
701 mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
706 /// translateOperand - Translates an operand stored in an internal instruction
707 /// to LLVM's format and appends it to an MCInst.
709 /// @param mcInst - The MCInst to append to.
710 /// @param operand - The operand, as stored in the descriptor table.
711 /// @param insn - The internal instruction.
712 /// @return - false on success; true otherwise.
713 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
714 InternalInstruction &insn,
715 const MCDisassembler *Dis) {
716 switch (operand.encoding) {
718 debug("Unhandled operand encoding during translation");
721 translateRegister(mcInst, insn.reg);
724 return translateRM(mcInst, operand, insn, Dis);
731 debug("Translation of code offsets isn't supported.");
739 translateImmediate(mcInst,
740 insn.immediates[insn.numImmediatesTranslated++],
749 translateRegister(mcInst, insn.opcodeRegister);
752 return translateFPRegister(mcInst, insn.opcodeModifier);
754 translateRegister(mcInst, insn.opcodeRegister);
757 translateRegister(mcInst, insn.vvvv);
760 return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
765 /// translateInstruction - Translates an internal instruction and all its
766 /// operands to an MCInst.
768 /// @param mcInst - The MCInst to populate with the instruction's data.
769 /// @param insn - The internal instruction.
770 /// @return - false on success; true otherwise.
771 static bool translateInstruction(MCInst &mcInst,
772 InternalInstruction &insn,
773 const MCDisassembler *Dis) {
775 debug("Instruction has no specification");
779 mcInst.setOpcode(insn.instructionID);
783 insn.numImmediatesTranslated = 0;
785 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
786 if (insn.operands[index].encoding != ENCODING_NONE) {
787 if (translateOperand(mcInst, insn.operands[index], insn, Dis)) {
796 static MCDisassembler *createX86_32Disassembler(const Target &T,
797 const MCSubtargetInfo &STI) {
798 return new X86Disassembler::X86GenericDisassembler(STI, MODE_32BIT,
799 T.createMCInstrInfo());
802 static MCDisassembler *createX86_64Disassembler(const Target &T,
803 const MCSubtargetInfo &STI) {
804 return new X86Disassembler::X86GenericDisassembler(STI, MODE_64BIT,
805 T.createMCInstrInfo());
808 extern "C" void LLVMInitializeX86Disassembler() {
809 // Register the disassembler.
810 TargetRegistry::RegisterMCDisassembler(TheX86_32Target,
811 createX86_32Disassembler);
812 TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
813 createX86_64Disassembler);