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