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