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