Emit symbol type information for ELF/COFF targets
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-emitter"
16 #include "X86InstrInfo.h"
17 #include "X86Subtarget.h"
18 #include "X86TargetMachine.h"
19 #include "X86Relocations.h"
20 #include "X86.h"
21 #include "llvm/PassManager.h"
22 #include "llvm/CodeGen/MachineCodeEmitter.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Function.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Target/TargetOptions.h"
30 using namespace llvm;
31
32 STATISTIC(NumEmitted, "Number of machine instructions emitted");
33
34 namespace {
35   class VISIBILITY_HIDDEN Emitter : public MachineFunctionPass {
36     const X86InstrInfo  *II;
37     const TargetData    *TD;
38     TargetMachine       &TM;
39     MachineCodeEmitter  &MCE;
40     bool Is64BitMode;
41   public:
42     explicit Emitter(TargetMachine &tm, MachineCodeEmitter &mce)
43       : II(0), TD(0), TM(tm), MCE(mce), Is64BitMode(false) {}
44     Emitter(TargetMachine &tm, MachineCodeEmitter &mce,
45             const X86InstrInfo &ii, const TargetData &td, bool is64)
46       : II(&ii), TD(&td), TM(tm), MCE(mce), Is64BitMode(is64) {}
47
48     bool runOnMachineFunction(MachineFunction &MF);
49
50     virtual const char *getPassName() const {
51       return "X86 Machine Code Emitter";
52     }
53
54     void emitInstruction(const MachineInstr &MI);
55
56   private:
57     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
58     void emitPCRelativeValue(intptr_t Address);
59     void emitGlobalAddressForCall(GlobalValue *GV, bool DoesntNeedStub);
60     void emitGlobalAddressForPtr(GlobalValue *GV, unsigned Reloc,
61                                  int Disp = 0, unsigned PCAdj = 0);
62     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
63     void emitConstPoolAddress(unsigned CPI, unsigned Reloc, int Disp = 0,
64                               unsigned PCAdj = 0);
65     void emitJumpTableAddress(unsigned JTI, unsigned Reloc, unsigned PCAdj = 0);
66
67     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
68                                unsigned PCAdj = 0);
69
70     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
71     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
72     void emitConstant(uint64_t Val, unsigned Size);
73
74     void emitMemModRMByte(const MachineInstr &MI,
75                           unsigned Op, unsigned RegOpcodeField,
76                           unsigned PCAdj = 0);
77
78     unsigned getX86RegNum(unsigned RegNo);
79     bool isX86_64ExtendedReg(const MachineOperand &MO);
80     unsigned determineREX(const MachineInstr &MI);
81   };
82 }
83
84 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
85 /// to the specified MCE object.
86 FunctionPass *llvm::createX86CodeEmitterPass(X86TargetMachine &TM,
87                                              MachineCodeEmitter &MCE) {
88   return new Emitter(TM, MCE);
89 }
90
91 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
92   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
93           MF.getTarget().getRelocationModel() != Reloc::Static) &&
94          "JIT relocation model must be set to static or default!");
95   II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
96   TD = ((X86TargetMachine&)MF.getTarget()).getTargetData();
97   Is64BitMode =
98     ((X86TargetMachine&)MF.getTarget()).getSubtarget<X86Subtarget>().is64Bit();
99
100   do {
101     MCE.startFunction(MF);
102     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
103          MBB != E; ++MBB) {
104       MCE.StartMachineBasicBlock(MBB);
105       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
106            I != E; ++I)
107         emitInstruction(*I);
108     }
109   } while (MCE.finishFunction(MF));
110
111   return false;
112 }
113
114 /// emitPCRelativeValue - Emit a PC relative address.
115 ///
116 void Emitter::emitPCRelativeValue(intptr_t Address) {
117   MCE.emitWordLE(Address-MCE.getCurrentPCValue()-4);
118 }
119
120 /// emitPCRelativeBlockAddress - This method keeps track of the information
121 /// necessary to resolve the address of this block later and emits a dummy
122 /// value.
123 ///
124 void Emitter::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
125   // Remember where this reference was and where it is to so we can
126   // deal with it later.
127   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
128                                              X86::reloc_pcrel_word, MBB));
129   MCE.emitWordLE(0);
130 }
131
132 /// emitGlobalAddressForCall - Emit the specified address to the code stream
133 /// assuming this is part of a function call, which is PC relative.
134 ///
135 void Emitter::emitGlobalAddressForCall(GlobalValue *GV, bool DoesntNeedStub) {
136   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
137                                       X86::reloc_pcrel_word, GV, 0,
138                                       DoesntNeedStub));
139   MCE.emitWordLE(0);
140 }
141
142 /// emitGlobalAddress - Emit the specified address to the code stream assuming
143 /// this is part of a "take the address of a global" instruction.
144 ///
145 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV, unsigned Reloc,
146                                       int Disp /* = 0 */,
147                                       unsigned PCAdj /* = 0 */) {
148   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
149                                              GV, PCAdj));
150   if (Reloc == X86::reloc_absolute_dword)
151     MCE.emitWordLE(0);
152   MCE.emitWordLE(Disp); // The relocated value will be added to the displacement
153 }
154
155 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
156 /// be emitted to the current location in the function, and allow it to be PC
157 /// relative.
158 void Emitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
159   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
160                                                  Reloc, ES));
161   if (Reloc == X86::reloc_absolute_dword)
162     MCE.emitWordLE(0);
163   MCE.emitWordLE(0);
164 }
165
166 /// emitConstPoolAddress - Arrange for the address of an constant pool
167 /// to be emitted to the current location in the function, and allow it to be PC
168 /// relative.
169 void Emitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
170                                    int Disp /* = 0 */,
171                                    unsigned PCAdj /* = 0 */) {
172   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
173                                                     Reloc, CPI, PCAdj));
174   if (Reloc == X86::reloc_absolute_dword)
175     MCE.emitWordLE(0);
176   MCE.emitWordLE(Disp); // The relocated value will be added to the displacement
177 }
178
179 /// emitJumpTableAddress - Arrange for the address of a jump table to
180 /// be emitted to the current location in the function, and allow it to be PC
181 /// relative.
182 void Emitter::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
183                                    unsigned PCAdj /* = 0 */) {
184   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
185                                                     Reloc, JTI, PCAdj));
186   if (Reloc == X86::reloc_absolute_dword)
187     MCE.emitWordLE(0);
188   MCE.emitWordLE(0); // The relocated value will be added to the displacement
189 }
190
191 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
192 ///
193 namespace N86 {
194   enum {
195     EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
196   };
197 }
198
199 // getX86RegNum - This function maps LLVM register identifiers to their X86
200 // specific numbering, which is used in various places encoding instructions.
201 //
202 unsigned Emitter::getX86RegNum(unsigned RegNo) {
203   switch(RegNo) {
204   case X86::RAX: case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
205   case X86::RCX: case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
206   case X86::RDX: case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
207   case X86::RBX: case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
208   case X86::RSP: case X86::ESP: case X86::SP: case X86::SPL: case X86::AH:
209     return N86::ESP;
210   case X86::RBP: case X86::EBP: case X86::BP: case X86::BPL: case X86::CH:
211     return N86::EBP;
212   case X86::RSI: case X86::ESI: case X86::SI: case X86::SIL: case X86::DH:
213     return N86::ESI;
214   case X86::RDI: case X86::EDI: case X86::DI: case X86::DIL: case X86::BH:
215     return N86::EDI;
216
217   case X86::R8:  case X86::R8D:  case X86::R8W:  case X86::R8B:
218     return N86::EAX;
219   case X86::R9:  case X86::R9D:  case X86::R9W:  case X86::R9B:
220     return N86::ECX;
221   case X86::R10: case X86::R10D: case X86::R10W: case X86::R10B:
222     return N86::EDX;
223   case X86::R11: case X86::R11D: case X86::R11W: case X86::R11B:
224     return N86::EBX;
225   case X86::R12: case X86::R12D: case X86::R12W: case X86::R12B:
226     return N86::ESP;
227   case X86::R13: case X86::R13D: case X86::R13W: case X86::R13B:
228     return N86::EBP;
229   case X86::R14: case X86::R14D: case X86::R14W: case X86::R14B:
230     return N86::ESI;
231   case X86::R15: case X86::R15D: case X86::R15W: case X86::R15B:
232     return N86::EDI;
233
234   case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
235   case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
236     return RegNo-X86::ST0;
237
238   case X86::XMM0:  case X86::XMM1:  case X86::XMM2:  case X86::XMM3:
239   case X86::XMM4:  case X86::XMM5:  case X86::XMM6:  case X86::XMM7:
240     return II->getRegisterInfo().getDwarfRegNum(RegNo) -
241            II->getRegisterInfo().getDwarfRegNum(X86::XMM0);
242   case X86::XMM8:  case X86::XMM9:  case X86::XMM10: case X86::XMM11:
243   case X86::XMM12: case X86::XMM13: case X86::XMM14: case X86::XMM15:
244     return II->getRegisterInfo().getDwarfRegNum(RegNo) -
245            II->getRegisterInfo().getDwarfRegNum(X86::XMM8);
246
247   default:
248     assert(MRegisterInfo::isVirtualRegister(RegNo) &&
249            "Unknown physical register!");
250     assert(0 && "Register allocator hasn't allocated reg correctly yet!");
251     return 0;
252   }
253 }
254
255 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
256                                       unsigned RM) {
257   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
258   return RM | (RegOpcode << 3) | (Mod << 6);
259 }
260
261 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
262   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
263 }
264
265 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
266   // SIB byte is in the same format as the ModRMByte...
267   MCE.emitByte(ModRMByte(SS, Index, Base));
268 }
269
270 void Emitter::emitConstant(uint64_t Val, unsigned Size) {
271   // Output the constant in little endian byte order...
272   for (unsigned i = 0; i != Size; ++i) {
273     MCE.emitByte(Val & 255);
274     Val >>= 8;
275   }
276 }
277
278 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
279 /// sign-extended field. 
280 static bool isDisp8(int Value) {
281   return Value == (signed char)Value;
282 }
283
284 void Emitter::emitDisplacementField(const MachineOperand *RelocOp,
285                                     int DispVal, unsigned PCAdj) {
286   // If this is a simple integer displacement that doesn't require a relocation,
287   // emit it now.
288   if (!RelocOp) {
289     emitConstant(DispVal, 4);
290     return;
291   }
292   
293   // Otherwise, this is something that requires a relocation.  Emit it as such
294   // now.
295   if (RelocOp->isGlobalAddress()) {
296     // In 64-bit static small code model, we could potentially emit absolute.
297     // But it's probably not beneficial.
298     //  89 05 00 00 00 00       mov    %eax,0(%rip)  # PC-relative
299     //  89 04 25 00 00 00 00    mov    %eax,0x0      # Absolute
300     unsigned rt= Is64BitMode ? X86::reloc_pcrel_word : X86::reloc_absolute_word;
301     emitGlobalAddressForPtr(RelocOp->getGlobal(), rt,
302                             RelocOp->getOffset(), PCAdj);
303   } else if (RelocOp->isConstantPoolIndex()) {
304     // Must be in 64-bit mode.
305     emitConstPoolAddress(RelocOp->getConstantPoolIndex(), X86::reloc_pcrel_word,
306                          RelocOp->getOffset(), PCAdj);
307   } else if (RelocOp->isJumpTableIndex()) {
308     // Must be in 64-bit mode.
309     emitJumpTableAddress(RelocOp->getJumpTableIndex(), X86::reloc_pcrel_word,
310                          PCAdj);
311   } else {
312     assert(0 && "Unknown value to relocate!");
313   }
314 }
315
316 void Emitter::emitMemModRMByte(const MachineInstr &MI,
317                                unsigned Op, unsigned RegOpcodeField,
318                                unsigned PCAdj) {
319   const MachineOperand &Op3 = MI.getOperand(Op+3);
320   int DispVal = 0;
321   const MachineOperand *DispForReloc = 0;
322   
323   // Figure out what sort of displacement we have to handle here.
324   if (Op3.isGlobalAddress()) {
325     DispForReloc = &Op3;
326   } else if (Op3.isConstantPoolIndex()) {
327     if (Is64BitMode) {
328       DispForReloc = &Op3;
329     } else {
330       DispVal += MCE.getConstantPoolEntryAddress(Op3.getConstantPoolIndex());
331       DispVal += Op3.getOffset();
332     }
333   } else if (Op3.isJumpTableIndex()) {
334     if (Is64BitMode) {
335       DispForReloc = &Op3;
336     } else {
337       DispVal += MCE.getJumpTableEntryAddress(Op3.getJumpTableIndex());
338     }
339   } else {
340     DispVal = Op3.getImm();
341   }
342
343   const MachineOperand &Base     = MI.getOperand(Op);
344   const MachineOperand &Scale    = MI.getOperand(Op+1);
345   const MachineOperand &IndexReg = MI.getOperand(Op+2);
346
347   unsigned BaseReg = Base.getReg();
348
349   // Is a SIB byte needed?
350   if (IndexReg.getReg() == 0 &&
351       (BaseReg == 0 || getX86RegNum(BaseReg) != N86::ESP)) {
352     if (BaseReg == 0) {  // Just a displacement?
353       // Emit special case [disp32] encoding
354       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
355       
356       emitDisplacementField(DispForReloc, DispVal, PCAdj);
357     } else {
358       unsigned BaseRegNo = getX86RegNum(BaseReg);
359       if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
360         // Emit simple indirect register encoding... [EAX] f.e.
361         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
362       } else if (!DispForReloc && isDisp8(DispVal)) {
363         // Emit the disp8 encoding... [REG+disp8]
364         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
365         emitConstant(DispVal, 1);
366       } else {
367         // Emit the most general non-SIB encoding: [REG+disp32]
368         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
369         emitDisplacementField(DispForReloc, DispVal, PCAdj);
370       }
371     }
372
373   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
374     assert(IndexReg.getReg() != X86::ESP &&
375            IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
376
377     bool ForceDisp32 = false;
378     bool ForceDisp8  = false;
379     if (BaseReg == 0) {
380       // If there is no base register, we emit the special case SIB byte with
381       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
382       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
383       ForceDisp32 = true;
384     } else if (DispForReloc) {
385       // Emit the normal disp32 encoding.
386       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
387       ForceDisp32 = true;
388     } else if (DispVal == 0 && getX86RegNum(BaseReg) != N86::EBP) {
389       // Emit no displacement ModR/M byte
390       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
391     } else if (isDisp8(DispVal)) {
392       // Emit the disp8 encoding...
393       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
394       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
395     } else {
396       // Emit the normal disp32 encoding...
397       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
398     }
399
400     // Calculate what the SS field value should be...
401     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
402     unsigned SS = SSTable[Scale.getImm()];
403
404     if (BaseReg == 0) {
405       // Handle the SIB byte for the case where there is no base.  The
406       // displacement has already been output.
407       assert(IndexReg.getReg() && "Index register must be specified!");
408       emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
409     } else {
410       unsigned BaseRegNo = getX86RegNum(BaseReg);
411       unsigned IndexRegNo;
412       if (IndexReg.getReg())
413         IndexRegNo = getX86RegNum(IndexReg.getReg());
414       else
415         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
416       emitSIBByte(SS, IndexRegNo, BaseRegNo);
417     }
418
419     // Do we need to output a displacement?
420     if (ForceDisp8) {
421       emitConstant(DispVal, 1);
422     } else if (DispVal != 0 || ForceDisp32) {
423       emitDisplacementField(DispForReloc, DispVal, PCAdj);
424     }
425   }
426 }
427
428 static unsigned sizeOfImm(const TargetInstrDescriptor *Desc) {
429   switch (Desc->TSFlags & X86II::ImmMask) {
430   case X86II::Imm8:   return 1;
431   case X86II::Imm16:  return 2;
432   case X86II::Imm32:  return 4;
433   case X86II::Imm64:  return 8;
434   default: assert(0 && "Immediate size not set!");
435     return 0;
436   }
437 }
438
439 /// isX86_64ExtendedReg - Is the MachineOperand a x86-64 extended register?
440 /// e.g. r8, xmm8, etc.
441 bool Emitter::isX86_64ExtendedReg(const MachineOperand &MO) {
442   if (!MO.isRegister()) return false;
443   unsigned RegNo = MO.getReg();
444   int DWNum = II->getRegisterInfo().getDwarfRegNum(RegNo);
445   if (DWNum >= II->getRegisterInfo().getDwarfRegNum(X86::R8) &&
446       DWNum <= II->getRegisterInfo().getDwarfRegNum(X86::R15))
447     return true;
448   if (DWNum >= II->getRegisterInfo().getDwarfRegNum(X86::XMM8) &&
449       DWNum <= II->getRegisterInfo().getDwarfRegNum(X86::XMM15))
450     return true;
451   return false;
452 }
453
454 inline static bool isX86_64TruncToByte(unsigned oc) {
455   return (oc == X86::TRUNC_64to8 || oc == X86::TRUNC_32to8 ||
456           oc == X86::TRUNC_16to8);
457 }
458
459
460 inline static bool isX86_64NonExtLowByteReg(unsigned reg) {
461   return (reg == X86::SPL || reg == X86::BPL ||
462           reg == X86::SIL || reg == X86::DIL);
463 }
464
465 /// determineREX - Determine if the MachineInstr has to be encoded with a X86-64
466 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
467 /// size, and 3) use of X86-64 extended registers.
468 unsigned Emitter::determineREX(const MachineInstr &MI) {
469   unsigned REX = 0;
470   const TargetInstrDescriptor *Desc = MI.getInstrDescriptor();
471   unsigned Opcode = Desc->Opcode;
472
473   // Pseudo instructions do not need REX prefix byte.
474   if ((Desc->TSFlags & X86II::FormMask) == X86II::Pseudo)
475     return 0;
476   if (Desc->TSFlags & X86II::REX_W)
477     REX |= 1 << 3;
478
479   unsigned NumOps = Desc->numOperands;
480   if (NumOps) {
481     bool isTwoAddr = NumOps > 1 &&
482       Desc->getOperandConstraint(1, TOI::TIED_TO) != -1;
483
484     // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
485     bool isTrunc8 = isX86_64TruncToByte(Opcode);
486     unsigned i = isTwoAddr ? 1 : 0;
487     for (unsigned e = NumOps; i != e; ++i) {
488       const MachineOperand& MO = MI.getOperand(i);
489       if (MO.isRegister()) {
490         unsigned Reg = MO.getReg();
491         // Trunc to byte are actually movb. The real source operand is the low
492         // byte of the register.
493         if (isTrunc8 && i == 1)
494           Reg = getX86SubSuperRegister(Reg, MVT::i8);
495         if (isX86_64NonExtLowByteReg(Reg))
496           REX |= 0x40;
497       }
498     }
499
500     switch (Desc->TSFlags & X86II::FormMask) {
501     case X86II::MRMInitReg:
502       if (isX86_64ExtendedReg(MI.getOperand(0)))
503         REX |= (1 << 0) | (1 << 2);
504       break;
505     case X86II::MRMSrcReg: {
506       if (isX86_64ExtendedReg(MI.getOperand(0)))
507         REX |= 1 << 2;
508       i = isTwoAddr ? 2 : 1;
509       for (unsigned e = NumOps; i != e; ++i) {
510         const MachineOperand& MO = MI.getOperand(i);
511         if (isX86_64ExtendedReg(MO))
512           REX |= 1 << 0;
513       }
514       break;
515     }
516     case X86II::MRMSrcMem: {
517       if (isX86_64ExtendedReg(MI.getOperand(0)))
518         REX |= 1 << 2;
519       unsigned Bit = 0;
520       i = isTwoAddr ? 2 : 1;
521       for (; i != NumOps; ++i) {
522         const MachineOperand& MO = MI.getOperand(i);
523         if (MO.isRegister()) {
524           if (isX86_64ExtendedReg(MO))
525             REX |= 1 << Bit;
526           Bit++;
527         }
528       }
529       break;
530     }
531     case X86II::MRM0m: case X86II::MRM1m:
532     case X86II::MRM2m: case X86II::MRM3m:
533     case X86II::MRM4m: case X86II::MRM5m:
534     case X86II::MRM6m: case X86II::MRM7m:
535     case X86II::MRMDestMem: {
536       unsigned e = isTwoAddr ? 5 : 4;
537       i = isTwoAddr ? 1 : 0;
538       if (NumOps > e && isX86_64ExtendedReg(MI.getOperand(e)))
539         REX |= 1 << 2;
540       unsigned Bit = 0;
541       for (; i != e; ++i) {
542         const MachineOperand& MO = MI.getOperand(i);
543         if (MO.isRegister()) {
544           if (isX86_64ExtendedReg(MO))
545             REX |= 1 << Bit;
546           Bit++;
547         }
548       }
549       break;
550     }
551     default: {
552       if (isX86_64ExtendedReg(MI.getOperand(0)))
553         REX |= 1 << 0;
554       i = isTwoAddr ? 2 : 1;
555       for (unsigned e = NumOps; i != e; ++i) {
556         const MachineOperand& MO = MI.getOperand(i);
557         if (isX86_64ExtendedReg(MO))
558           REX |= 1 << 2;
559       }
560       break;
561     }
562     }
563   }
564   return REX;
565 }
566
567 void Emitter::emitInstruction(const MachineInstr &MI) {
568   NumEmitted++;  // Keep track of the # of mi's emitted
569
570   const TargetInstrDescriptor *Desc = MI.getInstrDescriptor();
571   unsigned Opcode = Desc->Opcode;
572
573   // Emit the repeat opcode prefix as needed.
574   if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
575
576   // Emit the operand size opcode prefix as needed.
577   if (Desc->TSFlags & X86II::OpSize) MCE.emitByte(0x66);
578
579   // Emit the address size opcode prefix as needed.
580   if (Desc->TSFlags & X86II::AdSize) MCE.emitByte(0x67);
581
582   bool Need0FPrefix = false;
583   switch (Desc->TSFlags & X86II::Op0Mask) {
584   case X86II::TB:
585     Need0FPrefix = true;   // Two-byte opcode prefix
586     break;
587   case X86II::REP: break; // already handled.
588   case X86II::XS:   // F3 0F
589     MCE.emitByte(0xF3);
590     Need0FPrefix = true;
591     break;
592   case X86II::XD:   // F2 0F
593     MCE.emitByte(0xF2);
594     Need0FPrefix = true;
595     break;
596   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
597   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
598     MCE.emitByte(0xD8+
599                  (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
600                                    >> X86II::Op0Shift));
601     break; // Two-byte opcode prefix
602   default: assert(0 && "Invalid prefix!");
603   case 0: break;  // No prefix!
604   }
605
606   if (Is64BitMode) {
607     // REX prefix
608     unsigned REX = determineREX(MI);
609     if (REX)
610       MCE.emitByte(0x40 | REX);
611   }
612
613   // 0x0F escape code must be emitted just before the opcode.
614   if (Need0FPrefix)
615     MCE.emitByte(0x0F);
616
617   // If this is a two-address instruction, skip one of the register operands.
618   unsigned NumOps = Desc->numOperands;
619   unsigned CurOp = 0;
620   if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
621     CurOp++;
622
623   unsigned char BaseOpcode = II->getBaseOpcodeFor(Desc);
624   switch (Desc->TSFlags & X86II::FormMask) {
625   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
626   case X86II::Pseudo:
627 #ifndef NDEBUG
628     switch (Opcode) {
629     default: 
630       assert(0 && "psuedo instructions should be removed before code emission");
631     case TargetInstrInfo::INLINEASM:
632       assert(0 && "JIT does not support inline asm!\n");
633     case X86::IMPLICIT_USE:
634     case X86::IMPLICIT_DEF:
635     case X86::IMPLICIT_DEF_GR8:
636     case X86::IMPLICIT_DEF_GR16:
637     case X86::IMPLICIT_DEF_GR32:
638     case X86::IMPLICIT_DEF_GR64:
639     case X86::IMPLICIT_DEF_FR32:
640     case X86::IMPLICIT_DEF_FR64:
641     case X86::IMPLICIT_DEF_VR64:
642     case X86::IMPLICIT_DEF_VR128:
643     case X86::FP_REG_KILL:
644       break;
645     }
646 #endif
647     CurOp = NumOps;
648     break;
649
650   case X86II::RawFrm:
651     MCE.emitByte(BaseOpcode);
652     if (CurOp != NumOps) {
653       const MachineOperand &MO = MI.getOperand(CurOp++);
654       if (MO.isMachineBasicBlock()) {
655         emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
656       } else if (MO.isGlobalAddress()) {
657         bool isTailCall = Opcode == X86::TAILJMPd ||
658                           Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
659         emitGlobalAddressForCall(MO.getGlobal(), !isTailCall);
660       } else if (MO.isExternalSymbol()) {
661         emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
662       } else if (MO.isImmediate()) {
663         emitConstant(MO.getImm(), sizeOfImm(Desc));
664       } else {
665         assert(0 && "Unknown RawFrm operand!");
666       }
667     }
668     break;
669
670   case X86II::AddRegFrm:
671     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
672     
673     if (CurOp != NumOps) {
674       const MachineOperand &MO1 = MI.getOperand(CurOp++);
675       unsigned Size = sizeOfImm(Desc);
676       if (MO1.isImmediate())
677         emitConstant(MO1.getImm(), Size);
678       else {
679         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word : X86::reloc_absolute_word;
680         if (Opcode == X86::MOV64ri)
681           rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
682         if (MO1.isGlobalAddress())
683           emitGlobalAddressForPtr(MO1.getGlobal(), rt, MO1.getOffset());
684         else if (MO1.isExternalSymbol())
685           emitExternalSymbolAddress(MO1.getSymbolName(), rt);
686         else if (MO1.isConstantPoolIndex())
687           emitConstPoolAddress(MO1.getConstantPoolIndex(), rt);
688         else if (MO1.isJumpTableIndex())
689           emitJumpTableAddress(MO1.getJumpTableIndex(), rt);
690       }
691     }
692     break;
693
694   case X86II::MRMDestReg: {
695     MCE.emitByte(BaseOpcode);
696     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
697                      getX86RegNum(MI.getOperand(CurOp+1).getReg()));
698     CurOp += 2;
699     if (CurOp != NumOps)
700       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
701     break;
702   }
703   case X86II::MRMDestMem: {
704     MCE.emitByte(BaseOpcode);
705     emitMemModRMByte(MI, CurOp, getX86RegNum(MI.getOperand(CurOp+4).getReg()));
706     CurOp += 5;
707     if (CurOp != NumOps)
708       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
709     break;
710   }
711
712   case X86II::MRMSrcReg:
713     MCE.emitByte(BaseOpcode);
714     emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
715                      getX86RegNum(MI.getOperand(CurOp).getReg()));
716     CurOp += 2;
717     if (CurOp != NumOps)
718       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
719     break;
720
721   case X86II::MRMSrcMem: {
722     unsigned PCAdj = (CurOp+5 != NumOps) ? sizeOfImm(Desc) : 0;
723
724     MCE.emitByte(BaseOpcode);
725     emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
726                      PCAdj);
727     CurOp += 5;
728     if (CurOp != NumOps)
729       emitConstant(MI.getOperand(CurOp++).getImm(), sizeOfImm(Desc));
730     break;
731   }
732
733   case X86II::MRM0r: case X86II::MRM1r:
734   case X86II::MRM2r: case X86II::MRM3r:
735   case X86II::MRM4r: case X86II::MRM5r:
736   case X86II::MRM6r: case X86II::MRM7r:
737     MCE.emitByte(BaseOpcode);
738     emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
739                      (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
740
741     if (CurOp != NumOps) {
742       const MachineOperand &MO1 = MI.getOperand(CurOp++);
743       unsigned Size = sizeOfImm(Desc);
744       if (MO1.isImmediate())
745         emitConstant(MO1.getImm(), Size);
746       else {
747         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
748           : X86::reloc_absolute_word;
749         if (Opcode == X86::MOV64ri32)
750           rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
751         if (MO1.isGlobalAddress())
752           emitGlobalAddressForPtr(MO1.getGlobal(), rt, MO1.getOffset());
753         else if (MO1.isExternalSymbol())
754           emitExternalSymbolAddress(MO1.getSymbolName(), rt);
755         else if (MO1.isConstantPoolIndex())
756           emitConstPoolAddress(MO1.getConstantPoolIndex(), rt);
757         else if (MO1.isJumpTableIndex())
758           emitJumpTableAddress(MO1.getJumpTableIndex(), rt);
759       }
760     }
761     break;
762
763   case X86II::MRM0m: case X86II::MRM1m:
764   case X86II::MRM2m: case X86II::MRM3m:
765   case X86II::MRM4m: case X86II::MRM5m:
766   case X86II::MRM6m: case X86II::MRM7m: {
767     unsigned PCAdj = (CurOp+4 != NumOps) ?
768       (MI.getOperand(CurOp+4).isImmediate() ? sizeOfImm(Desc) : 4) : 0;
769
770     MCE.emitByte(BaseOpcode);
771     emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
772                      PCAdj);
773     CurOp += 4;
774
775     if (CurOp != NumOps) {
776       const MachineOperand &MO = MI.getOperand(CurOp++);
777       unsigned Size = sizeOfImm(Desc);
778       if (MO.isImmediate())
779         emitConstant(MO.getImm(), Size);
780       else {
781         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
782           : X86::reloc_absolute_word;
783         if (Opcode == X86::MOV64mi32)
784           rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
785         if (MO.isGlobalAddress())
786           emitGlobalAddressForPtr(MO.getGlobal(), rt, MO.getOffset());
787         else if (MO.isExternalSymbol())
788           emitExternalSymbolAddress(MO.getSymbolName(), rt);
789         else if (MO.isConstantPoolIndex())
790           emitConstPoolAddress(MO.getConstantPoolIndex(), rt);
791         else if (MO.isJumpTableIndex())
792           emitJumpTableAddress(MO.getJumpTableIndex(), rt);
793       }
794     }
795     break;
796   }
797
798   case X86II::MRMInitReg:
799     MCE.emitByte(BaseOpcode);
800     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
801     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
802                      getX86RegNum(MI.getOperand(CurOp).getReg()));
803     ++CurOp;
804     break;
805   }
806
807   assert((Desc->Flags & M_VARIABLE_OPS) != 0 ||
808          CurOp == NumOps && "Unknown encoding!");
809 }