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