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