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