Updated the llvm-mc disassembler C API to support for the X86 target.
[oota-llvm.git] / lib / Target / X86 / Disassembler / X86Disassembler.cpp
1 //===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is part of the X86 Disassembler.
11 // It contains code to translate the data produced by the decoder into
12 //  MCInsts.
13 // Documentation for the disassembler can be found in X86Disassembler.h.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86Disassembler.h"
18 #include "X86DisassemblerDecoder.h"
19
20 #include "llvm/MC/EDInstInfo.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MemoryObject.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
31
32 #define GET_REGINFO_ENUM
33 #include "X86GenRegisterInfo.inc"
34 #define GET_INSTRINFO_ENUM
35 #include "X86GenInstrInfo.inc"
36 #include "X86GenEDInfo.inc"
37
38 using namespace llvm;
39 using namespace llvm::X86Disassembler;
40
41 void x86DisassemblerDebug(const char *file,
42                           unsigned line,
43                           const char *s) {
44   dbgs() << file << ":" << line << ": " << s;
45 }
46
47 const char *x86DisassemblerGetInstrName(unsigned Opcode, void *mii) {
48   const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
49   return MII->getName(Opcode);
50 }
51
52 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
53
54 namespace llvm {  
55   
56 // Fill-ins to make the compiler happy.  These constants are never actually
57 //   assigned; they are just filler to make an automatically-generated switch
58 //   statement work.
59 namespace X86 {
60   enum {
61     BX_SI = 500,
62     BX_DI = 501,
63     BP_SI = 502,
64     BP_DI = 503,
65     sib   = 504,
66     sib64 = 505
67   };
68 }
69
70 extern Target TheX86_32Target, TheX86_64Target;
71
72 }
73
74 static bool translateInstruction(MCInst &target,
75                                 InternalInstruction &source,
76                                 const MCDisassembler *Dis);
77
78 X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
79                                                DisassemblerMode mode,
80                                                const MCInstrInfo *MII)
81   : MCDisassembler(STI), MII(MII), fMode(mode) {}
82
83 X86GenericDisassembler::~X86GenericDisassembler() {
84   delete MII;
85 }
86
87 const EDInstInfo *X86GenericDisassembler::getEDInfo() const {
88   return instInfoX86;
89 }
90
91 /// regionReader - a callback function that wraps the readByte method from
92 ///   MemoryObject.
93 ///
94 /// @param arg      - The generic callback parameter.  In this case, this should
95 ///                   be a pointer to a MemoryObject.
96 /// @param byte     - A pointer to the byte to be read.
97 /// @param address  - The address to be read.
98 static int regionReader(void* arg, uint8_t* byte, uint64_t address) {
99   MemoryObject* region = static_cast<MemoryObject*>(arg);
100   return region->readByte(address, byte);
101 }
102
103 /// logger - a callback function that wraps the operator<< method from
104 ///   raw_ostream.
105 ///
106 /// @param arg      - The generic callback parameter.  This should be a pointe
107 ///                   to a raw_ostream.
108 /// @param log      - A string to be logged.  logger() adds a newline.
109 static void logger(void* arg, const char* log) {
110   if (!arg)
111     return;
112   
113   raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
114   vStream << log << "\n";
115 }  
116   
117 //
118 // Public interface for the disassembler
119 //
120
121 MCDisassembler::DecodeStatus
122 X86GenericDisassembler::getInstruction(MCInst &instr,
123                                        uint64_t &size,
124                                        MemoryObject &region,
125                                        uint64_t address,
126                                        raw_ostream &vStream,
127                                        raw_ostream &cStream) const {
128   CommentStream = &cStream;
129
130   InternalInstruction internalInstr;
131
132   dlog_t loggerFn = logger;
133   if (&vStream == &nulls())
134     loggerFn = 0; // Disable logging completely if it's going to nulls().
135   
136   int ret = decodeInstruction(&internalInstr,
137                               regionReader,
138                               (void*)&region,
139                               loggerFn,
140                               (void*)&vStream,
141                               (void*)MII,
142                               address,
143                               fMode);
144
145   if (ret) {
146     size = internalInstr.readerCursor - address;
147     return Fail;
148   }
149   else {
150     size = internalInstr.length;
151     return (!translateInstruction(instr, internalInstr, this)) ?
152             Success : Fail;
153   }
154 }
155
156 //
157 // Private code that translates from struct InternalInstructions to MCInsts.
158 //
159
160 /// translateRegister - Translates an internal register to the appropriate LLVM
161 ///   register, and appends it as an operand to an MCInst.
162 ///
163 /// @param mcInst     - The MCInst to append to.
164 /// @param reg        - The Reg to append.
165 static void translateRegister(MCInst &mcInst, Reg reg) {
166 #define ENTRY(x) X86::x,
167   uint8_t llvmRegnums[] = {
168     ALL_REGS
169     0
170   };
171 #undef ENTRY
172
173   uint8_t llvmRegnum = llvmRegnums[reg];
174   mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
175 }
176
177 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
178 /// immediate Value in the MCInst. 
179 ///
180 /// @param Value      - The immediate Value, has had any PC adjustment made by
181 ///                     the caller.
182 /// @param isBranch   - If the instruction is a branch instruction
183 /// @param Address    - The starting address of the instruction
184 /// @param Offset     - The byte offset to this immediate in the instruction
185 /// @param Width      - The byte width of this immediate in the instruction
186 ///
187 /// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
188 /// called then that function is called to get any symbolic information for the
189 /// immediate in the instruction using the Address, Offset and Width.  If that
190 /// returns non-zero then the symbolic information it returns is used to create 
191 /// an MCExpr and that is added as an operand to the MCInst.  If getOpInfo()
192 /// returns zero and isBranch is true then a symbol look up for immediate Value
193 /// is done and if a symbol is found an MCExpr is created with that, else
194 /// an MCExpr with the immediate Value is created.  This function returns true
195 /// if it adds an operand to the MCInst and false otherwise.
196 static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
197                                      uint64_t Address, uint64_t Offset,
198                                      uint64_t Width, MCInst &MI, 
199                                      const MCDisassembler *Dis) {  
200   LLVMOpInfoCallback getOpInfo = Dis->getLLVMOpInfoCallback();
201   struct LLVMOpInfo1 SymbolicOp;
202   memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
203   SymbolicOp.Value = Value;
204   void *DisInfo = Dis->getDisInfoBlock();
205
206   if (!getOpInfo ||
207       !getOpInfo(DisInfo, Address, Offset, Width, 1, &SymbolicOp)) {
208     // Clear SymbolicOp.Value from above and also all other fields.
209     memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
210     LLVMSymbolLookupCallback SymbolLookUp = Dis->getLLVMSymbolLookupCallback();
211     if (!SymbolLookUp)
212       return false;
213     uint64_t ReferenceType;
214     if (isBranch)
215        ReferenceType = LLVMDisassembler_ReferenceType_In_Branch;
216     else
217        ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
218     const char *ReferenceName;
219     const char *Name = SymbolLookUp(DisInfo, Value, &ReferenceType, Address,
220                                     &ReferenceName);
221     if (Name) {
222       SymbolicOp.AddSymbol.Name = Name;
223       SymbolicOp.AddSymbol.Present = true;
224     }
225     // For branches always create an MCExpr so it gets printed as hex address.
226     else if (isBranch) {
227       SymbolicOp.Value = Value;
228     }
229     if(ReferenceType == LLVMDisassembler_ReferenceType_Out_SymbolStub)
230       (*Dis->CommentStream) << "symbol stub for: " << ReferenceName;
231     if (!Name && !isBranch)
232       return false;
233   }
234
235   MCContext *Ctx = Dis->getMCContext();
236   const MCExpr *Add = NULL;
237   if (SymbolicOp.AddSymbol.Present) {
238     if (SymbolicOp.AddSymbol.Name) {
239       StringRef Name(SymbolicOp.AddSymbol.Name);
240       MCSymbol *Sym = Ctx->GetOrCreateSymbol(Name);
241       Add = MCSymbolRefExpr::Create(Sym, *Ctx);
242     } else {
243       Add = MCConstantExpr::Create((int)SymbolicOp.AddSymbol.Value, *Ctx);
244     }
245   }
246
247   const MCExpr *Sub = NULL;
248   if (SymbolicOp.SubtractSymbol.Present) {
249       if (SymbolicOp.SubtractSymbol.Name) {
250       StringRef Name(SymbolicOp.SubtractSymbol.Name);
251       MCSymbol *Sym = Ctx->GetOrCreateSymbol(Name);
252       Sub = MCSymbolRefExpr::Create(Sym, *Ctx);
253     } else {
254       Sub = MCConstantExpr::Create((int)SymbolicOp.SubtractSymbol.Value, *Ctx);
255     }
256   }
257
258   const MCExpr *Off = NULL;
259   if (SymbolicOp.Value != 0)
260     Off = MCConstantExpr::Create(SymbolicOp.Value, *Ctx);
261
262   const MCExpr *Expr;
263   if (Sub) {
264     const MCExpr *LHS;
265     if (Add)
266       LHS = MCBinaryExpr::CreateSub(Add, Sub, *Ctx);
267     else
268       LHS = MCUnaryExpr::CreateMinus(Sub, *Ctx);
269     if (Off != 0)
270       Expr = MCBinaryExpr::CreateAdd(LHS, Off, *Ctx);
271     else
272       Expr = LHS;
273   } else if (Add) {
274     if (Off != 0)
275       Expr = MCBinaryExpr::CreateAdd(Add, Off, *Ctx);
276     else
277       Expr = Add;
278   } else {
279     if (Off != 0)
280       Expr = Off;
281     else
282       Expr = MCConstantExpr::Create(0, *Ctx);
283   }
284
285   MI.addOperand(MCOperand::CreateExpr(Expr));
286
287   return true;
288 }
289
290 /// translateImmediate  - Appends an immediate operand to an MCInst.
291 ///
292 /// @param mcInst       - The MCInst to append to.
293 /// @param immediate    - The immediate value to append.
294 /// @param operand      - The operand, as stored in the descriptor table.
295 /// @param insn         - The internal instruction.
296 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
297                                const OperandSpecifier &operand,
298                                InternalInstruction &insn,
299                                const MCDisassembler *Dis) {  
300   // Sign-extend the immediate if necessary.
301
302   OperandType type = operand.type;
303
304   if (type == TYPE_RELv) {
305     switch (insn.displacementSize) {
306     default:
307       break;
308     case 1:
309       type = TYPE_MOFFS8;
310       break;
311     case 2:
312       type = TYPE_MOFFS16;
313       break;
314     case 4:
315       type = TYPE_MOFFS32;
316       break;
317     case 8:
318       type = TYPE_MOFFS64;
319       break;
320     }
321   }
322   // By default sign-extend all X86 immediates based on their encoding.
323   else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
324            type == TYPE_IMM64) {
325     uint32_t Opcode = mcInst.getOpcode();
326     switch (operand.encoding) {
327     default:
328       break;
329     case ENCODING_IB:
330       // Special case those X86 instructions that use the imm8 as a set of
331       // bits, bit count, etc. and are not sign-extend.
332       if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
333           Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
334           Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
335           Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
336           Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
337           Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
338           Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
339           Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
340           Opcode != X86::VINSERTPSrr)
341         type = TYPE_MOFFS8;
342       break;
343     case ENCODING_IW:
344       type = TYPE_MOFFS16;
345       break;
346     case ENCODING_ID:
347       type = TYPE_MOFFS32;
348       break;
349     case ENCODING_IO:
350       type = TYPE_MOFFS64;
351       break;
352     }
353   }
354
355   bool isBranch = false;
356   uint64_t pcrel = 0;
357   switch (type) {
358   case TYPE_XMM128:
359     mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
360     return;
361   case TYPE_XMM256:
362     mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
363     return;
364   case TYPE_REL8:
365     isBranch = true;
366     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
367     // fall through to sign extend the immediate if needed.
368   case TYPE_MOFFS8:
369     if(immediate & 0x80)
370       immediate |= ~(0xffull);
371     break;
372   case TYPE_MOFFS16:
373     if(immediate & 0x8000)
374       immediate |= ~(0xffffull);
375     break;
376   case TYPE_REL32:
377   case TYPE_REL64:
378     isBranch = true;
379     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
380     // fall through to sign extend the immediate if needed.
381   case TYPE_MOFFS32:
382     if(immediate & 0x80000000)
383       immediate |= ~(0xffffffffull);
384     break;
385   case TYPE_MOFFS64:
386   default:
387     // operand is 64 bits wide.  Do nothing.
388     break;
389   }
390     
391   if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
392                                insn.immediateOffset, insn.immediateSize,
393                                mcInst, Dis))
394     mcInst.addOperand(MCOperand::CreateImm(immediate));
395 }
396
397 /// translateRMRegister - Translates a register stored in the R/M field of the
398 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
399 /// @param mcInst       - The MCInst to append to.
400 /// @param insn         - The internal instruction to extract the R/M field
401 ///                       from.
402 /// @return             - 0 on success; -1 otherwise
403 static bool translateRMRegister(MCInst &mcInst,
404                                 InternalInstruction &insn) {
405   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
406     debug("A R/M register operand may not have a SIB byte");
407     return true;
408   }
409   
410   switch (insn.eaBase) {
411   default:
412     debug("Unexpected EA base register");
413     return true;
414   case EA_BASE_NONE:
415     debug("EA_BASE_NONE for ModR/M base");
416     return true;
417 #define ENTRY(x) case EA_BASE_##x:
418   ALL_EA_BASES
419 #undef ENTRY
420     debug("A R/M register operand may not have a base; "
421           "the operand must be a register.");
422     return true;
423 #define ENTRY(x)                                                      \
424   case EA_REG_##x:                                                    \
425     mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
426   ALL_REGS
427 #undef ENTRY
428   }
429   
430   return false;
431 }
432
433 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
434 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
435 ///   operand in LLVM's format, and appends it to an MCInst.
436 ///
437 /// @param mcInst       - The MCInst to append to.
438 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
439 ///                       from.
440 /// @return             - 0 on success; nonzero otherwise
441 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
442                               const MCDisassembler *Dis) {  
443   // Addresses in an MCInst are represented as five operands:
444   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the 
445   //                                SIB base
446   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified 
447   //                                scale amount
448   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
449   //                                the index (which is multiplied by the 
450   //                                scale amount)
451   //   4. displacement  (immediate) 0, or the displacement if there is one
452   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
453   //                                if we have segment overrides
454   
455   MCOperand baseReg;
456   MCOperand scaleAmount;
457   MCOperand indexReg;
458   MCOperand displacement;
459   MCOperand segmentReg;
460   uint64_t pcrel = 0;
461   
462   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
463     if (insn.sibBase != SIB_BASE_NONE) {
464       switch (insn.sibBase) {
465       default:
466         debug("Unexpected sibBase");
467         return true;
468 #define ENTRY(x)                                          \
469       case SIB_BASE_##x:                                  \
470         baseReg = MCOperand::CreateReg(X86::x); break;
471       ALL_SIB_BASES
472 #undef ENTRY
473       }
474     } else {
475       baseReg = MCOperand::CreateReg(0);
476     }
477     
478     if (insn.sibIndex != SIB_INDEX_NONE) {
479       switch (insn.sibIndex) {
480       default:
481         debug("Unexpected sibIndex");
482         return true;
483 #define ENTRY(x)                                          \
484       case SIB_INDEX_##x:                                 \
485         indexReg = MCOperand::CreateReg(X86::x); break;
486       EA_BASES_32BIT
487       EA_BASES_64BIT
488 #undef ENTRY
489       }
490     } else {
491       indexReg = MCOperand::CreateReg(0);
492     }
493     
494     scaleAmount = MCOperand::CreateImm(insn.sibScale);
495   } else {
496     switch (insn.eaBase) {
497     case EA_BASE_NONE:
498       if (insn.eaDisplacement == EA_DISP_NONE) {
499         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
500         return true;
501       }
502       if (insn.mode == MODE_64BIT){
503         pcrel = insn.startLocation +
504                 insn.displacementOffset + insn.displacementSize;
505         baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
506       }
507       else
508         baseReg = MCOperand::CreateReg(0);
509       
510       indexReg = MCOperand::CreateReg(0);
511       break;
512     case EA_BASE_BX_SI:
513       baseReg = MCOperand::CreateReg(X86::BX);
514       indexReg = MCOperand::CreateReg(X86::SI);
515       break;
516     case EA_BASE_BX_DI:
517       baseReg = MCOperand::CreateReg(X86::BX);
518       indexReg = MCOperand::CreateReg(X86::DI);
519       break;
520     case EA_BASE_BP_SI:
521       baseReg = MCOperand::CreateReg(X86::BP);
522       indexReg = MCOperand::CreateReg(X86::SI);
523       break;
524     case EA_BASE_BP_DI:
525       baseReg = MCOperand::CreateReg(X86::BP);
526       indexReg = MCOperand::CreateReg(X86::DI);
527       break;
528     default:
529       indexReg = MCOperand::CreateReg(0);
530       switch (insn.eaBase) {
531       default:
532         debug("Unexpected eaBase");
533         return true;
534         // Here, we will use the fill-ins defined above.  However,
535         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
536         //   sib and sib64 were handled in the top-level if, so they're only
537         //   placeholders to keep the compiler happy.
538 #define ENTRY(x)                                        \
539       case EA_BASE_##x:                                 \
540         baseReg = MCOperand::CreateReg(X86::x); break; 
541       ALL_EA_BASES
542 #undef ENTRY
543 #define ENTRY(x) case EA_REG_##x:
544       ALL_REGS
545 #undef ENTRY
546         debug("A R/M memory operand may not be a register; "
547               "the base field must be a base.");
548         return true;
549       }
550     }
551     
552     scaleAmount = MCOperand::CreateImm(1);
553   }
554   
555   displacement = MCOperand::CreateImm(insn.displacement);
556   
557   static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
558     0,        // SEG_OVERRIDE_NONE
559     X86::CS,
560     X86::SS,
561     X86::DS,
562     X86::ES,
563     X86::FS,
564     X86::GS
565   };
566   
567   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
568   
569   mcInst.addOperand(baseReg);
570   mcInst.addOperand(scaleAmount);
571   mcInst.addOperand(indexReg);
572   if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
573                                insn.startLocation, insn.displacementOffset,
574                                insn.displacementSize, mcInst, Dis))
575     mcInst.addOperand(displacement);
576   mcInst.addOperand(segmentReg);
577   return false;
578 }
579
580 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
581 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
582 ///
583 /// @param mcInst       - The MCInst to append to.
584 /// @param operand      - The operand, as stored in the descriptor table.
585 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
586 ///                       from.
587 /// @return             - 0 on success; nonzero otherwise
588 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
589                         InternalInstruction &insn, const MCDisassembler *Dis) {  
590   switch (operand.type) {
591   default:
592     debug("Unexpected type for a R/M operand");
593     return true;
594   case TYPE_R8:
595   case TYPE_R16:
596   case TYPE_R32:
597   case TYPE_R64:
598   case TYPE_Rv:
599   case TYPE_MM:
600   case TYPE_MM32:
601   case TYPE_MM64:
602   case TYPE_XMM:
603   case TYPE_XMM32:
604   case TYPE_XMM64:
605   case TYPE_XMM128:
606   case TYPE_XMM256:
607   case TYPE_DEBUGREG:
608   case TYPE_CONTROLREG:
609     return translateRMRegister(mcInst, insn);
610   case TYPE_M:
611   case TYPE_M8:
612   case TYPE_M16:
613   case TYPE_M32:
614   case TYPE_M64:
615   case TYPE_M128:
616   case TYPE_M256:
617   case TYPE_M512:
618   case TYPE_Mv:
619   case TYPE_M32FP:
620   case TYPE_M64FP:
621   case TYPE_M80FP:
622   case TYPE_M16INT:
623   case TYPE_M32INT:
624   case TYPE_M64INT:
625   case TYPE_M1616:
626   case TYPE_M1632:
627   case TYPE_M1664:
628   case TYPE_LEA:
629     return translateRMMemory(mcInst, insn, Dis);
630   }
631 }
632   
633 /// translateFPRegister - Translates a stack position on the FPU stack to its
634 ///   LLVM form, and appends it to an MCInst.
635 ///
636 /// @param mcInst       - The MCInst to append to.
637 /// @param stackPos     - The stack position to translate.
638 /// @return             - 0 on success; nonzero otherwise.
639 static bool translateFPRegister(MCInst &mcInst,
640                                uint8_t stackPos) {
641   if (stackPos >= 8) {
642     debug("Invalid FP stack position");
643     return true;
644   }
645   
646   mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
647
648   return false;
649 }
650
651 /// translateOperand - Translates an operand stored in an internal instruction 
652 ///   to LLVM's format and appends it to an MCInst.
653 ///
654 /// @param mcInst       - The MCInst to append to.
655 /// @param operand      - The operand, as stored in the descriptor table.
656 /// @param insn         - The internal instruction.
657 /// @return             - false on success; true otherwise.
658 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
659                              InternalInstruction &insn,
660                              const MCDisassembler *Dis) {  
661   switch (operand.encoding) {
662   default:
663     debug("Unhandled operand encoding during translation");
664     return true;
665   case ENCODING_REG:
666     translateRegister(mcInst, insn.reg);
667     return false;
668   case ENCODING_RM:
669     return translateRM(mcInst, operand, insn, Dis);
670   case ENCODING_CB:
671   case ENCODING_CW:
672   case ENCODING_CD:
673   case ENCODING_CP:
674   case ENCODING_CO:
675   case ENCODING_CT:
676     debug("Translation of code offsets isn't supported.");
677     return true;
678   case ENCODING_IB:
679   case ENCODING_IW:
680   case ENCODING_ID:
681   case ENCODING_IO:
682   case ENCODING_Iv:
683   case ENCODING_Ia:
684     translateImmediate(mcInst,
685                        insn.immediates[insn.numImmediatesTranslated++],
686                        operand,
687                        insn,
688                        Dis);
689     return false;
690   case ENCODING_RB:
691   case ENCODING_RW:
692   case ENCODING_RD:
693   case ENCODING_RO:
694     translateRegister(mcInst, insn.opcodeRegister);
695     return false;
696   case ENCODING_I:
697     return translateFPRegister(mcInst, insn.opcodeModifier);
698   case ENCODING_Rv:
699     translateRegister(mcInst, insn.opcodeRegister);
700     return false;
701   case ENCODING_VVVV:
702     translateRegister(mcInst, insn.vvvv);
703     return false;
704   case ENCODING_DUP:
705     return translateOperand(mcInst,
706                             insn.spec->operands[operand.type - TYPE_DUP0],
707                             insn, Dis);
708   }
709 }
710   
711 /// translateInstruction - Translates an internal instruction and all its
712 ///   operands to an MCInst.
713 ///
714 /// @param mcInst       - The MCInst to populate with the instruction's data.
715 /// @param insn         - The internal instruction.
716 /// @return             - false on success; true otherwise.
717 static bool translateInstruction(MCInst &mcInst,
718                                 InternalInstruction &insn,
719                                 const MCDisassembler *Dis) {  
720   if (!insn.spec) {
721     debug("Instruction has no specification");
722     return true;
723   }
724   
725   mcInst.setOpcode(insn.instructionID);
726   
727   int index;
728   
729   insn.numImmediatesTranslated = 0;
730   
731   for (index = 0; index < X86_MAX_OPERANDS; ++index) {
732     if (insn.spec->operands[index].encoding != ENCODING_NONE) {
733       if (translateOperand(mcInst, insn.spec->operands[index], insn, Dis)) {
734         return true;
735       }
736     }
737   }
738   
739   return false;
740 }
741
742 static MCDisassembler *createX86_32Disassembler(const Target &T,
743                                                 const MCSubtargetInfo &STI) {
744   return new X86Disassembler::X86GenericDisassembler(STI, MODE_32BIT,
745                                                      T.createMCInstrInfo());
746 }
747
748 static MCDisassembler *createX86_64Disassembler(const Target &T,
749                                                 const MCSubtargetInfo &STI) {
750   return new X86Disassembler::X86GenericDisassembler(STI, MODE_64BIT,
751                                                      T.createMCInstrInfo());
752 }
753
754 extern "C" void LLVMInitializeX86Disassembler() { 
755   // Register the disassembler.
756   TargetRegistry::RegisterMCDisassembler(TheX86_32Target, 
757                                          createX86_32Disassembler);
758   TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
759                                          createX86_64Disassembler);
760 }