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