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