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