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