Move TargetRegistry and TargetSelect from Target to Support where they belong.
[oota-llvm.git] / lib / Target / X86 / Disassembler / X86Disassembler.cpp
1 //===- X86Disassembler.cpp - Disassembler for x86 and x86_64 ----*- C++ -*-===//
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/MCDisassembler.h"
22 #include "llvm/MC/MCDisassembler.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MemoryObject.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
28
29 #define GET_REGINFO_ENUM
30 #include "X86GenRegisterInfo.inc"
31 #include "X86GenEDInfo.inc"
32
33 using namespace llvm;
34 using namespace llvm::X86Disassembler;
35
36 void x86DisassemblerDebug(const char *file,
37                           unsigned line,
38                           const char *s) {
39   dbgs() << file << ":" << line << ": " << s;
40 }
41
42 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
43
44 namespace llvm {  
45   
46 // Fill-ins to make the compiler happy.  These constants are never actually
47 //   assigned; they are just filler to make an automatically-generated switch
48 //   statement work.
49 namespace X86 {
50   enum {
51     BX_SI = 500,
52     BX_DI = 501,
53     BP_SI = 502,
54     BP_DI = 503,
55     sib   = 504,
56     sib64 = 505
57   };
58 }
59
60 extern Target TheX86_32Target, TheX86_64Target;
61
62 }
63
64 static bool translateInstruction(MCInst &target,
65                                 InternalInstruction &source);
66
67 X86GenericDisassembler::X86GenericDisassembler(DisassemblerMode mode) :
68     MCDisassembler(),
69     fMode(mode) {
70 }
71
72 X86GenericDisassembler::~X86GenericDisassembler() {
73 }
74
75 EDInstInfo *X86GenericDisassembler::getEDInfo() const {
76   return instInfoX86;
77 }
78
79 /// regionReader - a callback function that wraps the readByte method from
80 ///   MemoryObject.
81 ///
82 /// @param arg      - The generic callback parameter.  In this case, this should
83 ///                   be a pointer to a MemoryObject.
84 /// @param byte     - A pointer to the byte to be read.
85 /// @param address  - The address to be read.
86 static int regionReader(void* arg, uint8_t* byte, uint64_t address) {
87   MemoryObject* region = static_cast<MemoryObject*>(arg);
88   return region->readByte(address, byte);
89 }
90
91 /// logger - a callback function that wraps the operator<< method from
92 ///   raw_ostream.
93 ///
94 /// @param arg      - The generic callback parameter.  This should be a pointe
95 ///                   to a raw_ostream.
96 /// @param log      - A string to be logged.  logger() adds a newline.
97 static void logger(void* arg, const char* log) {
98   if (!arg)
99     return;
100   
101   raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
102   vStream << log << "\n";
103 }  
104   
105 //
106 // Public interface for the disassembler
107 //
108
109 MCDisassembler::DecodeStatus
110 X86GenericDisassembler::getInstruction(MCInst &instr,
111                                        uint64_t &size,
112                                        const MemoryObject &region,
113                                        uint64_t address,
114                                        raw_ostream &vStream) const {
115   InternalInstruction internalInstr;
116   
117   int ret = decodeInstruction(&internalInstr,
118                               regionReader,
119                               (void*)&region,
120                               logger,
121                               (void*)&vStream,
122                               address,
123                               fMode);
124
125   if (ret) {
126     size = internalInstr.readerCursor - address;
127     return Fail;
128   }
129   else {
130     size = internalInstr.length;
131     return (!translateInstruction(instr, internalInstr)) ? Success : Fail;
132   }
133 }
134
135 //
136 // Private code that translates from struct InternalInstructions to MCInsts.
137 //
138
139 /// translateRegister - Translates an internal register to the appropriate LLVM
140 ///   register, and appends it as an operand to an MCInst.
141 ///
142 /// @param mcInst     - The MCInst to append to.
143 /// @param reg        - The Reg to append.
144 static void translateRegister(MCInst &mcInst, Reg reg) {
145 #define ENTRY(x) X86::x,
146   uint8_t llvmRegnums[] = {
147     ALL_REGS
148     0
149   };
150 #undef ENTRY
151
152   uint8_t llvmRegnum = llvmRegnums[reg];
153   mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
154 }
155
156 /// translateImmediate  - Appends an immediate operand to an MCInst.
157 ///
158 /// @param mcInst       - The MCInst to append to.
159 /// @param immediate    - The immediate value to append.
160 /// @param operand      - The operand, as stored in the descriptor table.
161 /// @param insn         - The internal instruction.
162 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
163                                const OperandSpecifier &operand,
164                                InternalInstruction &insn) {
165   // Sign-extend the immediate if necessary.
166
167   OperandType type = operand.type;
168
169   if (type == TYPE_RELv) {
170     switch (insn.displacementSize) {
171     default:
172       break;
173     case 1:
174       type = TYPE_MOFFS8;
175       break;
176     case 2:
177       type = TYPE_MOFFS16;
178       break;
179     case 4:
180       type = TYPE_MOFFS32;
181       break;
182     case 8:
183       type = TYPE_MOFFS64;
184       break;
185     }
186   }
187
188   switch (type) {
189   case TYPE_MOFFS8:
190   case TYPE_REL8:
191     if(immediate & 0x80)
192       immediate |= ~(0xffull);
193     break;
194   case TYPE_MOFFS16:
195     if(immediate & 0x8000)
196       immediate |= ~(0xffffull);
197     break;
198   case TYPE_MOFFS32:
199   case TYPE_REL32:
200   case TYPE_REL64:
201     if(immediate & 0x80000000)
202       immediate |= ~(0xffffffffull);
203     break;
204   case TYPE_MOFFS64:
205   default:
206     // operand is 64 bits wide.  Do nothing.
207     break;
208   }
209     
210   mcInst.addOperand(MCOperand::CreateImm(immediate));
211 }
212
213 /// translateRMRegister - Translates a register stored in the R/M field of the
214 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
215 /// @param mcInst       - The MCInst to append to.
216 /// @param insn         - The internal instruction to extract the R/M field
217 ///                       from.
218 /// @return             - 0 on success; -1 otherwise
219 static bool translateRMRegister(MCInst &mcInst,
220                                 InternalInstruction &insn) {
221   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
222     debug("A R/M register operand may not have a SIB byte");
223     return true;
224   }
225   
226   switch (insn.eaBase) {
227   default:
228     debug("Unexpected EA base register");
229     return true;
230   case EA_BASE_NONE:
231     debug("EA_BASE_NONE for ModR/M base");
232     return true;
233 #define ENTRY(x) case EA_BASE_##x:
234   ALL_EA_BASES
235 #undef ENTRY
236     debug("A R/M register operand may not have a base; "
237           "the operand must be a register.");
238     return true;
239 #define ENTRY(x)                                                      \
240   case EA_REG_##x:                                                    \
241     mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
242   ALL_REGS
243 #undef ENTRY
244   }
245   
246   return false;
247 }
248
249 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
250 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
251 ///   operand in LLVM's format, and appends it to an MCInst.
252 ///
253 /// @param mcInst       - The MCInst to append to.
254 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
255 ///                       from.
256 /// @return             - 0 on success; nonzero otherwise
257 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn) {
258   // Addresses in an MCInst are represented as five operands:
259   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the 
260   //                                SIB base
261   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified 
262   //                                scale amount
263   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
264   //                                the index (which is multiplied by the 
265   //                                scale amount)
266   //   4. displacement  (immediate) 0, or the displacement if there is one
267   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
268   //                                if we have segment overrides
269   
270   MCOperand baseReg;
271   MCOperand scaleAmount;
272   MCOperand indexReg;
273   MCOperand displacement;
274   MCOperand segmentReg;
275   
276   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
277     if (insn.sibBase != SIB_BASE_NONE) {
278       switch (insn.sibBase) {
279       default:
280         debug("Unexpected sibBase");
281         return true;
282 #define ENTRY(x)                                          \
283       case SIB_BASE_##x:                                  \
284         baseReg = MCOperand::CreateReg(X86::x); break;
285       ALL_SIB_BASES
286 #undef ENTRY
287       }
288     } else {
289       baseReg = MCOperand::CreateReg(0);
290     }
291     
292     if (insn.sibIndex != SIB_INDEX_NONE) {
293       switch (insn.sibIndex) {
294       default:
295         debug("Unexpected sibIndex");
296         return true;
297 #define ENTRY(x)                                          \
298       case SIB_INDEX_##x:                                 \
299         indexReg = MCOperand::CreateReg(X86::x); break;
300       EA_BASES_32BIT
301       EA_BASES_64BIT
302 #undef ENTRY
303       }
304     } else {
305       indexReg = MCOperand::CreateReg(0);
306     }
307     
308     scaleAmount = MCOperand::CreateImm(insn.sibScale);
309   } else {
310     switch (insn.eaBase) {
311     case EA_BASE_NONE:
312       if (insn.eaDisplacement == EA_DISP_NONE) {
313         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
314         return true;
315       }
316       if (insn.mode == MODE_64BIT)
317         baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
318       else
319         baseReg = MCOperand::CreateReg(0);
320       
321       indexReg = MCOperand::CreateReg(0);
322       break;
323     case EA_BASE_BX_SI:
324       baseReg = MCOperand::CreateReg(X86::BX);
325       indexReg = MCOperand::CreateReg(X86::SI);
326       break;
327     case EA_BASE_BX_DI:
328       baseReg = MCOperand::CreateReg(X86::BX);
329       indexReg = MCOperand::CreateReg(X86::DI);
330       break;
331     case EA_BASE_BP_SI:
332       baseReg = MCOperand::CreateReg(X86::BP);
333       indexReg = MCOperand::CreateReg(X86::SI);
334       break;
335     case EA_BASE_BP_DI:
336       baseReg = MCOperand::CreateReg(X86::BP);
337       indexReg = MCOperand::CreateReg(X86::DI);
338       break;
339     default:
340       indexReg = MCOperand::CreateReg(0);
341       switch (insn.eaBase) {
342       default:
343         debug("Unexpected eaBase");
344         return true;
345         // Here, we will use the fill-ins defined above.  However,
346         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
347         //   sib and sib64 were handled in the top-level if, so they're only
348         //   placeholders to keep the compiler happy.
349 #define ENTRY(x)                                        \
350       case EA_BASE_##x:                                 \
351         baseReg = MCOperand::CreateReg(X86::x); break; 
352       ALL_EA_BASES
353 #undef ENTRY
354 #define ENTRY(x) case EA_REG_##x:
355       ALL_REGS
356 #undef ENTRY
357         debug("A R/M memory operand may not be a register; "
358               "the base field must be a base.");
359         return true;
360       }
361     }
362     
363     scaleAmount = MCOperand::CreateImm(1);
364   }
365   
366   displacement = MCOperand::CreateImm(insn.displacement);
367   
368   static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
369     0,        // SEG_OVERRIDE_NONE
370     X86::CS,
371     X86::SS,
372     X86::DS,
373     X86::ES,
374     X86::FS,
375     X86::GS
376   };
377   
378   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
379   
380   mcInst.addOperand(baseReg);
381   mcInst.addOperand(scaleAmount);
382   mcInst.addOperand(indexReg);
383   mcInst.addOperand(displacement);
384   mcInst.addOperand(segmentReg);
385   return false;
386 }
387
388 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
389 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
390 ///
391 /// @param mcInst       - The MCInst to append to.
392 /// @param operand      - The operand, as stored in the descriptor table.
393 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
394 ///                       from.
395 /// @return             - 0 on success; nonzero otherwise
396 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
397                         InternalInstruction &insn) {
398   switch (operand.type) {
399   default:
400     debug("Unexpected type for a R/M operand");
401     return true;
402   case TYPE_R8:
403   case TYPE_R16:
404   case TYPE_R32:
405   case TYPE_R64:
406   case TYPE_Rv:
407   case TYPE_MM:
408   case TYPE_MM32:
409   case TYPE_MM64:
410   case TYPE_XMM:
411   case TYPE_XMM32:
412   case TYPE_XMM64:
413   case TYPE_XMM128:
414   case TYPE_XMM256:
415   case TYPE_DEBUGREG:
416   case TYPE_CONTROLREG:
417     return translateRMRegister(mcInst, insn);
418   case TYPE_M:
419   case TYPE_M8:
420   case TYPE_M16:
421   case TYPE_M32:
422   case TYPE_M64:
423   case TYPE_M128:
424   case TYPE_M256:
425   case TYPE_M512:
426   case TYPE_Mv:
427   case TYPE_M32FP:
428   case TYPE_M64FP:
429   case TYPE_M80FP:
430   case TYPE_M16INT:
431   case TYPE_M32INT:
432   case TYPE_M64INT:
433   case TYPE_M1616:
434   case TYPE_M1632:
435   case TYPE_M1664:
436   case TYPE_LEA:
437     return translateRMMemory(mcInst, insn);
438   }
439 }
440   
441 /// translateFPRegister - Translates a stack position on the FPU stack to its
442 ///   LLVM form, and appends it to an MCInst.
443 ///
444 /// @param mcInst       - The MCInst to append to.
445 /// @param stackPos     - The stack position to translate.
446 /// @return             - 0 on success; nonzero otherwise.
447 static bool translateFPRegister(MCInst &mcInst,
448                                uint8_t stackPos) {
449   if (stackPos >= 8) {
450     debug("Invalid FP stack position");
451     return true;
452   }
453   
454   mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
455
456   return false;
457 }
458
459 /// translateOperand - Translates an operand stored in an internal instruction 
460 ///   to LLVM's format and appends it to an MCInst.
461 ///
462 /// @param mcInst       - The MCInst to append to.
463 /// @param operand      - The operand, as stored in the descriptor table.
464 /// @param insn         - The internal instruction.
465 /// @return             - false on success; true otherwise.
466 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
467                              InternalInstruction &insn) {
468   switch (operand.encoding) {
469   default:
470     debug("Unhandled operand encoding during translation");
471     return true;
472   case ENCODING_REG:
473     translateRegister(mcInst, insn.reg);
474     return false;
475   case ENCODING_RM:
476     return translateRM(mcInst, operand, insn);
477   case ENCODING_CB:
478   case ENCODING_CW:
479   case ENCODING_CD:
480   case ENCODING_CP:
481   case ENCODING_CO:
482   case ENCODING_CT:
483     debug("Translation of code offsets isn't supported.");
484     return true;
485   case ENCODING_IB:
486   case ENCODING_IW:
487   case ENCODING_ID:
488   case ENCODING_IO:
489   case ENCODING_Iv:
490   case ENCODING_Ia:
491     translateImmediate(mcInst,
492                        insn.immediates[insn.numImmediatesTranslated++],
493                        operand,
494                        insn);
495     return false;
496   case ENCODING_RB:
497   case ENCODING_RW:
498   case ENCODING_RD:
499   case ENCODING_RO:
500     translateRegister(mcInst, insn.opcodeRegister);
501     return false;
502   case ENCODING_I:
503     return translateFPRegister(mcInst, insn.opcodeModifier);
504   case ENCODING_Rv:
505     translateRegister(mcInst, insn.opcodeRegister);
506     return false;
507   case ENCODING_VVVV:
508     translateRegister(mcInst, insn.vvvv);
509     return false;
510   case ENCODING_DUP:
511     return translateOperand(mcInst,
512                             insn.spec->operands[operand.type - TYPE_DUP0],
513                             insn);
514   }
515 }
516   
517 /// translateInstruction - Translates an internal instruction and all its
518 ///   operands to an MCInst.
519 ///
520 /// @param mcInst       - The MCInst to populate with the instruction's data.
521 /// @param insn         - The internal instruction.
522 /// @return             - false on success; true otherwise.
523 static bool translateInstruction(MCInst &mcInst,
524                                 InternalInstruction &insn) {  
525   if (!insn.spec) {
526     debug("Instruction has no specification");
527     return true;
528   }
529   
530   mcInst.setOpcode(insn.instructionID);
531   
532   int index;
533   
534   insn.numImmediatesTranslated = 0;
535   
536   for (index = 0; index < X86_MAX_OPERANDS; ++index) {
537     if (insn.spec->operands[index].encoding != ENCODING_NONE) {
538       if (translateOperand(mcInst, insn.spec->operands[index], insn)) {
539         return true;
540       }
541     }
542   }
543   
544   return false;
545 }
546
547 static MCDisassembler *createX86_32Disassembler(const Target &T) {
548   return new X86Disassembler::X86_32Disassembler;
549 }
550
551 static MCDisassembler *createX86_64Disassembler(const Target &T) {
552   return new X86Disassembler::X86_64Disassembler;
553 }
554
555 extern "C" void LLVMInitializeX86Disassembler() { 
556   // Register the disassembler.
557   TargetRegistry::RegisterMCDisassembler(TheX86_32Target, 
558                                          createX86_32Disassembler);
559   TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
560                                          createX86_64Disassembler);
561 }