AVX-512: decoder for AVX-512, made by Alexey Bader.
[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 #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"
29
30 #define GET_REGINFO_ENUM
31 #include "X86GenRegisterInfo.inc"
32 #define GET_INSTRINFO_ENUM
33 #include "X86GenInstrInfo.inc"
34
35 using namespace llvm;
36 using namespace llvm::X86Disassembler;
37
38 void x86DisassemblerDebug(const char *file,
39                           unsigned line,
40                           const char *s) {
41   dbgs() << file << ":" << line << ": " << s;
42 }
43
44 const char *x86DisassemblerGetInstrName(unsigned Opcode, const void *mii) {
45   const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
46   return MII->getName(Opcode);
47 }
48
49 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
50
51 namespace llvm {  
52   
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
55 //   statement work.
56 namespace X86 {
57   enum {
58     BX_SI = 500,
59     BX_DI = 501,
60     BP_SI = 502,
61     BP_DI = 503,
62     sib   = 504,
63     sib64 = 505
64   };
65 }
66
67 extern Target TheX86_32Target, TheX86_64Target;
68
69 }
70
71 static bool translateInstruction(MCInst &target,
72                                 InternalInstruction &source,
73                                 const MCDisassembler *Dis);
74
75 X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
76                                                DisassemblerMode mode,
77                                                const MCInstrInfo *MII)
78   : MCDisassembler(STI), MII(MII), fMode(mode) {}
79
80 X86GenericDisassembler::~X86GenericDisassembler() {
81   delete MII;
82 }
83
84 /// regionReader - a callback function that wraps the readByte method from
85 ///   MemoryObject.
86 ///
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);
94 }
95
96 /// logger - a callback function that wraps the operator<< method from
97 ///   raw_ostream.
98 ///
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) {
103   if (!arg)
104     return;
105   
106   raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
107   vStream << log << "\n";
108 }  
109   
110 //
111 // Public interface for the disassembler
112 //
113
114 MCDisassembler::DecodeStatus
115 X86GenericDisassembler::getInstruction(MCInst &instr,
116                                        uint64_t &size,
117                                        const MemoryObject &region,
118                                        uint64_t address,
119                                        raw_ostream &vStream,
120                                        raw_ostream &cStream) const {
121   CommentStream = &cStream;
122
123   InternalInstruction internalInstr;
124
125   dlog_t loggerFn = logger;
126   if (&vStream == &nulls())
127     loggerFn = 0; // Disable logging completely if it's going to nulls().
128   
129   int ret = decodeInstruction(&internalInstr,
130                               regionReader,
131                               (const void*)&region,
132                               loggerFn,
133                               (void*)&vStream,
134                               (const void*)MII,
135                               address,
136                               fMode);
137
138   if (ret) {
139     size = internalInstr.readerCursor - address;
140     return Fail;
141   }
142   else {
143     size = internalInstr.length;
144     return (!translateInstruction(instr, internalInstr, this)) ?
145             Success : Fail;
146   }
147 }
148
149 //
150 // Private code that translates from struct InternalInstructions to MCInsts.
151 //
152
153 /// translateRegister - Translates an internal register to the appropriate LLVM
154 ///   register, and appends it as an operand to an MCInst.
155 ///
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[] = {
161     ALL_REGS
162     0
163   };
164 #undef ENTRY
165
166   uint8_t llvmRegnum = llvmRegnums[reg];
167   mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
168 }
169
170 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
171 /// immediate Value in the MCInst. 
172 ///
173 /// @param Value      - The immediate Value, has had any PC adjustment made by
174 ///                     the caller.
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
179 ///
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   return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
194                                        Offset, Width);
195 }
196
197 /// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
198 /// referenced by a load instruction with the base register that is the rip.
199 /// These can often be addresses in a literal pool.  The Address of the
200 /// instruction and its immediate Value are used to determine the address
201 /// being referenced in the literal pool entry.  The SymbolLookUp call back will
202 /// return a pointer to a literal 'C' string if the referenced address is an 
203 /// address into a section with 'C' string literals.
204 static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
205                                             const void *Decoder) {
206   const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
207   Dis->tryAddingPcLoadReferenceComment(Value, Address);
208 }
209
210 /// translateImmediate  - Appends an immediate operand to an MCInst.
211 ///
212 /// @param mcInst       - The MCInst to append to.
213 /// @param immediate    - The immediate value to append.
214 /// @param operand      - The operand, as stored in the descriptor table.
215 /// @param insn         - The internal instruction.
216 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
217                                const OperandSpecifier &operand,
218                                InternalInstruction &insn,
219                                const MCDisassembler *Dis) {  
220   // Sign-extend the immediate if necessary.
221
222   OperandType type = (OperandType)operand.type;
223
224   bool isBranch = false;
225   uint64_t pcrel = 0;
226   if (type == TYPE_RELv) {
227     isBranch = true;
228     pcrel = insn.startLocation +
229             insn.immediateOffset + insn.immediateSize;
230     switch (insn.displacementSize) {
231     default:
232       break;
233     case 1:
234       if(immediate & 0x80)
235         immediate |= ~(0xffull);
236       break;
237     case 2:
238       if(immediate & 0x8000)
239         immediate |= ~(0xffffull);
240       break;
241     case 4:
242       if(immediate & 0x80000000)
243         immediate |= ~(0xffffffffull);
244       break;
245     case 8:
246       break;
247     }
248   }
249   // By default sign-extend all X86 immediates based on their encoding.
250   else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
251            type == TYPE_IMM64) {
252     uint32_t Opcode = mcInst.getOpcode();
253     switch (operand.encoding) {
254     default:
255       break;
256     case ENCODING_IB:
257       // Special case those X86 instructions that use the imm8 as a set of
258       // bits, bit count, etc. and are not sign-extend.
259       if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
260           Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
261           Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
262           Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
263           Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
264           Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
265           Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
266           Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
267           Opcode != X86::VINSERTPSrr)
268         if(immediate & 0x80)
269           immediate |= ~(0xffull);
270       break;
271     case ENCODING_IW:
272       if(immediate & 0x8000)
273         immediate |= ~(0xffffull);
274       break;
275     case ENCODING_ID:
276       if(immediate & 0x80000000)
277         immediate |= ~(0xffffffffull);
278       break;
279     case ENCODING_IO:
280       break;
281     }
282   }
283
284   switch (type) {
285   case TYPE_XMM32:
286   case TYPE_XMM64:
287   case TYPE_XMM128:
288     mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
289     return;
290   case TYPE_XMM256:
291     mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
292     return;
293   case TYPE_XMM512:
294     mcInst.addOperand(MCOperand::CreateReg(X86::ZMM0 + (immediate >> 4)));
295     return;
296   case TYPE_REL8:
297     isBranch = true;
298     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
299     if(immediate & 0x80)
300       immediate |= ~(0xffull);
301     break;
302   case TYPE_REL32:
303   case TYPE_REL64:
304     isBranch = true;
305     pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
306     if(immediate & 0x80000000)
307       immediate |= ~(0xffffffffull);
308     break;
309   default:
310     // operand is 64 bits wide.  Do nothing.
311     break;
312   }
313
314   if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
315                                insn.immediateOffset, insn.immediateSize,
316                                mcInst, Dis))
317     mcInst.addOperand(MCOperand::CreateImm(immediate));
318 }
319
320 /// translateRMRegister - Translates a register stored in the R/M field of the
321 ///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
322 /// @param mcInst       - The MCInst to append to.
323 /// @param insn         - The internal instruction to extract the R/M field
324 ///                       from.
325 /// @return             - 0 on success; -1 otherwise
326 static bool translateRMRegister(MCInst &mcInst,
327                                 InternalInstruction &insn) {
328   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
329     debug("A R/M register operand may not have a SIB byte");
330     return true;
331   }
332   
333   switch (insn.eaBase) {
334   default:
335     debug("Unexpected EA base register");
336     return true;
337   case EA_BASE_NONE:
338     debug("EA_BASE_NONE for ModR/M base");
339     return true;
340 #define ENTRY(x) case EA_BASE_##x:
341   ALL_EA_BASES
342 #undef ENTRY
343     debug("A R/M register operand may not have a base; "
344           "the operand must be a register.");
345     return true;
346 #define ENTRY(x)                                                      \
347   case EA_REG_##x:                                                    \
348     mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
349   ALL_REGS
350 #undef ENTRY
351   }
352   
353   return false;
354 }
355
356 /// translateRMMemory - Translates a memory operand stored in the Mod and R/M
357 ///   fields of an internal instruction (and possibly its SIB byte) to a memory
358 ///   operand in LLVM's format, and appends it to an MCInst.
359 ///
360 /// @param mcInst       - The MCInst to append to.
361 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
362 ///                       from.
363 /// @return             - 0 on success; nonzero otherwise
364 static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
365                               const MCDisassembler *Dis) {  
366   // Addresses in an MCInst are represented as five operands:
367   //   1. basereg       (register)  The R/M base, or (if there is a SIB) the 
368   //                                SIB base
369   //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified 
370   //                                scale amount
371   //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
372   //                                the index (which is multiplied by the 
373   //                                scale amount)
374   //   4. displacement  (immediate) 0, or the displacement if there is one
375   //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
376   //                                if we have segment overrides
377   
378   MCOperand baseReg;
379   MCOperand scaleAmount;
380   MCOperand indexReg;
381   MCOperand displacement;
382   MCOperand segmentReg;
383   uint64_t pcrel = 0;
384   
385   if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
386     if (insn.sibBase != SIB_BASE_NONE) {
387       switch (insn.sibBase) {
388       default:
389         debug("Unexpected sibBase");
390         return true;
391 #define ENTRY(x)                                          \
392       case SIB_BASE_##x:                                  \
393         baseReg = MCOperand::CreateReg(X86::x); break;
394       ALL_SIB_BASES
395 #undef ENTRY
396       }
397     } else {
398       baseReg = MCOperand::CreateReg(0);
399     }
400
401     // Check whether we are handling VSIB addressing mode for GATHER.
402     // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
403     // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
404     // I don't see a way to get the correct IndexReg in readSIB:
405     //   We can tell whether it is VSIB or SIB after instruction ID is decoded,
406     //   but instruction ID may not be decoded yet when calling readSIB.
407     uint32_t Opcode = mcInst.getOpcode();
408     bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
409                        Opcode == X86::VGATHERDPDYrm ||
410                        Opcode == X86::VGATHERQPDrm ||
411                        Opcode == X86::VGATHERDPSrm ||
412                        Opcode == X86::VGATHERQPSrm ||
413                        Opcode == X86::VPGATHERDQrm ||
414                        Opcode == X86::VPGATHERDQYrm ||
415                        Opcode == X86::VPGATHERQQrm ||
416                        Opcode == X86::VPGATHERDDrm ||
417                        Opcode == X86::VPGATHERQDrm);
418     bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
419                        Opcode == X86::VGATHERDPSYrm ||
420                        Opcode == X86::VGATHERQPSYrm ||
421                        Opcode == X86::VGATHERDPDZrm ||
422                        Opcode == X86::VPGATHERDQZrm ||
423                        Opcode == X86::VPGATHERQQYrm ||
424                        Opcode == X86::VPGATHERDDYrm ||
425                        Opcode == X86::VPGATHERQDYrm);
426     bool IndexIs512 = (Opcode == X86::VGATHERQPDZrm ||
427                        Opcode == X86::VGATHERDPSZrm ||
428                        Opcode == X86::VGATHERQPSZrm ||
429                        Opcode == X86::VPGATHERQQZrm ||
430                        Opcode == X86::VPGATHERDDZrm ||
431                        Opcode == X86::VPGATHERQDZrm);
432     if (IndexIs128 || IndexIs256 || IndexIs512) {
433       unsigned IndexOffset = insn.sibIndex -
434                          (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
435       SIBIndex IndexBase = IndexIs512 ? SIB_INDEX_ZMM0 :
436                            IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
437       insn.sibIndex = (SIBIndex)(IndexBase + 
438                            (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
439     }
440
441     if (insn.sibIndex != SIB_INDEX_NONE) {
442       switch (insn.sibIndex) {
443       default:
444         debug("Unexpected sibIndex");
445         return true;
446 #define ENTRY(x)                                          \
447       case SIB_INDEX_##x:                                 \
448         indexReg = MCOperand::CreateReg(X86::x); break;
449       EA_BASES_32BIT
450       EA_BASES_64BIT
451       REGS_XMM
452       REGS_YMM
453       REGS_ZMM
454 #undef ENTRY
455       }
456     } else {
457       indexReg = MCOperand::CreateReg(0);
458     }
459     
460     scaleAmount = MCOperand::CreateImm(insn.sibScale);
461   } else {
462     switch (insn.eaBase) {
463     case EA_BASE_NONE:
464       if (insn.eaDisplacement == EA_DISP_NONE) {
465         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
466         return true;
467       }
468       if (insn.mode == MODE_64BIT){
469         pcrel = insn.startLocation +
470                 insn.displacementOffset + insn.displacementSize;
471         tryAddingPcLoadReferenceComment(insn.startLocation +
472                                         insn.displacementOffset,
473                                         insn.displacement + pcrel, Dis);
474         baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
475       }
476       else
477         baseReg = MCOperand::CreateReg(0);
478       
479       indexReg = MCOperand::CreateReg(0);
480       break;
481     case EA_BASE_BX_SI:
482       baseReg = MCOperand::CreateReg(X86::BX);
483       indexReg = MCOperand::CreateReg(X86::SI);
484       break;
485     case EA_BASE_BX_DI:
486       baseReg = MCOperand::CreateReg(X86::BX);
487       indexReg = MCOperand::CreateReg(X86::DI);
488       break;
489     case EA_BASE_BP_SI:
490       baseReg = MCOperand::CreateReg(X86::BP);
491       indexReg = MCOperand::CreateReg(X86::SI);
492       break;
493     case EA_BASE_BP_DI:
494       baseReg = MCOperand::CreateReg(X86::BP);
495       indexReg = MCOperand::CreateReg(X86::DI);
496       break;
497     default:
498       indexReg = MCOperand::CreateReg(0);
499       switch (insn.eaBase) {
500       default:
501         debug("Unexpected eaBase");
502         return true;
503         // Here, we will use the fill-ins defined above.  However,
504         //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
505         //   sib and sib64 were handled in the top-level if, so they're only
506         //   placeholders to keep the compiler happy.
507 #define ENTRY(x)                                        \
508       case EA_BASE_##x:                                 \
509         baseReg = MCOperand::CreateReg(X86::x); break; 
510       ALL_EA_BASES
511 #undef ENTRY
512 #define ENTRY(x) case EA_REG_##x:
513       ALL_REGS
514 #undef ENTRY
515         debug("A R/M memory operand may not be a register; "
516               "the base field must be a base.");
517         return true;
518       }
519     }
520     
521     scaleAmount = MCOperand::CreateImm(1);
522   }
523   
524   displacement = MCOperand::CreateImm(insn.displacement);
525   
526   static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
527     0,        // SEG_OVERRIDE_NONE
528     X86::CS,
529     X86::SS,
530     X86::DS,
531     X86::ES,
532     X86::FS,
533     X86::GS
534   };
535   
536   segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);
537   
538   mcInst.addOperand(baseReg);
539   mcInst.addOperand(scaleAmount);
540   mcInst.addOperand(indexReg);
541   if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
542                                insn.startLocation, insn.displacementOffset,
543                                insn.displacementSize, mcInst, Dis))
544     mcInst.addOperand(displacement);
545   mcInst.addOperand(segmentReg);
546   return false;
547 }
548
549 /// translateRM - Translates an operand stored in the R/M (and possibly SIB)
550 ///   byte of an instruction to LLVM form, and appends it to an MCInst.
551 ///
552 /// @param mcInst       - The MCInst to append to.
553 /// @param operand      - The operand, as stored in the descriptor table.
554 /// @param insn         - The instruction to extract Mod, R/M, and SIB fields
555 ///                       from.
556 /// @return             - 0 on success; nonzero otherwise
557 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
558                         InternalInstruction &insn, const MCDisassembler *Dis) {  
559   switch (operand.type) {
560   default:
561     debug("Unexpected type for a R/M operand");
562     return true;
563   case TYPE_R8:
564   case TYPE_R16:
565   case TYPE_R32:
566   case TYPE_R64:
567   case TYPE_Rv:
568   case TYPE_MM:
569   case TYPE_MM32:
570   case TYPE_MM64:
571   case TYPE_XMM:
572   case TYPE_XMM32:
573   case TYPE_XMM64:
574   case TYPE_XMM128:
575   case TYPE_XMM256:
576   case TYPE_XMM512:
577   case TYPE_VK1:
578   case TYPE_VK8:
579   case TYPE_VK16:
580   case TYPE_DEBUGREG:
581   case TYPE_CONTROLREG:
582     return translateRMRegister(mcInst, insn);
583   case TYPE_M:
584   case TYPE_M8:
585   case TYPE_M16:
586   case TYPE_M32:
587   case TYPE_M64:
588   case TYPE_M128:
589   case TYPE_M256:
590   case TYPE_M512:
591   case TYPE_Mv:
592   case TYPE_M32FP:
593   case TYPE_M64FP:
594   case TYPE_M80FP:
595   case TYPE_M16INT:
596   case TYPE_M32INT:
597   case TYPE_M64INT:
598   case TYPE_M1616:
599   case TYPE_M1632:
600   case TYPE_M1664:
601   case TYPE_LEA:
602     return translateRMMemory(mcInst, insn, Dis);
603   }
604 }
605   
606 /// translateFPRegister - Translates a stack position on the FPU stack to its
607 ///   LLVM form, and appends it to an MCInst.
608 ///
609 /// @param mcInst       - The MCInst to append to.
610 /// @param stackPos     - The stack position to translate.
611 /// @return             - false on success; true otherwise.
612 static bool translateFPRegister(MCInst &mcInst,
613                                uint8_t stackPos) {
614   if (stackPos >= 8) {
615     debug("Invalid FP stack position");
616     return true;
617   }
618   
619   mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));
620
621   return false;
622 }
623
624 /// translateMaskRegister - Translates a 3-bit mask register number to
625 ///   LLVM form, and appends it to an MCInst.
626 ///
627 /// @param mcInst       - The MCInst to append to.
628 /// @param maskRegNum   - Number of mask register from 0 to 7.
629 /// @return             - false on success; true otherwise.
630 static bool translateMaskRegister(MCInst &mcInst,
631                                 uint8_t maskRegNum) {
632   if (maskRegNum >= 8) {
633     debug("Invalid mask register number");
634     return true;
635   }
636
637   mcInst.addOperand(MCOperand::CreateReg(X86::K0 + maskRegNum));
638   return false;
639 }
640
641 /// translateOperand - Translates an operand stored in an internal instruction 
642 ///   to LLVM's format and appends it to an MCInst.
643 ///
644 /// @param mcInst       - The MCInst to append to.
645 /// @param operand      - The operand, as stored in the descriptor table.
646 /// @param insn         - The internal instruction.
647 /// @return             - false on success; true otherwise.
648 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
649                              InternalInstruction &insn,
650                              const MCDisassembler *Dis) {  
651   switch (operand.encoding) {
652   default:
653     debug("Unhandled operand encoding during translation");
654     return true;
655   case ENCODING_REG:
656     translateRegister(mcInst, insn.reg);
657     return false;
658   case ENCODING_WRITEMASK:
659     return translateMaskRegister(mcInst, insn.writemask);
660   case ENCODING_RM:
661     return translateRM(mcInst, operand, insn, Dis);
662   case ENCODING_CB:
663   case ENCODING_CW:
664   case ENCODING_CD:
665   case ENCODING_CP:
666   case ENCODING_CO:
667   case ENCODING_CT:
668     debug("Translation of code offsets isn't supported.");
669     return true;
670   case ENCODING_IB:
671   case ENCODING_IW:
672   case ENCODING_ID:
673   case ENCODING_IO:
674   case ENCODING_Iv:
675   case ENCODING_Ia:
676     translateImmediate(mcInst,
677                        insn.immediates[insn.numImmediatesTranslated++],
678                        operand,
679                        insn,
680                        Dis);
681     return false;
682   case ENCODING_RB:
683   case ENCODING_RW:
684   case ENCODING_RD:
685   case ENCODING_RO:
686     translateRegister(mcInst, insn.opcodeRegister);
687     return false;
688   case ENCODING_I:
689     return translateFPRegister(mcInst, insn.opcodeModifier);
690   case ENCODING_Rv:
691     translateRegister(mcInst, insn.opcodeRegister);
692     return false;
693   case ENCODING_VVVV:
694     translateRegister(mcInst, insn.vvvv);
695     return false;
696   case ENCODING_DUP:
697     return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
698                             insn, Dis);
699   }
700 }
701   
702 /// translateInstruction - Translates an internal instruction and all its
703 ///   operands to an MCInst.
704 ///
705 /// @param mcInst       - The MCInst to populate with the instruction's data.
706 /// @param insn         - The internal instruction.
707 /// @return             - false on success; true otherwise.
708 static bool translateInstruction(MCInst &mcInst,
709                                 InternalInstruction &insn,
710                                 const MCDisassembler *Dis) {  
711   if (!insn.spec) {
712     debug("Instruction has no specification");
713     return true;
714   }
715   
716   mcInst.setOpcode(insn.instructionID);
717   // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
718   // prefix bytes should be disassembled as xrelease and xacquire then set the
719   // opcode to those instead of the rep and repne opcodes.
720   if (insn.xAcquireRelease) {
721     if(mcInst.getOpcode() == X86::REP_PREFIX)
722       mcInst.setOpcode(X86::XRELEASE_PREFIX);
723     else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
724       mcInst.setOpcode(X86::XACQUIRE_PREFIX);
725   }
726   
727   int index;
728   
729   insn.numImmediatesTranslated = 0;
730   
731   for (index = 0; index < X86_MAX_OPERANDS; ++index) {
732     if (insn.operands[index].encoding != ENCODING_NONE) {
733       if (translateOperand(mcInst, insn.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 }