Remove unneeded break.
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
1 //===-- 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 emitOpcodePrefix(uint64_t TSFlags, int MemOperand,
72                           const MachineInstr &MI,
73                           const MCInstrDesc *Desc) const;
74
75     void emitVEXOpcodePrefix(uint64_t TSFlags, int MemOperand,
76                              const MachineInstr &MI,
77                              const MCInstrDesc *Desc) const;
78
79     void emitSegmentOverridePrefix(uint64_t TSFlags,
80                                    int MemOperand,
81                                    const MachineInstr &MI) const;
82
83     void emitInstruction(MachineInstr &MI, const MCInstrDesc *Desc);
84
85     void getAnalysisUsage(AnalysisUsage &AU) const {
86       AU.setPreservesAll();
87       AU.addRequired<MachineModuleInfo>();
88       MachineFunctionPass::getAnalysisUsage(AU);
89     }
90
91   private:
92     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
93     void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
94                            intptr_t Disp = 0, intptr_t PCAdj = 0,
95                            bool Indirect = false);
96     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
97     void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
98                               intptr_t PCAdj = 0);
99     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
100                               intptr_t PCAdj = 0);
101
102     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
103                                intptr_t Adj = 0, bool IsPCRel = true);
104
105     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
106     void emitRegModRMByte(unsigned RegOpcodeField);
107     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
108     void emitConstant(uint64_t Val, unsigned Size);
109
110     void emitMemModRMByte(const MachineInstr &MI,
111                           unsigned Op, unsigned RegOpcodeField,
112                           intptr_t PCAdj = 0);
113   };
114
115 template<class CodeEmitter>
116   char Emitter<CodeEmitter>::ID = 0;
117 } // end anonymous namespace.
118
119 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
120 /// to the specified templated MachineCodeEmitter object.
121 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
122                                                 JITCodeEmitter &JCE) {
123   return new Emitter<JITCodeEmitter>(TM, JCE);
124 }
125
126 template<class CodeEmitter>
127 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
128   MMI = &getAnalysis<MachineModuleInfo>();
129   MCE.setModuleInfo(MMI);
130
131   II = TM.getInstrInfo();
132   TD = TM.getTargetData();
133   Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
134   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
135
136   do {
137     DEBUG(dbgs() << "JITTing function '"
138           << MF.getFunction()->getName() << "'\n");
139     MCE.startFunction(MF);
140     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
141          MBB != E; ++MBB) {
142       MCE.StartMachineBasicBlock(MBB);
143       for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
144            I != E; ++I) {
145         const MCInstrDesc &Desc = I->getDesc();
146         emitInstruction(*I, &Desc);
147         // MOVPC32r is basically a call plus a pop instruction.
148         if (Desc.getOpcode() == X86::MOVPC32r)
149           emitInstruction(*I, &II->get(X86::POP32r));
150         ++NumEmitted;  // Keep track of the # of mi's emitted
151       }
152     }
153   } while (MCE.finishFunction(MF));
154
155   return false;
156 }
157
158 /// determineREX - Determine if the MachineInstr has to be encoded with a X86-64
159 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
160 /// size, and 3) use of X86-64 extended registers.
161 static unsigned determineREX(const MachineInstr &MI) {
162   unsigned REX = 0;
163   const MCInstrDesc &Desc = MI.getDesc();
164
165   // Pseudo instructions do not need REX prefix byte.
166   if ((Desc.TSFlags & X86II::FormMask) == X86II::Pseudo)
167     return 0;
168   if (Desc.TSFlags & X86II::REX_W)
169     REX |= 1 << 3;
170
171   unsigned NumOps = Desc.getNumOperands();
172   if (NumOps) {
173     bool isTwoAddr = NumOps > 1 &&
174     Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1;
175
176     // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
177     unsigned i = isTwoAddr ? 1 : 0;
178     for (unsigned e = NumOps; i != e; ++i) {
179       const MachineOperand& MO = MI.getOperand(i);
180       if (MO.isReg()) {
181         unsigned Reg = MO.getReg();
182         if (X86II::isX86_64NonExtLowByteReg(Reg))
183           REX |= 0x40;
184       }
185     }
186
187     switch (Desc.TSFlags & X86II::FormMask) {
188       case X86II::MRMInitReg:
189         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
190           REX |= (1 << 0) | (1 << 2);
191         break;
192       case X86II::MRMSrcReg: {
193         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
194           REX |= 1 << 2;
195         i = isTwoAddr ? 2 : 1;
196         for (unsigned e = NumOps; i != e; ++i) {
197           const MachineOperand& MO = MI.getOperand(i);
198           if (X86InstrInfo::isX86_64ExtendedReg(MO))
199             REX |= 1 << 0;
200         }
201         break;
202       }
203       case X86II::MRMSrcMem: {
204         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
205           REX |= 1 << 2;
206         unsigned Bit = 0;
207         i = isTwoAddr ? 2 : 1;
208         for (; i != NumOps; ++i) {
209           const MachineOperand& MO = MI.getOperand(i);
210           if (MO.isReg()) {
211             if (X86InstrInfo::isX86_64ExtendedReg(MO))
212               REX |= 1 << Bit;
213             Bit++;
214           }
215         }
216         break;
217       }
218       case X86II::MRM0m: case X86II::MRM1m:
219       case X86II::MRM2m: case X86II::MRM3m:
220       case X86II::MRM4m: case X86II::MRM5m:
221       case X86II::MRM6m: case X86II::MRM7m:
222       case X86II::MRMDestMem: {
223         unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
224         i = isTwoAddr ? 1 : 0;
225         if (NumOps > e && X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e)))
226           REX |= 1 << 2;
227         unsigned Bit = 0;
228         for (; i != e; ++i) {
229           const MachineOperand& MO = MI.getOperand(i);
230           if (MO.isReg()) {
231             if (X86InstrInfo::isX86_64ExtendedReg(MO))
232               REX |= 1 << Bit;
233             Bit++;
234           }
235         }
236         break;
237       }
238       default: {
239         if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
240           REX |= 1 << 0;
241         i = isTwoAddr ? 2 : 1;
242         for (unsigned e = NumOps; i != e; ++i) {
243           const MachineOperand& MO = MI.getOperand(i);
244           if (X86InstrInfo::isX86_64ExtendedReg(MO))
245             REX |= 1 << 2;
246         }
247         break;
248       }
249     }
250   }
251   return REX;
252 }
253
254
255 /// emitPCRelativeBlockAddress - This method keeps track of the information
256 /// necessary to resolve the address of this block later and emits a dummy
257 /// value.
258 ///
259 template<class CodeEmitter>
260 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
261   // Remember where this reference was and where it is to so we can
262   // deal with it later.
263   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
264                                              X86::reloc_pcrel_word, MBB));
265   MCE.emitWordLE(0);
266 }
267
268 /// emitGlobalAddress - Emit the specified address to the code stream assuming
269 /// this is part of a "take the address of a global" instruction.
270 ///
271 template<class CodeEmitter>
272 void Emitter<CodeEmitter>::emitGlobalAddress(const GlobalValue *GV,
273                                 unsigned Reloc,
274                                 intptr_t Disp /* = 0 */,
275                                 intptr_t PCAdj /* = 0 */,
276                                 bool Indirect /* = false */) {
277   intptr_t RelocCST = Disp;
278   if (Reloc == X86::reloc_picrel_word)
279     RelocCST = PICBaseOffset;
280   else if (Reloc == X86::reloc_pcrel_word)
281     RelocCST = PCAdj;
282   MachineRelocation MR = Indirect
283     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
284                                            const_cast<GlobalValue *>(GV),
285                                            RelocCST, false)
286     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
287                                const_cast<GlobalValue *>(GV), RelocCST, false);
288   MCE.addRelocation(MR);
289   // The relocated value will be added to the displacement
290   if (Reloc == X86::reloc_absolute_dword)
291     MCE.emitDWordLE(Disp);
292   else
293     MCE.emitWordLE((int32_t)Disp);
294 }
295
296 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
297 /// be emitted to the current location in the function, and allow it to be PC
298 /// relative.
299 template<class CodeEmitter>
300 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
301                                                      unsigned Reloc) {
302   intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
303
304   // X86 never needs stubs because instruction selection will always pick
305   // an instruction sequence that is large enough to hold any address
306   // to a symbol.
307   // (see X86ISelLowering.cpp, near 2039: X86TargetLowering::LowerCall)
308   bool NeedStub = false;
309   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
310                                                  Reloc, ES, RelocCST,
311                                                  0, NeedStub));
312   if (Reloc == X86::reloc_absolute_dword)
313     MCE.emitDWordLE(0);
314   else
315     MCE.emitWordLE(0);
316 }
317
318 /// emitConstPoolAddress - Arrange for the address of an constant pool
319 /// to be emitted to the current location in the function, and allow it to be PC
320 /// relative.
321 template<class CodeEmitter>
322 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
323                                    intptr_t Disp /* = 0 */,
324                                    intptr_t PCAdj /* = 0 */) {
325   intptr_t RelocCST = 0;
326   if (Reloc == X86::reloc_picrel_word)
327     RelocCST = PICBaseOffset;
328   else if (Reloc == X86::reloc_pcrel_word)
329     RelocCST = PCAdj;
330   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
331                                                     Reloc, CPI, RelocCST));
332   // The relocated value will be added to the displacement
333   if (Reloc == X86::reloc_absolute_dword)
334     MCE.emitDWordLE(Disp);
335   else
336     MCE.emitWordLE((int32_t)Disp);
337 }
338
339 /// emitJumpTableAddress - Arrange for the address of a jump table to
340 /// be emitted to the current location in the function, and allow it to be PC
341 /// relative.
342 template<class CodeEmitter>
343 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
344                                    intptr_t PCAdj /* = 0 */) {
345   intptr_t RelocCST = 0;
346   if (Reloc == X86::reloc_picrel_word)
347     RelocCST = PICBaseOffset;
348   else if (Reloc == X86::reloc_pcrel_word)
349     RelocCST = PCAdj;
350   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
351                                                     Reloc, JTI, RelocCST));
352   // The relocated value will be added to the displacement
353   if (Reloc == X86::reloc_absolute_dword)
354     MCE.emitDWordLE(0);
355   else
356     MCE.emitWordLE(0);
357 }
358
359 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
360                                       unsigned RM) {
361   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
362   return RM | (RegOpcode << 3) | (Mod << 6);
363 }
364
365 template<class CodeEmitter>
366 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
367                                             unsigned RegOpcodeFld){
368   MCE.emitByte(ModRMByte(3, RegOpcodeFld, X86_MC::getX86RegNum(ModRMReg)));
369 }
370
371 template<class CodeEmitter>
372 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
373   MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
374 }
375
376 template<class CodeEmitter>
377 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS,
378                                        unsigned Index,
379                                        unsigned Base) {
380   // SIB byte is in the same format as the ModRMByte...
381   MCE.emitByte(ModRMByte(SS, Index, Base));
382 }
383
384 template<class CodeEmitter>
385 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
386   // Output the constant in little endian byte order...
387   for (unsigned i = 0; i != Size; ++i) {
388     MCE.emitByte(Val & 255);
389     Val >>= 8;
390   }
391 }
392
393 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
394 /// sign-extended field.
395 static bool isDisp8(int Value) {
396   return Value == (signed char)Value;
397 }
398
399 static bool gvNeedsNonLazyPtr(const MachineOperand &GVOp,
400                               const TargetMachine &TM) {
401   // For Darwin-64, simulate the linktime GOT by using the same non-lazy-pointer
402   // mechanism as 32-bit mode.
403   if (TM.getSubtarget<X86Subtarget>().is64Bit() &&
404       !TM.getSubtarget<X86Subtarget>().isTargetDarwin())
405     return false;
406
407   // Return true if this is a reference to a stub containing the address of the
408   // global, not the global itself.
409   return isGlobalStubReference(GVOp.getTargetFlags());
410 }
411
412 template<class CodeEmitter>
413 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
414                                                  int DispVal,
415                                                  intptr_t Adj /* = 0 */,
416                                                  bool IsPCRel /* = true */) {
417   // If this is a simple integer displacement that doesn't require a relocation,
418   // emit it now.
419   if (!RelocOp) {
420     emitConstant(DispVal, 4);
421     return;
422   }
423
424   // Otherwise, this is something that requires a relocation.  Emit it as such
425   // now.
426   unsigned RelocType = Is64BitMode ?
427     (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
428     : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
429   if (RelocOp->isGlobal()) {
430     // In 64-bit static small code model, we could potentially emit absolute.
431     // But it's probably not beneficial. If the MCE supports using RIP directly
432     // do it, otherwise fallback to absolute (this is determined by IsPCRel).
433     //  89 05 00 00 00 00     mov    %eax,0(%rip)  # PC-relative
434     //  89 04 25 00 00 00 00  mov    %eax,0x0      # Absolute
435     bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
436     emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
437                       Adj, Indirect);
438   } else if (RelocOp->isSymbol()) {
439     emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
440   } else if (RelocOp->isCPI()) {
441     emitConstPoolAddress(RelocOp->getIndex(), RelocType,
442                          RelocOp->getOffset(), Adj);
443   } else {
444     assert(RelocOp->isJTI() && "Unexpected machine operand!");
445     emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
446   }
447 }
448
449 template<class CodeEmitter>
450 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
451                                             unsigned Op,unsigned RegOpcodeField,
452                                             intptr_t PCAdj) {
453   const MachineOperand &Op3 = MI.getOperand(Op+3);
454   int DispVal = 0;
455   const MachineOperand *DispForReloc = 0;
456
457   // Figure out what sort of displacement we have to handle here.
458   if (Op3.isGlobal()) {
459     DispForReloc = &Op3;
460   } else if (Op3.isSymbol()) {
461     DispForReloc = &Op3;
462   } else if (Op3.isCPI()) {
463     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
464       DispForReloc = &Op3;
465     } else {
466       DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
467       DispVal += Op3.getOffset();
468     }
469   } else if (Op3.isJTI()) {
470     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
471       DispForReloc = &Op3;
472     } else {
473       DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
474     }
475   } else {
476     DispVal = Op3.getImm();
477   }
478
479   const MachineOperand &Base     = MI.getOperand(Op);
480   const MachineOperand &Scale    = MI.getOperand(Op+1);
481   const MachineOperand &IndexReg = MI.getOperand(Op+2);
482
483   unsigned BaseReg = Base.getReg();
484
485   // Handle %rip relative addressing.
486   if (BaseReg == X86::RIP ||
487       (Is64BitMode && DispForReloc)) { // [disp32+RIP] in X86-64 mode
488     assert(IndexReg.getReg() == 0 && Is64BitMode &&
489            "Invalid rip-relative address");
490     MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
491     emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
492     return;
493   }
494
495   // Indicate that the displacement will use an pcrel or absolute reference
496   // by default. MCEs able to resolve addresses on-the-fly use pcrel by default
497   // while others, unless explicit asked to use RIP, use absolute references.
498   bool IsPCRel = MCE.earlyResolveAddresses() ? true : false;
499
500   // Is a SIB byte needed?
501   // If no BaseReg, issue a RIP relative instruction only if the MCE can
502   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
503   // 2-7) and absolute references.
504   unsigned BaseRegNo = -1U;
505   if (BaseReg != 0 && BaseReg != X86::RIP)
506     BaseRegNo = X86_MC::getX86RegNum(BaseReg);
507
508   if (// The SIB byte must be used if there is an index register.
509       IndexReg.getReg() == 0 &&
510       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
511       // encode to an R/M value of 4, which indicates that a SIB byte is
512       // present.
513       BaseRegNo != N86::ESP &&
514       // If there is no base register and we're in 64-bit mode, we need a SIB
515       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
516       (!Is64BitMode || BaseReg != 0)) {
517     if (BaseReg == 0 ||          // [disp32]     in X86-32 mode
518         BaseReg == X86::RIP) {   // [disp32+RIP] in X86-64 mode
519       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
520       emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
521       return;
522     }
523
524     // If the base is not EBP/ESP and there is no displacement, use simple
525     // indirect register encoding, this handles addresses like [EAX].  The
526     // encoding for [EBP] with no displacement means [disp32] so we handle it
527     // by emitting a displacement of 0 below.
528     if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
529       MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
530       return;
531     }
532
533     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
534     if (!DispForReloc && isDisp8(DispVal)) {
535       MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
536       emitConstant(DispVal, 1);
537       return;
538     }
539
540     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
541     MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
542     emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
543     return;
544   }
545
546   // Otherwise we need a SIB byte, so start by outputting the ModR/M byte first.
547   assert(IndexReg.getReg() != X86::ESP &&
548          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
549
550   bool ForceDisp32 = false;
551   bool ForceDisp8  = false;
552   if (BaseReg == 0) {
553     // If there is no base register, we emit the special case SIB byte with
554     // MOD=0, BASE=4, to JUST get the index, scale, and displacement.
555     MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
556     ForceDisp32 = true;
557   } else if (DispForReloc) {
558     // Emit the normal disp32 encoding.
559     MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
560     ForceDisp32 = true;
561   } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
562     // Emit no displacement ModR/M byte
563     MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
564   } else if (isDisp8(DispVal)) {
565     // Emit the disp8 encoding...
566     MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
567     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
568   } else {
569     // Emit the normal disp32 encoding...
570     MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
571   }
572
573   // Calculate what the SS field value should be...
574   static const unsigned SSTable[] = { ~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3 };
575   unsigned SS = SSTable[Scale.getImm()];
576
577   if (BaseReg == 0) {
578     // Handle the SIB byte for the case where there is no base, see Intel
579     // Manual 2A, table 2-7. The displacement has already been output.
580     unsigned IndexRegNo;
581     if (IndexReg.getReg())
582       IndexRegNo = X86_MC::getX86RegNum(IndexReg.getReg());
583     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
584       IndexRegNo = 4;
585     emitSIBByte(SS, IndexRegNo, 5);
586   } else {
587     unsigned BaseRegNo = X86_MC::getX86RegNum(BaseReg);
588     unsigned IndexRegNo;
589     if (IndexReg.getReg())
590       IndexRegNo = X86_MC::getX86RegNum(IndexReg.getReg());
591     else
592       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
593     emitSIBByte(SS, IndexRegNo, BaseRegNo);
594   }
595
596   // Do we need to output a displacement?
597   if (ForceDisp8) {
598     emitConstant(DispVal, 1);
599   } else if (DispVal != 0 || ForceDisp32) {
600     emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
601   }
602 }
603
604 static const MCInstrDesc *UpdateOp(MachineInstr &MI, const X86InstrInfo *II,
605                                    unsigned Opcode) {
606   const MCInstrDesc *Desc = &II->get(Opcode);
607   MI.setDesc(*Desc);
608   return Desc;
609 }
610
611 /// Is16BitMemOperand - Return true if the specified instruction has
612 /// a 16-bit memory operand. Op specifies the operand # of the memoperand.
613 static bool Is16BitMemOperand(const MachineInstr &MI, unsigned Op) {
614   const MachineOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
615   const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
616
617   if ((BaseReg.getReg() != 0 &&
618        X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg.getReg())) ||
619       (IndexReg.getReg() != 0 &&
620        X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg.getReg())))
621     return true;
622   return false;
623 }
624
625 /// Is32BitMemOperand - Return true if the specified instruction has
626 /// a 32-bit memory operand. Op specifies the operand # of the memoperand.
627 static bool Is32BitMemOperand(const MachineInstr &MI, unsigned Op) {
628   const MachineOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
629   const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
630
631   if ((BaseReg.getReg() != 0 &&
632        X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
633       (IndexReg.getReg() != 0 &&
634        X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
635     return true;
636   return false;
637 }
638
639 /// Is64BitMemOperand - Return true if the specified instruction has
640 /// a 64-bit memory operand. Op specifies the operand # of the memoperand.
641 #ifndef NDEBUG
642 static bool Is64BitMemOperand(const MachineInstr &MI, unsigned Op) {
643   const MachineOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
644   const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
645
646   if ((BaseReg.getReg() != 0 &&
647        X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg())) ||
648       (IndexReg.getReg() != 0 &&
649        X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg())))
650     return true;
651   return false;
652 }
653 #endif
654
655 template<class CodeEmitter>
656 void Emitter<CodeEmitter>::emitOpcodePrefix(uint64_t TSFlags,
657                                             int MemOperand,
658                                             const MachineInstr &MI,
659                                             const MCInstrDesc *Desc) const {
660   // Emit the lock opcode prefix as needed.
661   if (Desc->TSFlags & X86II::LOCK)
662     MCE.emitByte(0xF0);
663
664   // Emit segment override opcode prefix as needed.
665   emitSegmentOverridePrefix(TSFlags, MemOperand, MI);
666
667   // Emit the repeat opcode prefix as needed.
668   if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP)
669     MCE.emitByte(0xF3);
670
671   // Emit the address size opcode prefix as needed.
672   bool need_address_override;
673   if (TSFlags & X86II::AdSize) {
674     need_address_override = true;
675   } else if (MemOperand == -1) {
676     need_address_override = false;
677   } else if (Is64BitMode) {
678     assert(!Is16BitMemOperand(MI, MemOperand));
679     need_address_override = Is32BitMemOperand(MI, MemOperand);
680   } else {
681     assert(!Is64BitMemOperand(MI, MemOperand));
682     need_address_override = Is16BitMemOperand(MI, MemOperand);
683   }
684
685   if (need_address_override)
686     MCE.emitByte(0x67);
687
688   // Emit the operand size opcode prefix as needed.
689   if (TSFlags & X86II::OpSize)
690     MCE.emitByte(0x66);
691
692   bool Need0FPrefix = false;
693   switch (Desc->TSFlags & X86II::Op0Mask) {
694     case X86II::TB:  // Two-byte opcode prefix
695     case X86II::T8:  // 0F 38
696     case X86II::TA:  // 0F 3A
697     case X86II::A6:  // 0F A6
698     case X86II::A7:  // 0F A7
699       Need0FPrefix = true;
700       break;
701     case X86II::REP: break; // already handled.
702     case X86II::T8XS: // F3 0F 38
703     case X86II::XS:   // F3 0F
704       MCE.emitByte(0xF3);
705       Need0FPrefix = true;
706       break;
707     case X86II::T8XD: // F2 0F 38
708     case X86II::TAXD: // F2 0F 3A
709     case X86II::XD:   // F2 0F
710       MCE.emitByte(0xF2);
711       Need0FPrefix = true;
712       break;
713     case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
714     case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
715       MCE.emitByte(0xD8+
716                    (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
717                     >> X86II::Op0Shift));
718       break; // Two-byte opcode prefix
719     default: llvm_unreachable("Invalid prefix!");
720     case 0: break;  // No prefix!
721   }
722
723   // Handle REX prefix.
724   if (Is64BitMode) {
725     if (unsigned REX = determineREX(MI))
726       MCE.emitByte(0x40 | REX);
727   }
728
729   // 0x0F escape code must be emitted just before the opcode.
730   if (Need0FPrefix)
731     MCE.emitByte(0x0F);
732
733   switch (Desc->TSFlags & X86II::Op0Mask) {
734     case X86II::T8XD:  // F2 0F 38
735     case X86II::T8XS:  // F3 0F 38
736     case X86II::T8:    // 0F 38
737       MCE.emitByte(0x38);
738       break;
739     case X86II::TAXD:  // F2 0F 38
740     case X86II::TA:    // 0F 3A
741       MCE.emitByte(0x3A);
742       break;
743     case X86II::A6:    // 0F A6
744       MCE.emitByte(0xA6);
745       break;
746     case X86II::A7:    // 0F A7
747       MCE.emitByte(0xA7);
748       break;
749   }
750 }
751
752 static unsigned GetX86RegNum(const MachineOperand &MO) {
753   return X86_MC::getX86RegNum(MO.getReg());
754 }
755
756 // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
757 // 0-7 and the difference between the 2 groups is given by the REX prefix.
758 // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
759 // in 1's complement form, example:
760 //
761 //  ModRM field => XMM9 => 1
762 //  VEX.VVVV    => XMM9 => ~9
763 //
764 // See table 4-35 of Intel AVX Programming Reference for details.
765 static unsigned char getVEXRegisterEncoding(const MachineInstr &MI,
766                                             unsigned OpNum) {
767   unsigned SrcReg = MI.getOperand(OpNum).getReg();
768   unsigned SrcRegNum = GetX86RegNum(MI.getOperand(OpNum));
769   if (X86II::isX86_64ExtendedReg(SrcReg))
770     SrcRegNum |= 8;
771
772   // The registers represented through VEX_VVVV should
773   // be encoded in 1's complement form.
774   return (~SrcRegNum) & 0xf;
775 }
776
777 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
778 template<class CodeEmitter>
779 void Emitter<CodeEmitter>::emitSegmentOverridePrefix(uint64_t TSFlags,
780                                                  int MemOperand,
781                                                  const MachineInstr &MI) const {
782   switch (TSFlags & X86II::SegOvrMask) {
783     default: llvm_unreachable("Invalid segment!");
784     case 0:
785       // No segment override, check for explicit one on memory operand.
786       if (MemOperand != -1) {   // If the instruction has a memory operand.
787         switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
788           default: llvm_unreachable("Unknown segment register!");
789           case 0: break;
790           case X86::CS: MCE.emitByte(0x2E); break;
791           case X86::SS: MCE.emitByte(0x36); break;
792           case X86::DS: MCE.emitByte(0x3E); break;
793           case X86::ES: MCE.emitByte(0x26); break;
794           case X86::FS: MCE.emitByte(0x64); break;
795           case X86::GS: MCE.emitByte(0x65); break;
796         }
797       }
798       break;
799     case X86II::FS:
800       MCE.emitByte(0x64);
801       break;
802     case X86II::GS:
803       MCE.emitByte(0x65);
804       break;
805   }
806 }
807
808 template<class CodeEmitter>
809 void Emitter<CodeEmitter>::emitVEXOpcodePrefix(uint64_t TSFlags,
810                                                int MemOperand,
811                                                const MachineInstr &MI,
812                                                const MCInstrDesc *Desc) const {
813   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
814   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
815
816   // VEX_R: opcode externsion equivalent to REX.R in
817   // 1's complement (inverted) form
818   //
819   //  1: Same as REX_R=0 (must be 1 in 32-bit mode)
820   //  0: Same as REX_R=1 (64 bit mode only)
821   //
822   unsigned char VEX_R = 0x1;
823
824   // VEX_X: equivalent to REX.X, only used when a
825   // register is used for index in SIB Byte.
826   //
827   //  1: Same as REX.X=0 (must be 1 in 32-bit mode)
828   //  0: Same as REX.X=1 (64-bit mode only)
829   unsigned char VEX_X = 0x1;
830
831   // VEX_B:
832   //
833   //  1: Same as REX_B=0 (ignored in 32-bit mode)
834   //  0: Same as REX_B=1 (64 bit mode only)
835   //
836   unsigned char VEX_B = 0x1;
837
838   // VEX_W: opcode specific (use like REX.W, or used for
839   // opcode extension, or ignored, depending on the opcode byte)
840   unsigned char VEX_W = 0;
841
842   // XOP: Use XOP prefix byte 0x8f instead of VEX.
843   unsigned char XOP = 0;
844
845   // VEX_5M (VEX m-mmmmm field):
846   //
847   //  0b00000: Reserved for future use
848   //  0b00001: implied 0F leading opcode
849   //  0b00010: implied 0F 38 leading opcode bytes
850   //  0b00011: implied 0F 3A leading opcode bytes
851   //  0b00100-0b11111: Reserved for future use
852   //  0b01000: XOP map select - 08h instructions with imm byte
853   //  0b10001: XOP map select - 09h instructions with no imm byte
854   unsigned char VEX_5M = 0x1;
855
856   // VEX_4V (VEX vvvv field): a register specifier
857   // (in 1's complement form) or 1111 if unused.
858   unsigned char VEX_4V = 0xf;
859
860   // VEX_L (Vector Length):
861   //
862   //  0: scalar or 128-bit vector
863   //  1: 256-bit vector
864   //
865   unsigned char VEX_L = 0;
866
867   // VEX_PP: opcode extension providing equivalent
868   // functionality of a SIMD prefix
869   //
870   //  0b00: None
871   //  0b01: 66
872   //  0b10: F3
873   //  0b11: F2
874   //
875   unsigned char VEX_PP = 0;
876
877   // Encode the operand size opcode prefix as needed.
878   if (TSFlags & X86II::OpSize)
879     VEX_PP = 0x01;
880
881   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
882     VEX_W = 1;
883
884   if ((TSFlags >> X86II::VEXShift) & X86II::XOP)
885     XOP = 1;
886
887   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
888     VEX_L = 1;
889
890   switch (TSFlags & X86II::Op0Mask) {
891     default: llvm_unreachable("Invalid prefix!");
892     case X86II::T8:  // 0F 38
893       VEX_5M = 0x2;
894       break;
895     case X86II::TA:  // 0F 3A
896       VEX_5M = 0x3;
897       break;
898     case X86II::T8XS: // F3 0F 38
899       VEX_PP = 0x2;
900       VEX_5M = 0x2;
901       break;
902     case X86II::T8XD: // F2 0F 38
903       VEX_PP = 0x3;
904       VEX_5M = 0x2;
905       break;
906     case X86II::TAXD: // F2 0F 3A
907       VEX_PP = 0x3;
908       VEX_5M = 0x3;
909       break;
910     case X86II::XS:  // F3 0F
911       VEX_PP = 0x2;
912       break;
913     case X86II::XD:  // F2 0F
914       VEX_PP = 0x3;
915       break;
916     case X86II::XOP8:
917       VEX_5M = 0x8;
918       break;
919     case X86II::XOP9:
920       VEX_5M = 0x9;
921       break;
922     case X86II::A6:  // Bypass: Not used by VEX
923     case X86II::A7:  // Bypass: Not used by VEX
924     case X86II::TB:  // Bypass: Not used by VEX
925     case 0:
926       break;  // No prefix!
927   }
928
929
930   // Set the vector length to 256-bit if YMM0-YMM15 is used
931   for (unsigned i = 0; i != MI.getNumOperands(); ++i) {
932     if (!MI.getOperand(i).isReg())
933       continue;
934     unsigned SrcReg = MI.getOperand(i).getReg();
935     if (SrcReg >= X86::YMM0 && SrcReg <= X86::YMM15)
936       VEX_L = 1;
937   }
938
939   // Classify VEX_B, VEX_4V, VEX_R, VEX_X
940   unsigned CurOp = 0;
941   switch (TSFlags & X86II::FormMask) {
942     case X86II::MRMInitReg:
943       // Duplicate register.
944       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
945         VEX_R = 0x0;
946
947       if (HasVEX_4V)
948         VEX_4V = getVEXRegisterEncoding(MI, CurOp);
949       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
950         VEX_B = 0x0;
951       if (HasVEX_4VOp3)
952         VEX_4V = getVEXRegisterEncoding(MI, CurOp);
953       break;
954     case X86II::MRMDestMem: {
955       // MRMDestMem instructions forms:
956       //  MemAddr, src1(ModR/M)
957       //  MemAddr, src1(VEX_4V), src2(ModR/M)
958       //  MemAddr, src1(ModR/M), imm8
959       //
960       if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrBaseReg).getReg()))
961         VEX_B = 0x0;
962       if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrIndexReg).getReg()))
963         VEX_X = 0x0;
964
965       CurOp = X86::AddrNumOperands;
966       if (HasVEX_4V)
967         VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
968
969       const MachineOperand &MO = MI.getOperand(CurOp);
970       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
971         VEX_R = 0x0;
972       break;
973     }
974     case X86II::MRMSrcMem:
975       // MRMSrcMem instructions forms:
976       //  src1(ModR/M), MemAddr
977       //  src1(ModR/M), src2(VEX_4V), MemAddr
978       //  src1(ModR/M), MemAddr, imm8
979       //  src1(ModR/M), MemAddr, src2(VEX_I8IMM)
980       //
981       //  FMA4:
982       //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
983       //  dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
984       if (X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
985         VEX_R = 0x0;
986
987       if (HasVEX_4V)
988         VEX_4V = getVEXRegisterEncoding(MI, 1);
989
990       if (X86II::isX86_64ExtendedReg(
991                           MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
992         VEX_B = 0x0;
993       if (X86II::isX86_64ExtendedReg(
994                           MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
995         VEX_X = 0x0;
996
997       if (HasVEX_4VOp3)
998         VEX_4V = getVEXRegisterEncoding(MI, X86::AddrNumOperands+1);
999       break;
1000     case X86II::MRM0m: case X86II::MRM1m:
1001     case X86II::MRM2m: case X86II::MRM3m:
1002     case X86II::MRM4m: case X86II::MRM5m:
1003     case X86II::MRM6m: case X86II::MRM7m: {
1004       // MRM[0-9]m instructions forms:
1005       //  MemAddr
1006       //  src1(VEX_4V), MemAddr
1007       if (HasVEX_4V)
1008         VEX_4V = getVEXRegisterEncoding(MI, 0);
1009
1010       if (X86II::isX86_64ExtendedReg(
1011                           MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
1012         VEX_B = 0x0;
1013       if (X86II::isX86_64ExtendedReg(
1014                           MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
1015         VEX_X = 0x0;
1016       break;
1017     }
1018     case X86II::MRMSrcReg:
1019       // MRMSrcReg instructions forms:
1020       //  dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
1021       //  dst(ModR/M), src1(ModR/M)
1022       //  dst(ModR/M), src1(ModR/M), imm8
1023       //
1024       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
1025         VEX_R = 0x0;
1026       CurOp++;
1027
1028       if (HasVEX_4V)
1029         VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
1030       if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
1031         VEX_B = 0x0;
1032       CurOp++;
1033       if (HasVEX_4VOp3)
1034         VEX_4V = getVEXRegisterEncoding(MI, CurOp);
1035       break;
1036     case X86II::MRMDestReg:
1037       // MRMDestReg instructions forms:
1038       //  dst(ModR/M), src(ModR/M)
1039       //  dst(ModR/M), src(ModR/M), imm8
1040       if (X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
1041         VEX_B = 0x0;
1042       if (X86II::isX86_64ExtendedReg(MI.getOperand(1).getReg()))
1043         VEX_R = 0x0;
1044       break;
1045     case X86II::MRM0r: case X86II::MRM1r:
1046     case X86II::MRM2r: case X86II::MRM3r:
1047     case X86II::MRM4r: case X86II::MRM5r:
1048     case X86II::MRM6r: case X86II::MRM7r:
1049       // MRM0r-MRM7r instructions forms:
1050       //  dst(VEX_4V), src(ModR/M), imm8
1051       VEX_4V = getVEXRegisterEncoding(MI, 0);
1052       if (X86II::isX86_64ExtendedReg(MI.getOperand(1).getReg()))
1053         VEX_B = 0x0;
1054       break;
1055     default: // RawFrm
1056       break;
1057   }
1058
1059   // Emit segment override opcode prefix as needed.
1060   emitSegmentOverridePrefix(TSFlags, MemOperand, MI);
1061
1062   // VEX opcode prefix can have 2 or 3 bytes
1063   //
1064   //  3 bytes:
1065   //    +-----+ +--------------+ +-------------------+
1066   //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
1067   //    +-----+ +--------------+ +-------------------+
1068   //  2 bytes:
1069   //    +-----+ +-------------------+
1070   //    | C5h | | R | vvvv | L | pp |
1071   //    +-----+ +-------------------+
1072   //
1073   unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
1074
1075   if (VEX_B && VEX_X && !VEX_W && !XOP && (VEX_5M == 1)) { // 2 byte VEX prefix
1076     MCE.emitByte(0xC5);
1077     MCE.emitByte(LastByte | (VEX_R << 7));
1078     return;
1079   }
1080
1081   // 3 byte VEX prefix
1082   MCE.emitByte(XOP ? 0x8F : 0xC4);
1083   MCE.emitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M);
1084   MCE.emitByte(LastByte | (VEX_W << 7));
1085 }
1086
1087 template<class CodeEmitter>
1088 void Emitter<CodeEmitter>::emitInstruction(MachineInstr &MI,
1089                                            const MCInstrDesc *Desc) {
1090   DEBUG(dbgs() << MI);
1091
1092   // If this is a pseudo instruction, lower it.
1093   switch (Desc->getOpcode()) {
1094   case X86::ADD16rr_DB:      Desc = UpdateOp(MI, II, X86::OR16rr); break;
1095   case X86::ADD32rr_DB:      Desc = UpdateOp(MI, II, X86::OR32rr); break;
1096   case X86::ADD64rr_DB:      Desc = UpdateOp(MI, II, X86::OR64rr); break;
1097   case X86::ADD16ri_DB:      Desc = UpdateOp(MI, II, X86::OR16ri); break;
1098   case X86::ADD32ri_DB:      Desc = UpdateOp(MI, II, X86::OR32ri); break;
1099   case X86::ADD64ri32_DB:    Desc = UpdateOp(MI, II, X86::OR64ri32); break;
1100   case X86::ADD16ri8_DB:     Desc = UpdateOp(MI, II, X86::OR16ri8); break;
1101   case X86::ADD32ri8_DB:     Desc = UpdateOp(MI, II, X86::OR32ri8); break;
1102   case X86::ADD64ri8_DB:     Desc = UpdateOp(MI, II, X86::OR64ri8); break;
1103   case X86::ACQUIRE_MOV8rm:  Desc = UpdateOp(MI, II, X86::MOV8rm); break;
1104   case X86::ACQUIRE_MOV16rm: Desc = UpdateOp(MI, II, X86::MOV16rm); break;
1105   case X86::ACQUIRE_MOV32rm: Desc = UpdateOp(MI, II, X86::MOV32rm); break;
1106   case X86::ACQUIRE_MOV64rm: Desc = UpdateOp(MI, II, X86::MOV64rm); break;
1107   case X86::RELEASE_MOV8mr:  Desc = UpdateOp(MI, II, X86::MOV8mr); break;
1108   case X86::RELEASE_MOV16mr: Desc = UpdateOp(MI, II, X86::MOV16mr); break;
1109   case X86::RELEASE_MOV32mr: Desc = UpdateOp(MI, II, X86::MOV32mr); break;
1110   case X86::RELEASE_MOV64mr: Desc = UpdateOp(MI, II, X86::MOV64mr); break;
1111   }
1112
1113
1114   MCE.processDebugLoc(MI.getDebugLoc(), true);
1115
1116   unsigned Opcode = Desc->Opcode;
1117
1118   // If this is a two-address instruction, skip one of the register operands.
1119   unsigned NumOps = Desc->getNumOperands();
1120   unsigned CurOp = 0;
1121   if (NumOps > 1 && Desc->getOperandConstraint(1, MCOI::TIED_TO) != -1)
1122     ++CurOp;
1123   else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1,MCOI::TIED_TO)== 0)
1124     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
1125     --NumOps;
1126
1127   uint64_t TSFlags = Desc->TSFlags;
1128
1129   // Is this instruction encoded using the AVX VEX prefix?
1130   bool HasVEXPrefix = (TSFlags >> X86II::VEXShift) & X86II::VEX;
1131   // It uses the VEX.VVVV field?
1132   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
1133   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
1134   bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
1135
1136   // Determine where the memory operand starts, if present.
1137   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags, Opcode);
1138   if (MemoryOperand != -1) MemoryOperand += CurOp;
1139
1140   if (!HasVEXPrefix)
1141     emitOpcodePrefix(TSFlags, MemoryOperand, MI, Desc);
1142   else
1143     emitVEXOpcodePrefix(TSFlags, MemoryOperand, MI, Desc);
1144
1145   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(Desc->TSFlags);
1146   switch (TSFlags & X86II::FormMask) {
1147   default:
1148     llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
1149   case X86II::Pseudo:
1150     // Remember the current PC offset, this is the PIC relocation
1151     // base address.
1152     switch (Opcode) {
1153     default:
1154       llvm_unreachable("pseudo instructions should be removed before code"
1155                        " emission");
1156     // Do nothing for Int_MemBarrier - it's just a comment.  Add a debug
1157     // to make it slightly easier to see.
1158     case X86::Int_MemBarrier:
1159       DEBUG(dbgs() << "#MEMBARRIER\n");
1160       break;
1161
1162     case TargetOpcode::INLINEASM:
1163       // We allow inline assembler nodes with empty bodies - they can
1164       // implicitly define registers, which is ok for JIT.
1165       if (MI.getOperand(0).getSymbolName()[0])
1166         report_fatal_error("JIT does not support inline asm!");
1167       break;
1168     case TargetOpcode::PROLOG_LABEL:
1169     case TargetOpcode::GC_LABEL:
1170     case TargetOpcode::EH_LABEL:
1171       MCE.emitLabel(MI.getOperand(0).getMCSymbol());
1172       break;
1173
1174     case TargetOpcode::IMPLICIT_DEF:
1175     case TargetOpcode::KILL:
1176       break;
1177     case X86::MOVPC32r: {
1178       // This emits the "call" portion of this pseudo instruction.
1179       MCE.emitByte(BaseOpcode);
1180       emitConstant(0, X86II::getSizeOfImm(Desc->TSFlags));
1181       // Remember PIC base.
1182       PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
1183       X86JITInfo *JTI = TM.getJITInfo();
1184       JTI->setPICBase(MCE.getCurrentPCValue());
1185       break;
1186     }
1187     }
1188     CurOp = NumOps;
1189     break;
1190   case X86II::RawFrm: {
1191     MCE.emitByte(BaseOpcode);
1192
1193     if (CurOp == NumOps)
1194       break;
1195
1196     const MachineOperand &MO = MI.getOperand(CurOp++);
1197
1198     DEBUG(dbgs() << "RawFrm CurOp " << CurOp << "\n");
1199     DEBUG(dbgs() << "isMBB " << MO.isMBB() << "\n");
1200     DEBUG(dbgs() << "isGlobal " << MO.isGlobal() << "\n");
1201     DEBUG(dbgs() << "isSymbol " << MO.isSymbol() << "\n");
1202     DEBUG(dbgs() << "isImm " << MO.isImm() << "\n");
1203
1204     if (MO.isMBB()) {
1205       emitPCRelativeBlockAddress(MO.getMBB());
1206       break;
1207     }
1208
1209     if (MO.isGlobal()) {
1210       emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
1211                         MO.getOffset(), 0);
1212       break;
1213     }
1214
1215     if (MO.isSymbol()) {
1216       emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
1217       break;
1218     }
1219
1220     // FIXME: Only used by hackish MCCodeEmitter, remove when dead.
1221     if (MO.isJTI()) {
1222       emitJumpTableAddress(MO.getIndex(), X86::reloc_pcrel_word);
1223       break;
1224     }
1225
1226     assert(MO.isImm() && "Unknown RawFrm operand!");
1227     if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
1228       // Fix up immediate operand for pc relative calls.
1229       intptr_t Imm = (intptr_t)MO.getImm();
1230       Imm = Imm - MCE.getCurrentPCValue() - 4;
1231       emitConstant(Imm, X86II::getSizeOfImm(Desc->TSFlags));
1232     } else
1233       emitConstant(MO.getImm(), X86II::getSizeOfImm(Desc->TSFlags));
1234     break;
1235   }
1236
1237   case X86II::AddRegFrm: {
1238     MCE.emitByte(BaseOpcode +
1239                  X86_MC::getX86RegNum(MI.getOperand(CurOp++).getReg()));
1240
1241     if (CurOp == NumOps)
1242       break;
1243
1244     const MachineOperand &MO1 = MI.getOperand(CurOp++);
1245     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1246     if (MO1.isImm()) {
1247       emitConstant(MO1.getImm(), Size);
1248       break;
1249     }
1250
1251     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1252       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1253     if (Opcode == X86::MOV64ri64i32)
1254       rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
1255     // This should not occur on Darwin for relocatable objects.
1256     if (Opcode == X86::MOV64ri)
1257       rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
1258     if (MO1.isGlobal()) {
1259       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
1260       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
1261                         Indirect);
1262     } else if (MO1.isSymbol())
1263       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
1264     else if (MO1.isCPI())
1265       emitConstPoolAddress(MO1.getIndex(), rt);
1266     else if (MO1.isJTI())
1267       emitJumpTableAddress(MO1.getIndex(), rt);
1268     break;
1269   }
1270
1271   case X86II::MRMDestReg: {
1272     MCE.emitByte(BaseOpcode);
1273     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
1274                      X86_MC::getX86RegNum(MI.getOperand(CurOp+1).getReg()));
1275     CurOp += 2;
1276     if (CurOp != NumOps)
1277       emitConstant(MI.getOperand(CurOp++).getImm(),
1278                    X86II::getSizeOfImm(Desc->TSFlags));
1279     break;
1280   }
1281   case X86II::MRMDestMem: {
1282     MCE.emitByte(BaseOpcode);
1283
1284     unsigned SrcRegNum = CurOp + X86::AddrNumOperands;
1285     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1286       SrcRegNum++;
1287     emitMemModRMByte(MI, CurOp,
1288                 X86_MC::getX86RegNum(MI.getOperand(SrcRegNum).getReg()));
1289     CurOp = SrcRegNum + 1;
1290     if (CurOp != NumOps)
1291       emitConstant(MI.getOperand(CurOp++).getImm(),
1292                    X86II::getSizeOfImm(Desc->TSFlags));
1293     break;
1294   }
1295
1296   case X86II::MRMSrcReg: {
1297     MCE.emitByte(BaseOpcode);
1298
1299     unsigned SrcRegNum = CurOp+1;
1300     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1301       SrcRegNum++;
1302
1303     if(HasMemOp4) // Skip 2nd src (which is encoded in I8IMM)
1304       SrcRegNum++;
1305
1306     emitRegModRMByte(MI.getOperand(SrcRegNum).getReg(),
1307                      X86_MC::getX86RegNum(MI.getOperand(CurOp).getReg()));
1308     // 2 operands skipped with HasMemOp4, comensate accordingly
1309     CurOp = HasMemOp4 ? SrcRegNum : SrcRegNum + 1;
1310     if (HasVEX_4VOp3)
1311       ++CurOp;
1312     if (CurOp != NumOps)
1313       emitConstant(MI.getOperand(CurOp++).getImm(),
1314                    X86II::getSizeOfImm(Desc->TSFlags));
1315     break;
1316   }
1317   case X86II::MRMSrcMem: {
1318     int AddrOperands = X86::AddrNumOperands;
1319     unsigned FirstMemOp = CurOp+1;
1320     if (HasVEX_4V) {
1321       ++AddrOperands;
1322       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_VVVV).
1323     }
1324     if(HasMemOp4) // Skip second register source (encoded in I8IMM)
1325       ++FirstMemOp;
1326
1327     MCE.emitByte(BaseOpcode);
1328
1329     intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
1330       X86II::getSizeOfImm(Desc->TSFlags) : 0;
1331     emitMemModRMByte(MI, FirstMemOp,
1332                      X86_MC::getX86RegNum(MI.getOperand(CurOp).getReg()),PCAdj);
1333     CurOp += AddrOperands + 1;
1334     if (HasVEX_4VOp3)
1335       ++CurOp;
1336     if (CurOp != NumOps)
1337       emitConstant(MI.getOperand(CurOp++).getImm(),
1338                    X86II::getSizeOfImm(Desc->TSFlags));
1339     break;
1340   }
1341
1342   case X86II::MRM0r: case X86II::MRM1r:
1343   case X86II::MRM2r: case X86II::MRM3r:
1344   case X86II::MRM4r: case X86II::MRM5r:
1345   case X86II::MRM6r: case X86II::MRM7r: {
1346     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1347       CurOp++;
1348     MCE.emitByte(BaseOpcode);
1349     emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
1350                      (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
1351
1352     if (CurOp == NumOps)
1353       break;
1354
1355     const MachineOperand &MO1 = MI.getOperand(CurOp++);
1356     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1357     if (MO1.isImm()) {
1358       emitConstant(MO1.getImm(), Size);
1359       break;
1360     }
1361
1362     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1363       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1364     if (Opcode == X86::MOV64ri32)
1365       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
1366     if (MO1.isGlobal()) {
1367       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
1368       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
1369                         Indirect);
1370     } else if (MO1.isSymbol())
1371       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
1372     else if (MO1.isCPI())
1373       emitConstPoolAddress(MO1.getIndex(), rt);
1374     else if (MO1.isJTI())
1375       emitJumpTableAddress(MO1.getIndex(), rt);
1376     break;
1377   }
1378
1379   case X86II::MRM0m: case X86II::MRM1m:
1380   case X86II::MRM2m: case X86II::MRM3m:
1381   case X86II::MRM4m: case X86II::MRM5m:
1382   case X86II::MRM6m: case X86II::MRM7m: {
1383     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1384       CurOp++;
1385     intptr_t PCAdj = (CurOp + X86::AddrNumOperands != NumOps) ?
1386       (MI.getOperand(CurOp+X86::AddrNumOperands).isImm() ?
1387           X86II::getSizeOfImm(Desc->TSFlags) : 4) : 0;
1388
1389     MCE.emitByte(BaseOpcode);
1390     emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
1391                      PCAdj);
1392     CurOp += X86::AddrNumOperands;
1393
1394     if (CurOp == NumOps)
1395       break;
1396
1397     const MachineOperand &MO = MI.getOperand(CurOp++);
1398     unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1399     if (MO.isImm()) {
1400       emitConstant(MO.getImm(), Size);
1401       break;
1402     }
1403
1404     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1405       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1406     if (Opcode == X86::MOV64mi32)
1407       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
1408     if (MO.isGlobal()) {
1409       bool Indirect = gvNeedsNonLazyPtr(MO, TM);
1410       emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
1411                         Indirect);
1412     } else if (MO.isSymbol())
1413       emitExternalSymbolAddress(MO.getSymbolName(), rt);
1414     else if (MO.isCPI())
1415       emitConstPoolAddress(MO.getIndex(), rt);
1416     else if (MO.isJTI())
1417       emitJumpTableAddress(MO.getIndex(), rt);
1418     break;
1419   }
1420
1421   case X86II::MRMInitReg:
1422     MCE.emitByte(BaseOpcode);
1423     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
1424     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
1425                      X86_MC::getX86RegNum(MI.getOperand(CurOp).getReg()));
1426     ++CurOp;
1427     break;
1428
1429   case X86II::MRM_C1:
1430     MCE.emitByte(BaseOpcode);
1431     MCE.emitByte(0xC1);
1432     break;
1433   case X86II::MRM_C8:
1434     MCE.emitByte(BaseOpcode);
1435     MCE.emitByte(0xC8);
1436     break;
1437   case X86II::MRM_C9:
1438     MCE.emitByte(BaseOpcode);
1439     MCE.emitByte(0xC9);
1440     break;
1441   case X86II::MRM_E8:
1442     MCE.emitByte(BaseOpcode);
1443     MCE.emitByte(0xE8);
1444     break;
1445   case X86II::MRM_F0:
1446     MCE.emitByte(BaseOpcode);
1447     MCE.emitByte(0xF0);
1448     break;
1449   }
1450
1451   if (!MI.isVariadic() && CurOp != NumOps) {
1452 #ifndef NDEBUG
1453     dbgs() << "Cannot encode all operands of: " << MI << "\n";
1454 #endif
1455     llvm_unreachable(0);
1456   }
1457
1458   MCE.processDebugLoc(MI.getDebugLoc(), false);
1459 }