Be a bit more efficient when processing the active and inactive
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the pass that transforms the X86 machine instructions into
11 // actual executable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "X86TargetMachine.h"
17 #include "X86.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Function.h"
24 #include "Support/Debug.h"
25 #include "Support/Statistic.h"
26 #include "Config/alloca.h"
27 using namespace llvm;
28
29 namespace {
30   Statistic<>
31   NumEmitted("x86-emitter", "Number of machine instructions emitted");
32
33   class JITResolver {
34     MachineCodeEmitter &MCE;
35
36     // LazyCodeGenMap - Keep track of call sites for functions that are to be
37     // lazily resolved.
38     std::map<unsigned, Function*> LazyCodeGenMap;
39
40     // LazyResolverMap - Keep track of the lazy resolver created for a
41     // particular function so that we can reuse them if necessary.
42     std::map<Function*, unsigned> LazyResolverMap;
43   public:
44     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
45     unsigned getLazyResolver(Function *F);
46     unsigned addFunctionReference(unsigned Address, Function *F);
47     
48   private:
49     unsigned emitStubForFunction(Function *F);
50     static void CompilationCallback();
51     unsigned resolveFunctionReference(unsigned RetAddr);
52   };
53
54   static JITResolver &getResolver(MachineCodeEmitter &MCE) {
55     static JITResolver *TheJITResolver = 0;
56     if (TheJITResolver == 0)
57       TheJITResolver = new JITResolver(MCE);
58     return *TheJITResolver;
59   }
60 }
61
62
63 void *X86JITInfo::getJITStubForFunction(Function *F, MachineCodeEmitter &MCE) {
64   return (void*)((unsigned long)getResolver(MCE).getLazyResolver(F));
65 }
66
67 void X86JITInfo::replaceMachineCodeForFunction (void *Old, void *New) {
68   char *OldByte = (char *) Old;
69   *OldByte++ = 0xE9;                // Emit JMP opcode.
70   int32_t *OldWord = (int32_t *) OldByte;
71   int32_t NewAddr = (intptr_t) New;
72   int32_t OldAddr = (intptr_t) OldWord;
73   *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
74 }
75
76 /// addFunctionReference - This method is called when we need to emit the
77 /// address of a function that has not yet been emitted, so we don't know the
78 /// address.  Instead, we emit a call to the CompilationCallback method, and
79 /// keep track of where we are.
80 ///
81 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
82   LazyCodeGenMap[Address] = F;  
83   return (intptr_t)&JITResolver::CompilationCallback;
84 }
85
86 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
87   std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
88   assert(I != LazyCodeGenMap.end() && "Not in map!");
89   Function *F = I->second;
90   LazyCodeGenMap.erase(I);
91   return MCE.forceCompilationOf(F);
92 }
93
94 unsigned JITResolver::getLazyResolver(Function *F) {
95   std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
96   if (I != LazyResolverMap.end() && I->first == F) return I->second;
97   
98 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
99
100   unsigned Stub = emitStubForFunction(F);
101   LazyResolverMap.insert(I, std::make_pair(F, Stub));
102   return Stub;
103 }
104
105 void JITResolver::CompilationCallback() {
106   unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
107   unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
108   assert(StackPtr[1] == RetAddr &&
109          "Could not find return address on the stack!");
110
111   // It's a stub if there is an interrupt marker after the call...
112   bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
113
114   // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
115   // pointer elimination has been performed.  Having a variable sized alloca
116   // disables frame pointer elimination currently, even if it's dead.  This is a
117   // gross hack.
118   alloca(10+isStub);
119   // FIXME FIXME FIXME FIXME
120
121   // The call instruction should have pushed the return value onto the stack...
122   RetAddr -= 4;  // Backtrack to the reference itself...
123
124 #if 0
125   DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
126                   << " ESP=0x" << (unsigned)StackPtr << std::dec
127                   << ": Resolving call to function: "
128                   << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
129 #endif
130
131   // Sanity check to make sure this really is a call instruction...
132   assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
133   
134   JITResolver &JR = getResolver(*(MachineCodeEmitter*)0);
135   unsigned NewVal = JR.resolveFunctionReference(RetAddr);
136
137   // Rewrite the call target... so that we don't fault every time we execute
138   // the call.
139   *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;    
140
141   if (isStub) {
142     // If this is a stub, rewrite the call into an unconditional branch
143     // instruction so that two return addresses are not pushed onto the stack
144     // when the requested function finally gets called.  This also makes the
145     // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
146     ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
147   }
148
149   // Change the return address to reexecute the call instruction...
150   StackPtr[1] -= 5;
151 }
152
153 /// emitStubForFunction - This method is used by the JIT when it needs to emit
154 /// the address of a function for a function whose code has not yet been
155 /// generated.  In order to do this, it generates a stub which jumps to the lazy
156 /// function compiler, which will eventually get fixed to call the function
157 /// directly.
158 ///
159 unsigned JITResolver::emitStubForFunction(Function *F) {
160   MCE.startFunctionStub(*F, 6);
161   MCE.emitByte(0xE8);   // Call with 32 bit pc-rel destination...
162
163   unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
164   MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
165
166   MCE.emitByte(0xCD);   // Interrupt - Just a marker identifying the stub!
167   return (intptr_t)MCE.finishFunctionStub(*F);
168 }
169
170
171 namespace {
172   class Emitter : public MachineFunctionPass {
173     const X86InstrInfo  *II;
174     MachineCodeEmitter  &MCE;
175     std::map<const MachineBasicBlock*, unsigned> BasicBlockAddrs;
176     std::vector<std::pair<const MachineBasicBlock *, unsigned> > BBRefs;
177   public:
178     explicit Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
179     Emitter(MachineCodeEmitter &mce, const X86InstrInfo& ii)
180         : II(&ii), MCE(mce) {}
181
182     bool runOnMachineFunction(MachineFunction &MF);
183
184     virtual const char *getPassName() const {
185       return "X86 Machine Code Emitter";
186     }
187
188     void emitInstruction(const MachineInstr &MI);
189
190   private:
191     void emitBasicBlock(const MachineBasicBlock &MBB);
192
193     void emitPCRelativeBlockAddress(const MachineBasicBlock *BB);
194     void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
195     void emitGlobalAddressForCall(GlobalValue *GV);
196     void emitGlobalAddressForPtr(GlobalValue *GV);
197
198     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
199     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
200     void emitConstant(unsigned Val, unsigned Size);
201
202     void emitMemModRMByte(const MachineInstr &MI,
203                           unsigned Op, unsigned RegOpcodeField);
204
205   };
206 }
207
208 // This function is required by Printer.cpp to workaround gas bugs
209 void llvm::X86::emitInstruction(MachineCodeEmitter& mce,
210                                 const X86InstrInfo& ii,
211                                 const MachineInstr& mi)
212 {
213     Emitter(mce, ii).emitInstruction(mi);
214 }
215
216 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
217 /// machine code emitted.  This uses a MachineCodeEmitter object to handle
218 /// actually outputting the machine code and resolving things like the address
219 /// of functions.  This method should returns true if machine code emission is
220 /// not supported.
221 ///
222 bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
223                                                   MachineCodeEmitter &MCE) {
224   PM.add(new Emitter(MCE));
225   // Delete machine code for this function
226   PM.add(createMachineCodeDeleter());
227   return false;
228 }
229
230 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
231   II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
232
233   MCE.startFunction(MF);
234   MCE.emitConstantPool(MF.getConstantPool());
235   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
236     emitBasicBlock(*I);
237   MCE.finishFunction(MF);
238
239   // Resolve all forward branches now...
240   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
241     unsigned Location = BasicBlockAddrs[BBRefs[i].first];
242     unsigned Ref = BBRefs[i].second;
243     MCE.emitWordAt (Location-Ref-4, (unsigned*)(intptr_t)Ref);
244   }
245   BBRefs.clear();
246   BasicBlockAddrs.clear();
247   return false;
248 }
249
250 void Emitter::emitBasicBlock(const MachineBasicBlock &MBB) {
251   if (uint64_t Addr = MCE.getCurrentPCValue())
252     BasicBlockAddrs[&MBB] = Addr;
253
254   for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
255     emitInstruction(*I);
256 }
257
258 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
259 /// the specified basic block, or if the basic block hasn't been emitted yet
260 /// (because this is a forward branch), it keeps track of the information
261 /// necessary to resolve this address later (and emits a dummy value).
262 ///
263 void Emitter::emitPCRelativeBlockAddress(const MachineBasicBlock *MBB) {
264   // FIXME: Emit backward branches directly
265   BBRefs.push_back(std::make_pair(MBB, MCE.getCurrentPCValue()));
266   MCE.emitWord(0);
267 }
268
269 /// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
270 ///
271 void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
272   if (isPCRelative)
273     MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
274   else
275     MCE.emitWord(Address);
276 }
277
278 /// emitGlobalAddressForCall - Emit the specified address to the code stream
279 /// assuming this is part of a function call, which is PC relative.
280 ///
281 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
282   // Get the address from the backend...
283   unsigned Address = MCE.getGlobalValueAddress(GV);
284   
285   if (Address == 0) {
286     // FIXME: this is JIT specific!
287     Address = getResolver(MCE).addFunctionReference(MCE.getCurrentPCValue(),
288                                                     cast<Function>(GV));
289   }
290   emitMaybePCRelativeValue(Address, true);
291 }
292
293 /// emitGlobalAddress - Emit the specified address to the code stream assuming
294 /// this is part of a "take the address of a global" instruction, which is not
295 /// PC relative.
296 ///
297 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
298   // Get the address from the backend...
299   unsigned Address = MCE.getGlobalValueAddress(GV);
300
301   // If the machine code emitter doesn't know what the address IS yet, we have
302   // to take special measures.
303   //
304   if (Address == 0) {
305     // FIXME: this is JIT specific!
306     Address = getResolver(MCE).getLazyResolver((Function*)GV);
307   }
308
309   emitMaybePCRelativeValue(Address, false);
310 }
311
312
313
314 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
315 ///
316 namespace N86 {
317   enum {
318     EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
319   };
320 }
321
322
323 // getX86RegNum - This function maps LLVM register identifiers to their X86
324 // specific numbering, which is used in various places encoding instructions.
325 //
326 static unsigned getX86RegNum(unsigned RegNo) {
327   switch(RegNo) {
328   case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
329   case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
330   case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
331   case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
332   case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
333   case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
334   case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
335   case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
336
337   case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
338   case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
339     return RegNo-X86::ST0;
340   default:
341     assert(MRegisterInfo::isVirtualRegister(RegNo) &&
342            "Unknown physical register!");
343     assert(0 && "Register allocator hasn't allocated reg correctly yet!");
344     return 0;
345   }
346 }
347
348 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
349                                       unsigned RM) {
350   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
351   return RM | (RegOpcode << 3) | (Mod << 6);
352 }
353
354 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
355   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
356 }
357
358 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
359   // SIB byte is in the same format as the ModRMByte...
360   MCE.emitByte(ModRMByte(SS, Index, Base));
361 }
362
363 void Emitter::emitConstant(unsigned Val, unsigned Size) {
364   // Output the constant in little endian byte order...
365   for (unsigned i = 0; i != Size; ++i) {
366     MCE.emitByte(Val & 255);
367     Val >>= 8;
368   }
369 }
370
371 static bool isDisp8(int Value) {
372   return Value == (signed char)Value;
373 }
374
375 void Emitter::emitMemModRMByte(const MachineInstr &MI,
376                                unsigned Op, unsigned RegOpcodeField) {
377   const MachineOperand &Disp     = MI.getOperand(Op+3);
378   if (MI.getOperand(Op).isConstantPoolIndex()) {
379     // Emit a direct address reference [disp32] where the displacement of the
380     // constant pool entry is controlled by the MCE.
381     MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
382     unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
383     unsigned Address = MCE.getConstantPoolEntryAddress(Index);
384     MCE.emitWord(Address+Disp.getImmedValue());
385     return;
386   }
387
388   const MachineOperand &BaseReg  = MI.getOperand(Op);
389   const MachineOperand &Scale    = MI.getOperand(Op+1);
390   const MachineOperand &IndexReg = MI.getOperand(Op+2);
391
392   // Is a SIB byte needed?
393   if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
394     if (BaseReg.getReg() == 0) {  // Just a displacement?
395       // Emit special case [disp32] encoding
396       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
397       emitConstant(Disp.getImmedValue(), 4);
398     } else {
399       unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
400       if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
401         // Emit simple indirect register encoding... [EAX] f.e.
402         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
403       } else if (isDisp8(Disp.getImmedValue())) {
404         // Emit the disp8 encoding... [REG+disp8]
405         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
406         emitConstant(Disp.getImmedValue(), 1);
407       } else {
408         // Emit the most general non-SIB encoding: [REG+disp32]
409         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
410         emitConstant(Disp.getImmedValue(), 4);
411       }
412     }
413
414   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
415     assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
416
417     bool ForceDisp32 = false;
418     bool ForceDisp8  = false;
419     if (BaseReg.getReg() == 0) {
420       // If there is no base register, we emit the special case SIB byte with
421       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
422       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
423       ForceDisp32 = true;
424     } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
425       // Emit no displacement ModR/M byte
426       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
427     } else if (isDisp8(Disp.getImmedValue())) {
428       // Emit the disp8 encoding...
429       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
430       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
431     } else {
432       // Emit the normal disp32 encoding...
433       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
434     }
435
436     // Calculate what the SS field value should be...
437     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
438     unsigned SS = SSTable[Scale.getImmedValue()];
439
440     if (BaseReg.getReg() == 0) {
441       // Handle the SIB byte for the case where there is no base.  The
442       // displacement has already been output.
443       assert(IndexReg.getReg() && "Index register must be specified!");
444       emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
445     } else {
446       unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
447       unsigned IndexRegNo;
448       if (IndexReg.getReg())
449         IndexRegNo = getX86RegNum(IndexReg.getReg());
450       else
451         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
452       emitSIBByte(SS, IndexRegNo, BaseRegNo);
453     }
454
455     // Do we need to output a displacement?
456     if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
457       if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
458         emitConstant(Disp.getImmedValue(), 1);
459       else
460         emitConstant(Disp.getImmedValue(), 4);
461     }
462   }
463 }
464
465 static unsigned sizeOfImm(const TargetInstrDescriptor &Desc) {
466   switch (Desc.TSFlags & X86II::ImmMask) {
467   case X86II::Imm8:   return 1;
468   case X86II::Imm16:  return 2;
469   case X86II::Imm32:  return 4;
470   default: assert(0 && "Immediate size not set!");
471     return 0;
472   }
473 }
474
475 void Emitter::emitInstruction(const MachineInstr &MI) {
476   NumEmitted++;  // Keep track of the # of mi's emitted
477
478   unsigned Opcode = MI.getOpcode();
479   const TargetInstrDescriptor &Desc = II->get(Opcode);
480
481   // Emit the repeat opcode prefix as needed.
482   if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
483
484   // Emit instruction prefixes if necessary
485   if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
486
487   switch (Desc.TSFlags & X86II::Op0Mask) {
488   case X86II::TB:
489     MCE.emitByte(0x0F);   // Two-byte opcode prefix
490     break;
491   case X86II::REP: break; // already handled.
492   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
493   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
494     MCE.emitByte(0xD8+
495                  (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
496                                    >> X86II::Op0Shift));
497     break; // Two-byte opcode prefix
498   default: assert(0 && "Invalid prefix!");
499   case 0: break;  // No prefix!
500   }
501
502   unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
503   switch (Desc.TSFlags & X86II::FormMask) {
504   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
505   case X86II::Pseudo:
506     if (Opcode != X86::IMPLICIT_USE &&
507         Opcode != X86::IMPLICIT_DEF &&
508         Opcode != X86::FP_REG_KILL)
509       std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
510     break;
511
512   case X86II::RawFrm:
513     MCE.emitByte(BaseOpcode);
514     if (MI.getNumOperands() == 1) {
515       const MachineOperand &MO = MI.getOperand(0);
516       if (MO.isMachineBasicBlock()) {
517         emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
518       } else if (MO.isGlobalAddress()) {
519         assert(MO.isPCRelative() && "Call target is not PC Relative?");
520         emitGlobalAddressForCall(MO.getGlobal());
521       } else if (MO.isExternalSymbol()) {
522         unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
523         assert(Address && "Unknown external symbol!");
524         emitMaybePCRelativeValue(Address, MO.isPCRelative());
525       } else if (MO.isImmediate()) {
526         emitConstant(MO.getImmedValue(), sizeOfImm(Desc));        
527       } else {
528         assert(0 && "Unknown RawFrm operand!");
529       }
530     }
531     break;
532
533   case X86II::AddRegFrm:
534     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
535     if (MI.getNumOperands() == 2) {
536       const MachineOperand &MO1 = MI.getOperand(1);
537       if (Value *V = MO1.getVRegValueOrNull()) {
538         assert(sizeOfImm(Desc) == 4 && "Don't know how to emit non-pointer values!");
539         emitGlobalAddressForPtr(cast<GlobalValue>(V));
540       } else if (MO1.isGlobalAddress()) {
541         assert(sizeOfImm(Desc) == 4 && "Don't know how to emit non-pointer values!");
542         assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
543         emitGlobalAddressForPtr(MO1.getGlobal());
544       } else if (MO1.isExternalSymbol()) {
545         assert(sizeOfImm(Desc) == 4 && "Don't know how to emit non-pointer values!");
546
547         unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
548         assert(Address && "Unknown external symbol!");
549         emitMaybePCRelativeValue(Address, MO1.isPCRelative());
550       } else {
551         emitConstant(MO1.getImmedValue(), sizeOfImm(Desc));
552       }
553     }
554     break;
555
556   case X86II::MRMDestReg: {
557     MCE.emitByte(BaseOpcode);
558     emitRegModRMByte(MI.getOperand(0).getReg(),
559                      getX86RegNum(MI.getOperand(1).getReg()));
560     if (MI.getNumOperands() == 3)
561       emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
562     break;
563   }
564   case X86II::MRMDestMem:
565     MCE.emitByte(BaseOpcode);
566     emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
567     if (MI.getNumOperands() == 6)
568       emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
569     break;
570
571   case X86II::MRMSrcReg:
572     MCE.emitByte(BaseOpcode);
573
574     emitRegModRMByte(MI.getOperand(1).getReg(),
575                      getX86RegNum(MI.getOperand(0).getReg()));
576     if (MI.getNumOperands() == 3)
577       emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
578     break;
579
580   case X86II::MRMSrcMem:
581     MCE.emitByte(BaseOpcode);
582     emitMemModRMByte(MI, 1, getX86RegNum(MI.getOperand(0).getReg()));
583     if (MI.getNumOperands() == 2+4)
584       emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
585     break;
586
587   case X86II::MRM0r: case X86II::MRM1r:
588   case X86II::MRM2r: case X86II::MRM3r:
589   case X86II::MRM4r: case X86II::MRM5r:
590   case X86II::MRM6r: case X86II::MRM7r:
591     MCE.emitByte(BaseOpcode);
592     emitRegModRMByte(MI.getOperand(0).getReg(),
593                      (Desc.TSFlags & X86II::FormMask)-X86II::MRM0r);
594
595     if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
596       emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), sizeOfImm(Desc));
597     }
598     break;
599
600   case X86II::MRM0m: case X86II::MRM1m:
601   case X86II::MRM2m: case X86II::MRM3m:
602   case X86II::MRM4m: case X86II::MRM5m:
603   case X86II::MRM6m: case X86II::MRM7m: 
604     MCE.emitByte(BaseOpcode);
605     emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRM0m);
606
607     if (MI.getNumOperands() == 5) {
608       if (MI.getOperand(4).isImmediate())
609         emitConstant(MI.getOperand(4).getImmedValue(), sizeOfImm(Desc));
610       else if (MI.getOperand(4).isGlobalAddress())
611         emitGlobalAddressForPtr(MI.getOperand(4).getGlobal());
612       else
613         assert(0 && "Unknown operand!");
614     }
615     break;
616   }
617 }