Revert r110396 to fix buildbots.
[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/LLVMContext.h"
23 #include "llvm/PassManager.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/MC/MCCodeEmitter.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
38 using namespace llvm;
39
40 STATISTIC(NumEmitted, "Number of machine instructions emitted");
41
42 namespace {
43   template<class CodeEmitter>
44   class Emitter : public MachineFunctionPass {
45     const X86InstrInfo  *II;
46     const TargetData    *TD;
47     X86TargetMachine    &TM;
48     CodeEmitter         &MCE;
49     MachineModuleInfo   *MMI;
50     intptr_t PICBaseOffset;
51     bool Is64BitMode;
52     bool IsPIC;
53   public:
54     static char ID;
55     explicit Emitter(X86TargetMachine &tm, CodeEmitter &mce)
56       : MachineFunctionPass(&ID), II(0), TD(0), TM(tm), 
57       MCE(mce), PICBaseOffset(0), Is64BitMode(false),
58       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
59     Emitter(X86TargetMachine &tm, CodeEmitter &mce,
60             const X86InstrInfo &ii, const TargetData &td, bool is64)
61       : MachineFunctionPass(&ID), II(&ii), TD(&td), TM(tm), 
62       MCE(mce), PICBaseOffset(0), Is64BitMode(is64),
63       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
64
65     bool runOnMachineFunction(MachineFunction &MF);
66
67     virtual const char *getPassName() const {
68       return "X86 Machine Code Emitter";
69     }
70
71     void emitInstruction(const MachineInstr &MI,
72                          const TargetInstrDesc *Desc);
73     
74     void getAnalysisUsage(AnalysisUsage &AU) const {
75       AU.setPreservesAll();
76       AU.addRequired<MachineModuleInfo>();
77       MachineFunctionPass::getAnalysisUsage(AU);
78     }
79
80   private:
81     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
82     void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
83                            intptr_t Disp = 0, intptr_t PCAdj = 0,
84                            bool Indirect = false);
85     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
86     void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
87                               intptr_t PCAdj = 0);
88     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
89                               intptr_t PCAdj = 0);
90
91     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
92                                intptr_t Adj = 0, bool IsPCRel = true);
93
94     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
95     void emitRegModRMByte(unsigned RegOpcodeField);
96     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
97     void emitConstant(uint64_t Val, unsigned Size);
98
99     void emitMemModRMByte(const MachineInstr &MI,
100                           unsigned Op, unsigned RegOpcodeField,
101                           intptr_t PCAdj = 0);
102
103     unsigned getX86RegNum(unsigned RegNo) const;
104   };
105
106 template<class CodeEmitter>
107   char Emitter<CodeEmitter>::ID = 0;
108 } // end anonymous namespace.
109
110 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
111 /// to the specified templated MachineCodeEmitter object.
112 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
113                                                 JITCodeEmitter &JCE) {
114   return new Emitter<JITCodeEmitter>(TM, JCE);
115 }
116
117 template<class CodeEmitter>
118 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
119   MMI = &getAnalysis<MachineModuleInfo>();
120   MCE.setModuleInfo(MMI);
121   
122   II = TM.getInstrInfo();
123   TD = TM.getTargetData();
124   Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
125   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
126   
127   do {
128     DEBUG(dbgs() << "JITTing function '" 
129           << MF.getFunction()->getName() << "'\n");
130     MCE.startFunction(MF);
131     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
132          MBB != E; ++MBB) {
133       MCE.StartMachineBasicBlock(MBB);
134       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
135            I != E; ++I) {
136         const TargetInstrDesc &Desc = I->getDesc();
137         emitInstruction(*I, &Desc);
138         // MOVPC32r is basically a call plus a pop instruction.
139         if (Desc.getOpcode() == X86::MOVPC32r)
140           emitInstruction(*I, &II->get(X86::POP32r));
141         ++NumEmitted;  // Keep track of the # of mi's emitted
142       }
143     }
144   } while (MCE.finishFunction(MF));
145
146   return false;
147 }
148
149 /// determineREX - Determine if the MachineInstr has to be encoded with a X86-64
150 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
151 /// size, and 3) use of X86-64 extended registers.
152 static unsigned determineREX(const MachineInstr &MI) {
153   unsigned REX = 0;
154   const TargetInstrDesc &Desc = MI.getDesc();
155   
156   // Pseudo instructions do not need REX prefix byte.
157   if ((Desc.TSFlags & X86II::FormMask) == X86II::Pseudo)
158     return 0;
159   if (Desc.TSFlags & X86II::REX_W)
160     REX |= 1 << 3;
161   
162   unsigned NumOps = Desc.getNumOperands();
163   if (NumOps) {
164     bool isTwoAddr = NumOps > 1 &&
165     Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
166     
167     // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
168     unsigned i = isTwoAddr ? 1 : 0;
169     for (unsigned e = NumOps; i != e; ++i) {
170       const MachineOperand& MO = MI.getOperand(i);
171       if (MO.isReg()) {
172         unsigned Reg = MO.getReg();
173         if (X86InstrInfo::isX86_64NonExtLowByteReg(Reg))
174           REX |= 0x40;
175       }
176     }
177     
178     switch (Desc.TSFlags & X86II::FormMask) {
179       case X86II::MRMInitReg:
180         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
181           REX |= (1 << 0) | (1 << 2);
182         break;
183       case X86II::MRMSrcReg: {
184         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
185           REX |= 1 << 2;
186         i = isTwoAddr ? 2 : 1;
187         for (unsigned e = NumOps; i != e; ++i) {
188           const MachineOperand& MO = MI.getOperand(i);
189           if (X86InstrInfo::isX86_64ExtendedReg(MO))
190             REX |= 1 << 0;
191         }
192         break;
193       }
194       case X86II::MRMSrcMem: {
195         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
196           REX |= 1 << 2;
197         unsigned Bit = 0;
198         i = isTwoAddr ? 2 : 1;
199         for (; i != NumOps; ++i) {
200           const MachineOperand& MO = MI.getOperand(i);
201           if (MO.isReg()) {
202             if (X86InstrInfo::isX86_64ExtendedReg(MO))
203               REX |= 1 << Bit;
204             Bit++;
205           }
206         }
207         break;
208       }
209       case X86II::MRM0m: case X86II::MRM1m:
210       case X86II::MRM2m: case X86II::MRM3m:
211       case X86II::MRM4m: case X86II::MRM5m:
212       case X86II::MRM6m: case X86II::MRM7m:
213       case X86II::MRMDestMem: {
214         unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
215         i = isTwoAddr ? 1 : 0;
216         if (NumOps > e && X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e)))
217           REX |= 1 << 2;
218         unsigned Bit = 0;
219         for (; i != e; ++i) {
220           const MachineOperand& MO = MI.getOperand(i);
221           if (MO.isReg()) {
222             if (X86InstrInfo::isX86_64ExtendedReg(MO))
223               REX |= 1 << Bit;
224             Bit++;
225           }
226         }
227         break;
228       }
229       default: {
230         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
231           REX |= 1 << 0;
232         i = isTwoAddr ? 2 : 1;
233         for (unsigned e = NumOps; i != e; ++i) {
234           const MachineOperand& MO = MI.getOperand(i);
235           if (X86InstrInfo::isX86_64ExtendedReg(MO))
236             REX |= 1 << 2;
237         }
238         break;
239       }
240     }
241   }
242   return REX;
243 }
244
245
246 /// emitPCRelativeBlockAddress - This method keeps track of the information
247 /// necessary to resolve the address of this block later and emits a dummy
248 /// value.
249 ///
250 template<class CodeEmitter>
251 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
252   // Remember where this reference was and where it is to so we can
253   // deal with it later.
254   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
255                                              X86::reloc_pcrel_word, MBB));
256   MCE.emitWordLE(0);
257 }
258
259 /// emitGlobalAddress - Emit the specified address to the code stream assuming
260 /// this is part of a "take the address of a global" instruction.
261 ///
262 template<class CodeEmitter>
263 void Emitter<CodeEmitter>::emitGlobalAddress(const GlobalValue *GV,
264                                 unsigned Reloc,
265                                 intptr_t Disp /* = 0 */,
266                                 intptr_t PCAdj /* = 0 */,
267                                 bool Indirect /* = false */) {
268   intptr_t RelocCST = Disp;
269   if (Reloc == X86::reloc_picrel_word)
270     RelocCST = PICBaseOffset;
271   else if (Reloc == X86::reloc_pcrel_word)
272     RelocCST = PCAdj;
273   MachineRelocation MR = Indirect
274     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
275                                            const_cast<GlobalValue *>(GV),
276                                            RelocCST, false)
277     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
278                                const_cast<GlobalValue *>(GV), RelocCST, false);
279   MCE.addRelocation(MR);
280   // The relocated value will be added to the displacement
281   if (Reloc == X86::reloc_absolute_dword)
282     MCE.emitDWordLE(Disp);
283   else
284     MCE.emitWordLE((int32_t)Disp);
285 }
286
287 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
288 /// be emitted to the current location in the function, and allow it to be PC
289 /// relative.
290 template<class CodeEmitter>
291 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
292                                                      unsigned Reloc) {
293   intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
294
295   // X86 never needs stubs because instruction selection will always pick
296   // an instruction sequence that is large enough to hold any address
297   // to a symbol.
298   // (see X86ISelLowering.cpp, near 2039: X86TargetLowering::LowerCall)
299   bool NeedStub = false;
300   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
301                                                  Reloc, ES, RelocCST,
302                                                  0, NeedStub));
303   if (Reloc == X86::reloc_absolute_dword)
304     MCE.emitDWordLE(0);
305   else
306     MCE.emitWordLE(0);
307 }
308
309 /// emitConstPoolAddress - Arrange for the address of an constant pool
310 /// to be emitted to the current location in the function, and allow it to be PC
311 /// relative.
312 template<class CodeEmitter>
313 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
314                                    intptr_t Disp /* = 0 */,
315                                    intptr_t PCAdj /* = 0 */) {
316   intptr_t RelocCST = 0;
317   if (Reloc == X86::reloc_picrel_word)
318     RelocCST = PICBaseOffset;
319   else if (Reloc == X86::reloc_pcrel_word)
320     RelocCST = PCAdj;
321   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
322                                                     Reloc, CPI, RelocCST));
323   // The relocated value will be added to the displacement
324   if (Reloc == X86::reloc_absolute_dword)
325     MCE.emitDWordLE(Disp);
326   else
327     MCE.emitWordLE((int32_t)Disp);
328 }
329
330 /// emitJumpTableAddress - Arrange for the address of a jump table to
331 /// be emitted to the current location in the function, and allow it to be PC
332 /// relative.
333 template<class CodeEmitter>
334 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
335                                    intptr_t PCAdj /* = 0 */) {
336   intptr_t RelocCST = 0;
337   if (Reloc == X86::reloc_picrel_word)
338     RelocCST = PICBaseOffset;
339   else if (Reloc == X86::reloc_pcrel_word)
340     RelocCST = PCAdj;
341   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
342                                                     Reloc, JTI, RelocCST));
343   // The relocated value will be added to the displacement
344   if (Reloc == X86::reloc_absolute_dword)
345     MCE.emitDWordLE(0);
346   else
347     MCE.emitWordLE(0);
348 }
349
350 template<class CodeEmitter>
351 unsigned Emitter<CodeEmitter>::getX86RegNum(unsigned RegNo) const {
352   return X86RegisterInfo::getX86RegNum(RegNo);
353 }
354
355 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
356                                       unsigned RM) {
357   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
358   return RM | (RegOpcode << 3) | (Mod << 6);
359 }
360
361 template<class CodeEmitter>
362 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
363                                             unsigned RegOpcodeFld){
364   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
365 }
366
367 template<class CodeEmitter>
368 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
369   MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
370 }
371
372 template<class CodeEmitter>
373 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS, 
374                                        unsigned Index,
375                                        unsigned Base) {
376   // SIB byte is in the same format as the ModRMByte...
377   MCE.emitByte(ModRMByte(SS, Index, Base));
378 }
379
380 template<class CodeEmitter>
381 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
382   // Output the constant in little endian byte order...
383   for (unsigned i = 0; i != Size; ++i) {
384     MCE.emitByte(Val & 255);
385     Val >>= 8;
386   }
387 }
388
389 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
390 /// sign-extended field. 
391 static bool isDisp8(int Value) {
392   return Value == (signed char)Value;
393 }
394
395 static bool gvNeedsNonLazyPtr(const MachineOperand &GVOp,
396                               const TargetMachine &TM) {
397   // For Darwin-64, simulate the linktime GOT by using the same non-lazy-pointer
398   // mechanism as 32-bit mode.
399   if (TM.getSubtarget<X86Subtarget>().is64Bit() && 
400       !TM.getSubtarget<X86Subtarget>().isTargetDarwin())
401     return false;
402   
403   // Return true if this is a reference to a stub containing the address of the
404   // global, not the global itself.
405   return isGlobalStubReference(GVOp.getTargetFlags());
406 }
407
408 template<class CodeEmitter>
409 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
410                                                  int DispVal,
411                                                  intptr_t Adj /* = 0 */,
412                                                  bool IsPCRel /* = true */) {
413   // If this is a simple integer displacement that doesn't require a relocation,
414   // emit it now.
415   if (!RelocOp) {
416     emitConstant(DispVal, 4);
417     return;
418   }
419
420   // Otherwise, this is something that requires a relocation.  Emit it as such
421   // now.
422   unsigned RelocType = Is64BitMode ?
423     (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
424     : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
425   if (RelocOp->isGlobal()) {
426     // In 64-bit static small code model, we could potentially emit absolute.
427     // But it's probably not beneficial. If the MCE supports using RIP directly
428     // do it, otherwise fallback to absolute (this is determined by IsPCRel). 
429     //  89 05 00 00 00 00     mov    %eax,0(%rip)  # PC-relative
430     //  89 04 25 00 00 00 00  mov    %eax,0x0      # Absolute
431     bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
432     emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
433                       Adj, Indirect);
434   } else if (RelocOp->isSymbol()) {
435     emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
436   } else if (RelocOp->isCPI()) {
437     emitConstPoolAddress(RelocOp->getIndex(), RelocType,
438                          RelocOp->getOffset(), Adj);
439   } else {
440     assert(RelocOp->isJTI() && "Unexpected machine operand!");
441     emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
442   }
443 }
444
445 template<class CodeEmitter>
446 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
447                                             unsigned Op,unsigned RegOpcodeField,
448                                             intptr_t PCAdj) {
449   const MachineOperand &Op3 = MI.getOperand(Op+3);
450   int DispVal = 0;
451   const MachineOperand *DispForReloc = 0;
452   
453   // Figure out what sort of displacement we have to handle here.
454   if (Op3.isGlobal()) {
455     DispForReloc = &Op3;
456   } else if (Op3.isSymbol()) {
457     DispForReloc = &Op3;
458   } else if (Op3.isCPI()) {
459     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
460       DispForReloc = &Op3;
461     } else {
462       DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
463       DispVal += Op3.getOffset();
464     }
465   } else if (Op3.isJTI()) {
466     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
467       DispForReloc = &Op3;
468     } else {
469       DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
470     }
471   } else {
472     DispVal = Op3.getImm();
473   }
474
475   const MachineOperand &Base     = MI.getOperand(Op);
476   const MachineOperand &Scale    = MI.getOperand(Op+1);
477   const MachineOperand &IndexReg = MI.getOperand(Op+2);
478
479   unsigned BaseReg = Base.getReg();
480   
481   // Handle %rip relative addressing.
482   if (BaseReg == X86::RIP ||
483       (Is64BitMode && DispForReloc)) { // [disp32+RIP] in X86-64 mode
484     assert(IndexReg.getReg() == 0 && Is64BitMode &&
485            "Invalid rip-relative address");
486     MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
487     emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
488     return;
489   }
490
491   // Indicate that the displacement will use an pcrel or absolute reference
492   // by default. MCEs able to resolve addresses on-the-fly use pcrel by default
493   // while others, unless explicit asked to use RIP, use absolute references.
494   bool IsPCRel = MCE.earlyResolveAddresses() ? true : false;
495
496   // Is a SIB byte needed?
497   // If no BaseReg, issue a RIP relative instruction only if the MCE can 
498   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
499   // 2-7) and absolute references.
500   unsigned BaseRegNo = -1U;
501   if (BaseReg != 0 && BaseReg != X86::RIP)
502     BaseRegNo = getX86RegNum(BaseReg);
503
504   if (// The SIB byte must be used if there is an index register.
505       IndexReg.getReg() == 0 && 
506       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
507       // encode to an R/M value of 4, which indicates that a SIB byte is
508       // present.
509       BaseRegNo != N86::ESP &&
510       // If there is no base register and we're in 64-bit mode, we need a SIB
511       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
512       (!Is64BitMode || BaseReg != 0)) {
513     if (BaseReg == 0 ||          // [disp32]     in X86-32 mode
514         BaseReg == X86::RIP) {   // [disp32+RIP] in X86-64 mode
515       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
516       emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
517       return;
518     }
519     
520     // If the base is not EBP/ESP and there is no displacement, use simple
521     // indirect register encoding, this handles addresses like [EAX].  The
522     // encoding for [EBP] with no displacement means [disp32] so we handle it
523     // by emitting a displacement of 0 below.
524     if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
525       MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
526       return;
527     }
528     
529     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
530     if (!DispForReloc && isDisp8(DispVal)) {
531       MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
532       emitConstant(DispVal, 1);
533       return;
534     }
535     
536     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
537     MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
538     emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
539     return;
540   }
541   
542   // Otherwise we need a SIB byte, so start by outputting the ModR/M byte first.
543   assert(IndexReg.getReg() != X86::ESP &&
544          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
545
546   bool ForceDisp32 = false;
547   bool ForceDisp8  = false;
548   if (BaseReg == 0) {
549     // If there is no base register, we emit the special case SIB byte with
550     // MOD=0, BASE=4, to JUST get the index, scale, and displacement.
551     MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
552     ForceDisp32 = true;
553   } else if (DispForReloc) {
554     // Emit the normal disp32 encoding.
555     MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
556     ForceDisp32 = true;
557   } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
558     // Emit no displacement ModR/M byte
559     MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
560   } else if (isDisp8(DispVal)) {
561     // Emit the disp8 encoding...
562     MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
563     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
564   } else {
565     // Emit the normal disp32 encoding...
566     MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
567   }
568
569   // Calculate what the SS field value should be...
570   static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
571   unsigned SS = SSTable[Scale.getImm()];
572
573   if (BaseReg == 0) {
574     // Handle the SIB byte for the case where there is no base, see Intel 
575     // Manual 2A, table 2-7. The displacement has already been output.
576     unsigned IndexRegNo;
577     if (IndexReg.getReg())
578       IndexRegNo = getX86RegNum(IndexReg.getReg());
579     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
580       IndexRegNo = 4;
581     emitSIBByte(SS, IndexRegNo, 5);
582   } else {
583     unsigned BaseRegNo = getX86RegNum(BaseReg);
584     unsigned IndexRegNo;
585     if (IndexReg.getReg())
586       IndexRegNo = getX86RegNum(IndexReg.getReg());
587     else
588       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
589     emitSIBByte(SS, IndexRegNo, BaseRegNo);
590   }
591
592   // Do we need to output a displacement?
593   if (ForceDisp8) {
594     emitConstant(DispVal, 1);
595   } else if (DispVal != 0 || ForceDisp32) {
596     emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
597   }
598 }
599
600 template<class CodeEmitter>
601 void Emitter<CodeEmitter>::emitInstruction(const MachineInstr &MI,
602                                            const TargetInstrDesc *Desc) {
603   DEBUG(dbgs() << MI);
604
605   MCE.processDebugLoc(MI.getDebugLoc(), true);
606
607   unsigned Opcode = Desc->Opcode;
608
609   // Emit the lock opcode prefix as needed.
610   if (Desc->TSFlags & X86II::LOCK)
611     MCE.emitByte(0xF0);
612
613   // Emit segment override opcode prefix as needed.
614   switch (Desc->TSFlags & X86II::SegOvrMask) {
615   case X86II::FS:
616     MCE.emitByte(0x64);
617     break;
618   case X86II::GS:
619     MCE.emitByte(0x65);
620     break;
621   default: llvm_unreachable("Invalid segment!");
622   case 0: break;  // No segment override!
623   }
624
625   // Emit the repeat opcode prefix as needed.
626   if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP)
627     MCE.emitByte(0xF3);
628
629   // Emit the operand size opcode prefix as needed.
630   if (Desc->TSFlags & X86II::OpSize)
631     MCE.emitByte(0x66);
632
633   // Emit the address size opcode prefix as needed.
634   if (Desc->TSFlags & X86II::AdSize)
635     MCE.emitByte(0x67);
636
637   bool Need0FPrefix = false;
638   switch (Desc->TSFlags & X86II::Op0Mask) {
639   case X86II::TB:  // Two-byte opcode prefix
640   case X86II::T8:  // 0F 38
641   case X86II::TA:  // 0F 3A
642     Need0FPrefix = true;
643     break;
644   case X86II::TF: // F2 0F 38
645     MCE.emitByte(0xF2);
646     Need0FPrefix = true;
647     break;
648   case X86II::REP: break; // already handled.
649   case X86II::XS:   // F3 0F
650     MCE.emitByte(0xF3);
651     Need0FPrefix = true;
652     break;
653   case X86II::XD:   // F2 0F
654     MCE.emitByte(0xF2);
655     Need0FPrefix = true;
656     break;
657   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
658   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
659     MCE.emitByte(0xD8+
660                  (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
661                                    >> X86II::Op0Shift));
662     break; // Two-byte opcode prefix
663   default: llvm_unreachable("Invalid prefix!");
664   case 0: break;  // No prefix!
665   }
666
667   // Handle REX prefix.
668   if (Is64BitMode) {
669     if (unsigned REX = determineREX(MI))
670       MCE.emitByte(0x40 | REX);
671   }
672
673   // 0x0F escape code must be emitted just before the opcode.
674   if (Need0FPrefix)
675     MCE.emitByte(0x0F);
676
677   switch (Desc->TSFlags & X86II::Op0Mask) {
678   case X86II::TF:    // F2 0F 38
679   case X86II::T8:    // 0F 38
680     MCE.emitByte(0x38);
681     break;
682   case X86II::TA:    // 0F 3A
683     MCE.emitByte(0x3A);
684     break;
685   }
686
687   // If this is a two-address instruction, skip one of the register operands.
688   unsigned NumOps = Desc->getNumOperands();
689   unsigned CurOp = 0;
690   if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
691     ++CurOp;
692   else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
693     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
694     --NumOps;
695
696   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(Desc->TSFlags);
697   switch (Desc->TSFlags & X86II::FormMask) {
698   default:
699     llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
700   case X86II::Pseudo:
701     // Remember the current PC offset, this is the PIC relocation
702     // base address.
703     switch (Opcode) {
704     default: 
705       llvm_unreachable("psuedo instructions should be removed before code"
706                        " emission");
707       break;
708     // Do nothing for Int_MemBarrier - it's just a comment.  Add a debug
709     // to make it slightly easier to see.
710     case X86::Int_MemBarrier:
711       DEBUG(dbgs() << "#MEMBARRIER\n");
712       break;
713     
714     case TargetOpcode::INLINEASM:
715       // We allow inline assembler nodes with empty bodies - they can
716       // implicitly define registers, which is ok for JIT.
717       if (MI.getOperand(0).getSymbolName()[0])
718         report_fatal_error("JIT does not support inline asm!");
719       break;
720     case TargetOpcode::PROLOG_LABEL:
721     case TargetOpcode::GC_LABEL:
722     case TargetOpcode::EH_LABEL:
723       MCE.emitLabel(MI.getOperand(0).getMCSymbol());
724       break;
725     
726     case TargetOpcode::IMPLICIT_DEF:
727     case TargetOpcode::KILL:
728       break;
729     case X86::MOVPC32r: {
730       // This emits the "call" portion of this pseudo instruction.
731       MCE.emitByte(BaseOpcode);
732       emitConstant(0, X86II::getSizeOfImm(Desc->TSFlags));
733       // Remember PIC base.
734       PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
735       X86JITInfo *JTI = TM.getJITInfo();
736       JTI->setPICBase(MCE.getCurrentPCValue());
737       break;
738     }
739     }
740     CurOp = NumOps;
741     break;
742   case X86II::RawFrm: {
743     MCE.emitByte(BaseOpcode);
744
745     if (CurOp == NumOps)
746       break;
747       
748     const MachineOperand &MO = MI.getOperand(CurOp++);
749
750     DEBUG(dbgs() << "RawFrm CurOp " << CurOp << "\n");
751     DEBUG(dbgs() << "isMBB " << MO.isMBB() << "\n");
752     DEBUG(dbgs() << "isGlobal " << MO.isGlobal() << "\n");
753     DEBUG(dbgs() << "isSymbol " << MO.isSymbol() << "\n");
754     DEBUG(dbgs() << "isImm " << MO.isImm() << "\n");
755
756     if (MO.isMBB()) {
757       emitPCRelativeBlockAddress(MO.getMBB());
758       break;
759     }
760     
761     if (MO.isGlobal()) {
762       emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
763                         MO.getOffset(), 0);
764       break;
765     }
766     
767     if (MO.isSymbol()) {
768       emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
769       break;
770     }
771
772     // FIXME: Only used by hackish MCCodeEmitter, remove when dead.
773     if (MO.isJTI()) {
774       emitJumpTableAddress(MO.getIndex(), X86::reloc_pcrel_word);
775       break;
776     }
777     
778     assert(MO.isImm() && "Unknown RawFrm operand!");
779     if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
780       // Fix up immediate operand for pc relative calls.
781       intptr_t Imm = (intptr_t)MO.getImm();
782       Imm = Imm - MCE.getCurrentPCValue() - 4;
783       emitConstant(Imm, X86II::getSizeOfImm(Desc->TSFlags));
784     } else
785       emitConstant(MO.getImm(), X86II::getSizeOfImm(Desc->TSFlags));
786     break;
787   }
788       
789   case X86II::AddRegFrm: {
790     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
791     
792     if (CurOp == NumOps)
793       break;
794       
795     const MachineOperand &MO1 = MI.getOperand(CurOp++);
796     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
797     if (MO1.isImm()) {
798       emitConstant(MO1.getImm(), Size);
799       break;
800     }
801     
802     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
803       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
804     if (Opcode == X86::MOV64ri64i32)
805       rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
806     // This should not occur on Darwin for relocatable objects.
807     if (Opcode == X86::MOV64ri)
808       rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
809     if (MO1.isGlobal()) {
810       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
811       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
812                         Indirect);
813     } else if (MO1.isSymbol())
814       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
815     else if (MO1.isCPI())
816       emitConstPoolAddress(MO1.getIndex(), rt);
817     else if (MO1.isJTI())
818       emitJumpTableAddress(MO1.getIndex(), rt);
819     break;
820   }
821
822   case X86II::MRMDestReg: {
823     MCE.emitByte(BaseOpcode);
824     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
825                      getX86RegNum(MI.getOperand(CurOp+1).getReg()));
826     CurOp += 2;
827     if (CurOp != NumOps)
828       emitConstant(MI.getOperand(CurOp++).getImm(),
829                    X86II::getSizeOfImm(Desc->TSFlags));
830     break;
831   }
832   case X86II::MRMDestMem: {
833     MCE.emitByte(BaseOpcode);
834     emitMemModRMByte(MI, CurOp,
835                      getX86RegNum(MI.getOperand(CurOp + X86::AddrNumOperands)
836                                   .getReg()));
837     CurOp +=  X86::AddrNumOperands + 1;
838     if (CurOp != NumOps)
839       emitConstant(MI.getOperand(CurOp++).getImm(),
840                    X86II::getSizeOfImm(Desc->TSFlags));
841     break;
842   }
843
844   case X86II::MRMSrcReg:
845     MCE.emitByte(BaseOpcode);
846     emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
847                      getX86RegNum(MI.getOperand(CurOp).getReg()));
848     CurOp += 2;
849     if (CurOp != NumOps)
850       emitConstant(MI.getOperand(CurOp++).getImm(),
851                    X86II::getSizeOfImm(Desc->TSFlags));
852     break;
853
854   case X86II::MRMSrcMem: {
855     int AddrOperands = X86::AddrNumOperands;
856
857     intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
858       X86II::getSizeOfImm(Desc->TSFlags) : 0;
859
860     MCE.emitByte(BaseOpcode);
861     emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
862                      PCAdj);
863     CurOp += AddrOperands + 1;
864     if (CurOp != NumOps)
865       emitConstant(MI.getOperand(CurOp++).getImm(),
866                    X86II::getSizeOfImm(Desc->TSFlags));
867     break;
868   }
869
870   case X86II::MRM0r: case X86II::MRM1r:
871   case X86II::MRM2r: case X86II::MRM3r:
872   case X86II::MRM4r: case X86II::MRM5r:
873   case X86II::MRM6r: case X86II::MRM7r: {
874     MCE.emitByte(BaseOpcode);
875     emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
876                      (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
877
878     if (CurOp == NumOps)
879       break;
880     
881     const MachineOperand &MO1 = MI.getOperand(CurOp++);
882     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
883     if (MO1.isImm()) {
884       emitConstant(MO1.getImm(), Size);
885       break;
886     }
887     
888     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
889       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
890     if (Opcode == X86::MOV64ri32)
891       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
892     if (MO1.isGlobal()) {
893       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
894       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
895                         Indirect);
896     } else if (MO1.isSymbol())
897       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
898     else if (MO1.isCPI())
899       emitConstPoolAddress(MO1.getIndex(), rt);
900     else if (MO1.isJTI())
901       emitJumpTableAddress(MO1.getIndex(), rt);
902     break;
903   }
904
905   case X86II::MRM0m: case X86II::MRM1m:
906   case X86II::MRM2m: case X86II::MRM3m:
907   case X86II::MRM4m: case X86II::MRM5m:
908   case X86II::MRM6m: case X86II::MRM7m: {
909     intptr_t PCAdj = (CurOp + X86::AddrNumOperands != NumOps) ?
910       (MI.getOperand(CurOp+X86::AddrNumOperands).isImm() ? 
911           X86II::getSizeOfImm(Desc->TSFlags) : 4) : 0;
912
913     MCE.emitByte(BaseOpcode);
914     emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
915                      PCAdj);
916     CurOp += X86::AddrNumOperands;
917
918     if (CurOp == NumOps)
919       break;
920     
921     const MachineOperand &MO = MI.getOperand(CurOp++);
922     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
923     if (MO.isImm()) {
924       emitConstant(MO.getImm(), Size);
925       break;
926     }
927     
928     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
929       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
930     if (Opcode == X86::MOV64mi32)
931       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
932     if (MO.isGlobal()) {
933       bool Indirect = gvNeedsNonLazyPtr(MO, TM);
934       emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
935                         Indirect);
936     } else if (MO.isSymbol())
937       emitExternalSymbolAddress(MO.getSymbolName(), rt);
938     else if (MO.isCPI())
939       emitConstPoolAddress(MO.getIndex(), rt);
940     else if (MO.isJTI())
941       emitJumpTableAddress(MO.getIndex(), rt);
942     break;
943   }
944
945   case X86II::MRMInitReg:
946     MCE.emitByte(BaseOpcode);
947     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
948     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
949                      getX86RegNum(MI.getOperand(CurOp).getReg()));
950     ++CurOp;
951     break;
952       
953   case X86II::MRM_C1:
954     MCE.emitByte(BaseOpcode);
955     MCE.emitByte(0xC1);
956     break;
957   case X86II::MRM_C8:
958     MCE.emitByte(BaseOpcode);
959     MCE.emitByte(0xC8);
960     break;
961   case X86II::MRM_C9:
962     MCE.emitByte(BaseOpcode);
963     MCE.emitByte(0xC9);
964     break;
965   case X86II::MRM_E8:
966     MCE.emitByte(BaseOpcode);
967     MCE.emitByte(0xE8);
968     break;
969   case X86II::MRM_F0:
970     MCE.emitByte(BaseOpcode);
971     MCE.emitByte(0xF0);
972     break;
973   }
974
975   if (!Desc->isVariadic() && CurOp != NumOps) {
976 #ifndef NDEBUG
977     dbgs() << "Cannot encode all operands of: " << MI << "\n";
978 #endif
979     llvm_unreachable(0);
980   }
981
982   MCE.processDebugLoc(MI.getDebugLoc(), false);
983 }