Change target-specific classes to use more precise static types.
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-emitter"
16 #include "X86InstrInfo.h"
17 #include "X86JITInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "X86Relocations.h"
21 #include "X86.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/CodeGen/MachineCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/Function.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Target/TargetOptions.h"
33 using namespace llvm;
34
35 STATISTIC(NumEmitted, "Number of machine instructions emitted");
36
37 namespace {
38   class VISIBILITY_HIDDEN Emitter : public MachineFunctionPass {
39     const X86InstrInfo  *II;
40     const TargetData    *TD;
41     X86TargetMachine    &TM;
42     MachineCodeEmitter  &MCE;
43     intptr_t PICBaseOffset;
44     bool Is64BitMode;
45     bool IsPIC;
46   public:
47     static char ID;
48     explicit Emitter(X86TargetMachine &tm, MachineCodeEmitter &mce)
49       : MachineFunctionPass((intptr_t)&ID), II(0), TD(0), TM(tm), 
50       MCE(mce), PICBaseOffset(0), Is64BitMode(false),
51       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
52     Emitter(X86TargetMachine &tm, MachineCodeEmitter &mce,
53             const X86InstrInfo &ii, const TargetData &td, bool is64)
54       : MachineFunctionPass((intptr_t)&ID), II(&ii), TD(&td), TM(tm), 
55       MCE(mce), PICBaseOffset(0), Is64BitMode(is64),
56       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
57
58     bool runOnMachineFunction(MachineFunction &MF);
59
60     virtual const char *getPassName() const {
61       return "X86 Machine Code Emitter";
62     }
63
64     void emitInstruction(const MachineInstr &MI,
65                          const TargetInstrDesc *Desc);
66     
67     void getAnalysisUsage(AnalysisUsage &AU) const {
68       AU.addRequired<MachineModuleInfo>();
69       MachineFunctionPass::getAnalysisUsage(AU);
70     }
71
72   private:
73     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
74     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
75                            int Disp = 0, intptr_t PCAdj = 0,
76                            bool NeedStub = false, bool IsLazy = false);
77     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
78     void emitConstPoolAddress(unsigned CPI, unsigned Reloc, int Disp = 0,
79                               intptr_t PCAdj = 0);
80     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
81                               intptr_t PCAdj = 0);
82
83     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
84                                intptr_t PCAdj = 0);
85
86     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
87     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
88     void emitConstant(uint64_t Val, unsigned Size);
89
90     void emitMemModRMByte(const MachineInstr &MI,
91                           unsigned Op, unsigned RegOpcodeField,
92                           intptr_t PCAdj = 0);
93
94     unsigned getX86RegNum(unsigned RegNo) const;
95
96     bool gvNeedsLazyPtr(const GlobalValue *GV);
97   };
98   char Emitter::ID = 0;
99 }
100
101 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
102 /// to the specified MCE object.
103 FunctionPass *llvm::createX86CodeEmitterPass(X86TargetMachine &TM,
104                                              MachineCodeEmitter &MCE) {
105   return new Emitter(TM, MCE);
106 }
107
108 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
109   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
110           MF.getTarget().getRelocationModel() != Reloc::Static) &&
111          "JIT relocation model must be set to static or default!");
112   
113   MCE.setModuleInfo(&getAnalysis<MachineModuleInfo>());
114   
115   II = TM.getInstrInfo();
116   TD = TM.getTargetData();
117   Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
118   
119   do {
120     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
121     MCE.startFunction(MF);
122     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
123          MBB != E; ++MBB) {
124       MCE.StartMachineBasicBlock(MBB);
125       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
126            I != E; ++I) {
127         const TargetInstrDesc &Desc = I->getDesc();
128         emitInstruction(*I, &Desc);
129         // MOVPC32r is basically a call plus a pop instruction.
130         if (Desc.getOpcode() == X86::MOVPC32r)
131           emitInstruction(*I, &II->get(X86::POP32r));
132         NumEmitted++;  // Keep track of the # of mi's emitted
133       }
134     }
135   } while (MCE.finishFunction(MF));
136
137   return false;
138 }
139
140 /// emitPCRelativeBlockAddress - This method keeps track of the information
141 /// necessary to resolve the address of this block later and emits a dummy
142 /// value.
143 ///
144 void Emitter::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
145   // Remember where this reference was and where it is to so we can
146   // deal with it later.
147   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
148                                              X86::reloc_pcrel_word, MBB));
149   MCE.emitWordLE(0);
150 }
151
152 /// emitGlobalAddress - Emit the specified address to the code stream assuming
153 /// this is part of a "take the address of a global" instruction.
154 ///
155 void Emitter::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
156                                 int Disp /* = 0 */, intptr_t PCAdj /* = 0 */,
157                                 bool NeedStub /* = false */,
158                                 bool isLazy /* = false */) {
159   intptr_t RelocCST = 0;
160   if (Reloc == X86::reloc_picrel_word)
161     RelocCST = PICBaseOffset;
162   else if (Reloc == X86::reloc_pcrel_word)
163     RelocCST = PCAdj;
164   MachineRelocation MR = isLazy 
165     ? MachineRelocation::getGVLazyPtr(MCE.getCurrentPCOffset(), Reloc,
166                                       GV, RelocCST, NeedStub)
167     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
168                                GV, RelocCST, NeedStub);
169   MCE.addRelocation(MR);
170   if (Reloc == X86::reloc_absolute_dword)
171     MCE.emitWordLE(0);
172   MCE.emitWordLE(Disp); // The relocated value will be added to the displacement
173 }
174
175 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
176 /// be emitted to the current location in the function, and allow it to be PC
177 /// relative.
178 void Emitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
179   intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
180   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
181                                                  Reloc, ES, RelocCST));
182   if (Reloc == X86::reloc_absolute_dword)
183     MCE.emitWordLE(0);
184   MCE.emitWordLE(0);
185 }
186
187 /// emitConstPoolAddress - Arrange for the address of an constant pool
188 /// to be emitted to the current location in the function, and allow it to be PC
189 /// relative.
190 void Emitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
191                                    int Disp /* = 0 */,
192                                    intptr_t PCAdj /* = 0 */) {
193   intptr_t RelocCST = 0;
194   if (Reloc == X86::reloc_picrel_word)
195     RelocCST = PICBaseOffset;
196   else if (Reloc == X86::reloc_pcrel_word)
197     RelocCST = PCAdj;
198   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
199                                                     Reloc, CPI, RelocCST));
200   if (Reloc == X86::reloc_absolute_dword)
201     MCE.emitWordLE(0);
202   MCE.emitWordLE(Disp); // The relocated value will be added to the displacement
203 }
204
205 /// emitJumpTableAddress - Arrange for the address of a jump table to
206 /// be emitted to the current location in the function, and allow it to be PC
207 /// relative.
208 void Emitter::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
209                                    intptr_t PCAdj /* = 0 */) {
210   intptr_t RelocCST = 0;
211   if (Reloc == X86::reloc_picrel_word)
212     RelocCST = PICBaseOffset;
213   else if (Reloc == X86::reloc_pcrel_word)
214     RelocCST = PCAdj;
215   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
216                                                     Reloc, JTI, RelocCST));
217   if (Reloc == X86::reloc_absolute_dword)
218     MCE.emitWordLE(0);
219   MCE.emitWordLE(0); // The relocated value will be added to the displacement
220 }
221
222 unsigned Emitter::getX86RegNum(unsigned RegNo) const {
223   return II->getRegisterInfo().getX86RegNum(RegNo);
224 }
225
226 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
227                                       unsigned RM) {
228   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
229   return RM | (RegOpcode << 3) | (Mod << 6);
230 }
231
232 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
233   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
234 }
235
236 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
237   // SIB byte is in the same format as the ModRMByte...
238   MCE.emitByte(ModRMByte(SS, Index, Base));
239 }
240
241 void Emitter::emitConstant(uint64_t Val, unsigned Size) {
242   // Output the constant in little endian byte order...
243   for (unsigned i = 0; i != Size; ++i) {
244     MCE.emitByte(Val & 255);
245     Val >>= 8;
246   }
247 }
248
249 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
250 /// sign-extended field. 
251 static bool isDisp8(int Value) {
252   return Value == (signed char)Value;
253 }
254
255 bool Emitter::gvNeedsLazyPtr(const GlobalValue *GV) {
256   return !Is64BitMode && 
257     TM.getSubtarget<X86Subtarget>().GVRequiresExtraLoad(GV, TM, false);
258 }
259
260 void Emitter::emitDisplacementField(const MachineOperand *RelocOp,
261                                     int DispVal, intptr_t PCAdj) {
262   // If this is a simple integer displacement that doesn't require a relocation,
263   // emit it now.
264   if (!RelocOp) {
265     emitConstant(DispVal, 4);
266     return;
267   }
268   
269   // Otherwise, this is something that requires a relocation.  Emit it as such
270   // now.
271   if (RelocOp->isGlobalAddress()) {
272     // In 64-bit static small code model, we could potentially emit absolute.
273     // But it's probably not beneficial.
274     //  89 05 00 00 00 00     mov    %eax,0(%rip)  # PC-relative
275     //  89 04 25 00 00 00 00  mov    %eax,0x0      # Absolute
276     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
277       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
278     bool NeedStub = isa<Function>(RelocOp->getGlobal());
279     bool isLazy = gvNeedsLazyPtr(RelocOp->getGlobal());
280     emitGlobalAddress(RelocOp->getGlobal(), rt, RelocOp->getOffset(),
281                       PCAdj, NeedStub, isLazy);
282   } else if (RelocOp->isConstantPoolIndex()) {
283     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word : X86::reloc_picrel_word;
284     emitConstPoolAddress(RelocOp->getIndex(), rt,
285                          RelocOp->getOffset(), PCAdj);
286   } else if (RelocOp->isJumpTableIndex()) {
287     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word : X86::reloc_picrel_word;
288     emitJumpTableAddress(RelocOp->getIndex(), rt, PCAdj);
289   } else {
290     assert(0 && "Unknown value to relocate!");
291   }
292 }
293
294 void Emitter::emitMemModRMByte(const MachineInstr &MI,
295                                unsigned Op, unsigned RegOpcodeField,
296                                intptr_t PCAdj) {
297   const MachineOperand &Op3 = MI.getOperand(Op+3);
298   int DispVal = 0;
299   const MachineOperand *DispForReloc = 0;
300   
301   // Figure out what sort of displacement we have to handle here.
302   if (Op3.isGlobalAddress()) {
303     DispForReloc = &Op3;
304   } else if (Op3.isConstantPoolIndex()) {
305     if (Is64BitMode || IsPIC) {
306       DispForReloc = &Op3;
307     } else {
308       DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
309       DispVal += Op3.getOffset();
310     }
311   } else if (Op3.isJumpTableIndex()) {
312     if (Is64BitMode || IsPIC) {
313       DispForReloc = &Op3;
314     } else {
315       DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
316     }
317   } else {
318     DispVal = Op3.getImm();
319   }
320
321   const MachineOperand &Base     = MI.getOperand(Op);
322   const MachineOperand &Scale    = MI.getOperand(Op+1);
323   const MachineOperand &IndexReg = MI.getOperand(Op+2);
324
325   unsigned BaseReg = Base.getReg();
326
327   // Is a SIB byte needed?
328   if (IndexReg.getReg() == 0 &&
329       (BaseReg == 0 || getX86RegNum(BaseReg) != N86::ESP)) {
330     if (BaseReg == 0) {  // Just a displacement?
331       // Emit special case [disp32] encoding
332       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
333       
334       emitDisplacementField(DispForReloc, DispVal, PCAdj);
335     } else {
336       unsigned BaseRegNo = getX86RegNum(BaseReg);
337       if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
338         // Emit simple indirect register encoding... [EAX] f.e.
339         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
340       } else if (!DispForReloc && isDisp8(DispVal)) {
341         // Emit the disp8 encoding... [REG+disp8]
342         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
343         emitConstant(DispVal, 1);
344       } else {
345         // Emit the most general non-SIB encoding: [REG+disp32]
346         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
347         emitDisplacementField(DispForReloc, DispVal, PCAdj);
348       }
349     }
350
351   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
352     assert(IndexReg.getReg() != X86::ESP &&
353            IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
354
355     bool ForceDisp32 = false;
356     bool ForceDisp8  = false;
357     if (BaseReg == 0) {
358       // If there is no base register, we emit the special case SIB byte with
359       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
360       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
361       ForceDisp32 = true;
362     } else if (DispForReloc) {
363       // Emit the normal disp32 encoding.
364       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
365       ForceDisp32 = true;
366     } else if (DispVal == 0 && getX86RegNum(BaseReg) != N86::EBP) {
367       // Emit no displacement ModR/M byte
368       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
369     } else if (isDisp8(DispVal)) {
370       // Emit the disp8 encoding...
371       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
372       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
373     } else {
374       // Emit the normal disp32 encoding...
375       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
376     }
377
378     // Calculate what the SS field value should be...
379     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
380     unsigned SS = SSTable[Scale.getImm()];
381
382     if (BaseReg == 0) {
383       // Handle the SIB byte for the case where there is no base.  The
384       // displacement has already been output.
385       assert(IndexReg.getReg() && "Index register must be specified!");
386       emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
387     } else {
388       unsigned BaseRegNo = getX86RegNum(BaseReg);
389       unsigned IndexRegNo;
390       if (IndexReg.getReg())
391         IndexRegNo = getX86RegNum(IndexReg.getReg());
392       else
393         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
394       emitSIBByte(SS, IndexRegNo, BaseRegNo);
395     }
396
397     // Do we need to output a displacement?
398     if (ForceDisp8) {
399       emitConstant(DispVal, 1);
400     } else if (DispVal != 0 || ForceDisp32) {
401       emitDisplacementField(DispForReloc, DispVal, PCAdj);
402     }
403   }
404 }
405
406 void Emitter::emitInstruction(const MachineInstr &MI,
407                               const TargetInstrDesc *Desc) {
408   DOUT << MI;
409
410   unsigned Opcode = Desc->Opcode;
411
412   // Emit the lock opcode prefix as needed.
413   if (Desc->TSFlags & X86II::LOCK) MCE.emitByte(0xF0);
414
415   // Emit the repeat opcode prefix as needed.
416   if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
417
418   // Emit the operand size opcode prefix as needed.
419   if (Desc->TSFlags & X86II::OpSize) MCE.emitByte(0x66);
420
421   // Emit the address size opcode prefix as needed.
422   if (Desc->TSFlags & X86II::AdSize) MCE.emitByte(0x67);
423
424   bool Need0FPrefix = false;
425   switch (Desc->TSFlags & X86II::Op0Mask) {
426   case X86II::TB:  // Two-byte opcode prefix
427   case X86II::T8:  // 0F 38
428   case X86II::TA:  // 0F 3A
429     Need0FPrefix = true;
430     break;
431   case X86II::REP: break; // already handled.
432   case X86II::XS:   // F3 0F
433     MCE.emitByte(0xF3);
434     Need0FPrefix = true;
435     break;
436   case X86II::XD:   // F2 0F
437     MCE.emitByte(0xF2);
438     Need0FPrefix = true;
439     break;
440   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
441   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
442     MCE.emitByte(0xD8+
443                  (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
444                                    >> X86II::Op0Shift));
445     break; // Two-byte opcode prefix
446   default: assert(0 && "Invalid prefix!");
447   case 0: break;  // No prefix!
448   }
449
450   if (Is64BitMode) {
451     // REX prefix
452     unsigned REX = X86InstrInfo::determineREX(MI);
453     if (REX)
454       MCE.emitByte(0x40 | REX);
455   }
456
457   // 0x0F escape code must be emitted just before the opcode.
458   if (Need0FPrefix)
459     MCE.emitByte(0x0F);
460
461   switch (Desc->TSFlags & X86II::Op0Mask) {
462   case X86II::T8:  // 0F 38
463     MCE.emitByte(0x38);
464     break;
465   case X86II::TA:    // 0F 3A
466     MCE.emitByte(0x3A);
467     break;
468   }
469
470   // If this is a two-address instruction, skip one of the register operands.
471   unsigned NumOps = Desc->getNumOperands();
472   unsigned CurOp = 0;
473   if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
474     ++CurOp;
475   else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
476     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
477     --NumOps;
478
479   unsigned char BaseOpcode = II->getBaseOpcodeFor(Desc);
480   switch (Desc->TSFlags & X86II::FormMask) {
481   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
482   case X86II::Pseudo:
483     // Remember the current PC offset, this is the PIC relocation
484     // base address.
485     switch (Opcode) {
486     default: 
487       assert(0 && "psuedo instructions should be removed before code emission");
488       break;
489     case TargetInstrInfo::INLINEASM:
490       assert(0 && "JIT does not support inline asm!\n");
491       break;
492     case TargetInstrInfo::LABEL:
493       MCE.emitLabel(MI.getOperand(0).getImm());
494       break;
495     case TargetInstrInfo::IMPLICIT_DEF:
496     case TargetInstrInfo::DECLARE:
497     case X86::DWARF_LOC:
498     case X86::FP_REG_KILL:
499       break;
500     case X86::MOVPC32r: {
501       // This emits the "call" portion of this pseudo instruction.
502       MCE.emitByte(BaseOpcode);
503       emitConstant(0, X86InstrInfo::sizeOfImm(Desc));
504       // Remember PIC base.
505       PICBaseOffset = MCE.getCurrentPCOffset();
506       X86JITInfo *JTI = TM.getJITInfo();
507       JTI->setPICBase(MCE.getCurrentPCValue());
508       break;
509     }
510     }
511     CurOp = NumOps;
512     break;
513   case X86II::RawFrm:
514     MCE.emitByte(BaseOpcode);
515
516     if (CurOp != NumOps) {
517       const MachineOperand &MO = MI.getOperand(CurOp++);
518       if (MO.isMachineBasicBlock()) {
519         emitPCRelativeBlockAddress(MO.getMBB());
520       } else if (MO.isGlobalAddress()) {
521         bool NeedStub = (Is64BitMode && TM.getCodeModel() == CodeModel::Large)
522           || Opcode == X86::TAILJMPd;
523         emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
524                           0, 0, NeedStub);
525       } else if (MO.isExternalSymbol()) {
526         emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
527       } else if (MO.isImmediate()) {
528         emitConstant(MO.getImm(), X86InstrInfo::sizeOfImm(Desc));
529       } else {
530         assert(0 && "Unknown RawFrm operand!");
531       }
532     }
533     break;
534
535   case X86II::AddRegFrm:
536     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
537     
538     if (CurOp != NumOps) {
539       const MachineOperand &MO1 = MI.getOperand(CurOp++);
540       unsigned Size = X86InstrInfo::sizeOfImm(Desc);
541       if (MO1.isImmediate())
542         emitConstant(MO1.getImm(), Size);
543       else {
544         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
545           : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
546         if (Opcode == X86::MOV64ri)
547           rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
548         if (MO1.isGlobalAddress()) {
549           bool NeedStub = isa<Function>(MO1.getGlobal());
550           bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());
551           emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
552                             NeedStub, isLazy);
553         } else if (MO1.isExternalSymbol())
554           emitExternalSymbolAddress(MO1.getSymbolName(), rt);
555         else if (MO1.isConstantPoolIndex())
556           emitConstPoolAddress(MO1.getIndex(), rt);
557         else if (MO1.isJumpTableIndex())
558           emitJumpTableAddress(MO1.getIndex(), rt);
559       }
560     }
561     break;
562
563   case X86II::MRMDestReg: {
564     MCE.emitByte(BaseOpcode);
565     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
566                      getX86RegNum(MI.getOperand(CurOp+1).getReg()));
567     CurOp += 2;
568     if (CurOp != NumOps)
569       emitConstant(MI.getOperand(CurOp++).getImm(), X86InstrInfo::sizeOfImm(Desc));
570     break;
571   }
572   case X86II::MRMDestMem: {
573     MCE.emitByte(BaseOpcode);
574     emitMemModRMByte(MI, CurOp, getX86RegNum(MI.getOperand(CurOp+4).getReg()));
575     CurOp += 5;
576     if (CurOp != NumOps)
577       emitConstant(MI.getOperand(CurOp++).getImm(), X86InstrInfo::sizeOfImm(Desc));
578     break;
579   }
580
581   case X86II::MRMSrcReg:
582     MCE.emitByte(BaseOpcode);
583     emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
584                      getX86RegNum(MI.getOperand(CurOp).getReg()));
585     CurOp += 2;
586     if (CurOp != NumOps)
587       emitConstant(MI.getOperand(CurOp++).getImm(), X86InstrInfo::sizeOfImm(Desc));
588     break;
589
590   case X86II::MRMSrcMem: {
591     intptr_t PCAdj = (CurOp+5 != NumOps) ? X86InstrInfo::sizeOfImm(Desc) : 0;
592
593     MCE.emitByte(BaseOpcode);
594     emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
595                      PCAdj);
596     CurOp += 5;
597     if (CurOp != NumOps)
598       emitConstant(MI.getOperand(CurOp++).getImm(), X86InstrInfo::sizeOfImm(Desc));
599     break;
600   }
601
602   case X86II::MRM0r: case X86II::MRM1r:
603   case X86II::MRM2r: case X86II::MRM3r:
604   case X86II::MRM4r: case X86II::MRM5r:
605   case X86II::MRM6r: case X86II::MRM7r:
606     MCE.emitByte(BaseOpcode);
607     emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
608                      (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
609
610     if (CurOp != NumOps) {
611       const MachineOperand &MO1 = MI.getOperand(CurOp++);
612       unsigned Size = X86InstrInfo::sizeOfImm(Desc);
613       if (MO1.isImmediate())
614         emitConstant(MO1.getImm(), Size);
615       else {
616         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
617           : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
618         if (Opcode == X86::MOV64ri32)
619           rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
620         if (MO1.isGlobalAddress()) {
621           bool NeedStub = isa<Function>(MO1.getGlobal());
622           bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());
623           emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
624                             NeedStub, isLazy);
625         } else if (MO1.isExternalSymbol())
626           emitExternalSymbolAddress(MO1.getSymbolName(), rt);
627         else if (MO1.isConstantPoolIndex())
628           emitConstPoolAddress(MO1.getIndex(), rt);
629         else if (MO1.isJumpTableIndex())
630           emitJumpTableAddress(MO1.getIndex(), rt);
631       }
632     }
633     break;
634
635   case X86II::MRM0m: case X86II::MRM1m:
636   case X86II::MRM2m: case X86II::MRM3m:
637   case X86II::MRM4m: case X86II::MRM5m:
638   case X86II::MRM6m: case X86II::MRM7m: {
639     intptr_t PCAdj = (CurOp+4 != NumOps) ?
640       (MI.getOperand(CurOp+4).isImmediate() ? X86InstrInfo::sizeOfImm(Desc) : 4) : 0;
641
642     MCE.emitByte(BaseOpcode);
643     emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
644                      PCAdj);
645     CurOp += 4;
646
647     if (CurOp != NumOps) {
648       const MachineOperand &MO = MI.getOperand(CurOp++);
649       unsigned Size = X86InstrInfo::sizeOfImm(Desc);
650       if (MO.isImmediate())
651         emitConstant(MO.getImm(), Size);
652       else {
653         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
654           : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
655         if (Opcode == X86::MOV64mi32)
656           rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
657         if (MO.isGlobalAddress()) {
658           bool NeedStub = isa<Function>(MO.getGlobal());
659           bool isLazy = gvNeedsLazyPtr(MO.getGlobal());
660           emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
661                             NeedStub, isLazy);
662         } else if (MO.isExternalSymbol())
663           emitExternalSymbolAddress(MO.getSymbolName(), rt);
664         else if (MO.isConstantPoolIndex())
665           emitConstPoolAddress(MO.getIndex(), rt);
666         else if (MO.isJumpTableIndex())
667           emitJumpTableAddress(MO.getIndex(), rt);
668       }
669     }
670     break;
671   }
672
673   case X86II::MRMInitReg:
674     MCE.emitByte(BaseOpcode);
675     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
676     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
677                      getX86RegNum(MI.getOperand(CurOp).getReg()));
678     ++CurOp;
679     break;
680   }
681
682   if (!Desc->isVariadic() && CurOp != NumOps) {
683     cerr << "Cannot encode: ";
684     MI.dump();
685     cerr << '\n';
686     abort();
687   }
688 }