0e3d01470db59de62a7d44c1f60f49110a294f17
[oota-llvm.git] / lib / Target / X86 / X86MCCodeEmitter.cpp
1 //===-- X86/X86MCCodeEmitter.cpp - Convert X86 code to machine code -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the X86MCCodeEmitter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "x86-emitter"
15 #include "X86.h"
16 #include "X86InstrInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/Support/raw_ostream.h"
20 using namespace llvm;
21
22 // FIXME: This should move to a header.
23 namespace llvm {
24 namespace X86 {
25 enum Fixups {
26   reloc_pcrel_4byte = FirstTargetFixupKind,  // 32-bit pcrel, e.g. a branch.
27   reloc_pcrel_1byte,                         // 8-bit pcrel, e.g. branch_1
28   reloc_riprel_4byte                         // 32-bit rip-relative   
29 };
30 }
31 }
32
33 namespace {
34 class X86MCCodeEmitter : public MCCodeEmitter {
35   X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
36   void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
37   const TargetMachine &TM;
38   const TargetInstrInfo &TII;
39   bool Is64BitMode;
40 public:
41   X86MCCodeEmitter(TargetMachine &tm, bool is64Bit) 
42     : TM(tm), TII(*TM.getInstrInfo()) {
43     Is64BitMode = is64Bit;
44   }
45
46   ~X86MCCodeEmitter() {}
47
48   unsigned getNumFixupKinds() const {
49     return 3;
50   }
51
52   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
53     const static MCFixupKindInfo Infos[] = {
54       { "reloc_pcrel_4byte", 0, 4 * 8 },
55       { "reloc_pcrel_1byte", 0, 1 * 8 },
56       { "reloc_riprel_4byte", 0, 4 * 8 }
57     };
58     
59     if (Kind < FirstTargetFixupKind)
60       return MCCodeEmitter::getFixupKindInfo(Kind);
61
62     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
63            "Invalid kind!");
64     return Infos[Kind - FirstTargetFixupKind];
65   }
66   
67   static unsigned GetX86RegNum(const MCOperand &MO) {
68     return X86RegisterInfo::getX86RegNum(MO.getReg());
69   }
70   
71   void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
72     OS << (char)C;
73     ++CurByte;
74   }
75   
76   void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
77                     raw_ostream &OS) const {
78     // Output the constant in little endian byte order.
79     for (unsigned i = 0; i != Size; ++i) {
80       EmitByte(Val & 255, CurByte, OS);
81       Val >>= 8;
82     }
83   }
84
85   void EmitImmediate(const MCOperand &Disp, 
86                      unsigned ImmSize, MCFixupKind FixupKind,
87                      unsigned &CurByte, raw_ostream &OS,
88                      SmallVectorImpl<MCFixup> &Fixups,
89                      int ImmOffset = 0) const;
90   
91   inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
92                                         unsigned RM) {
93     assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
94     return RM | (RegOpcode << 3) | (Mod << 6);
95   }
96   
97   void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
98                         unsigned &CurByte, raw_ostream &OS) const {
99     EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
100   }
101   
102   void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
103                    unsigned &CurByte, raw_ostream &OS) const {
104     // SIB byte is in the same format as the ModRMByte.
105     EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
106   }
107   
108   
109   void EmitMemModRMByte(const MCInst &MI, unsigned Op,
110                         unsigned RegOpcodeField, 
111                         unsigned TSFlags, unsigned &CurByte, raw_ostream &OS,
112                         SmallVectorImpl<MCFixup> &Fixups) const;
113   
114   void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
115                          SmallVectorImpl<MCFixup> &Fixups) const;
116   
117 };
118
119 } // end anonymous namespace
120
121
122 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
123                                                TargetMachine &TM,
124                                                MCContext &Ctx) {
125   return new X86MCCodeEmitter(TM, false);
126 }
127
128 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
129                                                TargetMachine &TM,
130                                                MCContext &Ctx) {
131   return new X86MCCodeEmitter(TM, true);
132 }
133
134
135 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
136 /// sign-extended field. 
137 static bool isDisp8(int Value) {
138   return Value == (signed char)Value;
139 }
140
141 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
142 /// in an instruction with the specified TSFlags.
143 static MCFixupKind getImmFixupKind(unsigned TSFlags) {
144   unsigned Size = X86II::getSizeOfImm(TSFlags);
145   bool isPCRel = X86II::isImmPCRel(TSFlags);
146   
147   switch (Size) {
148   default: assert(0 && "Unknown immediate size");
149   case 1: return isPCRel ? MCFixupKind(X86::reloc_pcrel_1byte) : FK_Data_1;
150   case 4: return isPCRel ? MCFixupKind(X86::reloc_pcrel_4byte) : FK_Data_4;
151   case 2: assert(!isPCRel); return FK_Data_2;
152   case 8: assert(!isPCRel); return FK_Data_8;
153   }
154 }
155
156
157 void X86MCCodeEmitter::
158 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
159               unsigned &CurByte, raw_ostream &OS,
160               SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
161   // If this is a simple integer displacement that doesn't require a relocation,
162   // emit it now.
163   if (DispOp.isImm()) {
164     EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
165     return;
166   }
167
168   // If we have an immoffset, add it to the expression.
169   const MCExpr *Expr = DispOp.getExpr();
170   // FIXME: NO CONTEXT.
171   
172   // Emit a symbolic constant as a fixup and 4 zeros.
173   Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
174   EmitConstant(0, Size, CurByte, OS);
175 }
176
177
178 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
179                                         unsigned RegOpcodeField,
180                                         unsigned TSFlags, unsigned &CurByte,
181                                         raw_ostream &OS,
182                                         SmallVectorImpl<MCFixup> &Fixups) const{
183   const MCOperand &Disp     = MI.getOperand(Op+3);
184   const MCOperand &Base     = MI.getOperand(Op);
185   const MCOperand &Scale    = MI.getOperand(Op+1);
186   const MCOperand &IndexReg = MI.getOperand(Op+2);
187   unsigned BaseReg = Base.getReg();
188   
189   // Handle %rip relative addressing.
190   if (BaseReg == X86::RIP) {    // [disp32+RIP] in X86-64 mode
191     assert(IndexReg.getReg() == 0 && Is64BitMode &&
192            "Invalid rip-relative address");
193     EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
194     
195     // rip-relative addressing is actually relative to the *next* instruction.
196     // Since an immediate can follow the mod/rm byte for an instruction, this
197     // means that we need to bias the immediate field of the instruction with
198     // the size of the immediate field.  If we have this case, add it into the
199     // expression to emit.
200     int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
201     EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_riprel_4byte),
202                   CurByte, OS, Fixups, -ImmSize);
203     return;
204   }
205   
206   unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
207   
208   // Determine whether a SIB byte is needed.
209   // If no BaseReg, issue a RIP relative instruction only if the MCE can 
210   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
211   // 2-7) and absolute references.
212
213   if (// The SIB byte must be used if there is an index register.
214       IndexReg.getReg() == 0 && 
215       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
216       // encode to an R/M value of 4, which indicates that a SIB byte is
217       // present.
218       BaseRegNo != N86::ESP &&
219       // If there is no base register and we're in 64-bit mode, we need a SIB
220       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
221       (!Is64BitMode || BaseReg != 0)) {
222
223     if (BaseReg == 0) {          // [disp32]     in X86-32 mode
224       EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
225       EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
226       return;
227     }
228     
229     // If the base is not EBP/ESP and there is no displacement, use simple
230     // indirect register encoding, this handles addresses like [EAX].  The
231     // encoding for [EBP] with no displacement means [disp32] so we handle it
232     // by emitting a displacement of 0 below.
233     if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
234       EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
235       return;
236     }
237     
238     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
239     if (Disp.isImm() && isDisp8(Disp.getImm())) {
240       EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
241       EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
242       return;
243     }
244     
245     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
246     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
247     EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
248     return;
249   }
250     
251   // We need a SIB byte, so start by outputting the ModR/M byte first
252   assert(IndexReg.getReg() != X86::ESP &&
253          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
254   
255   bool ForceDisp32 = false;
256   bool ForceDisp8  = false;
257   if (BaseReg == 0) {
258     // If there is no base register, we emit the special case SIB byte with
259     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
260     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
261     ForceDisp32 = true;
262   } else if (!Disp.isImm()) {
263     // Emit the normal disp32 encoding.
264     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
265     ForceDisp32 = true;
266   } else if (Disp.getImm() == 0 && BaseReg != X86::EBP) {
267     // Emit no displacement ModR/M byte
268     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
269   } else if (isDisp8(Disp.getImm())) {
270     // Emit the disp8 encoding.
271     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
272     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
273   } else {
274     // Emit the normal disp32 encoding.
275     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
276   }
277   
278   // Calculate what the SS field value should be...
279   static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
280   unsigned SS = SSTable[Scale.getImm()];
281   
282   if (BaseReg == 0) {
283     // Handle the SIB byte for the case where there is no base, see Intel 
284     // Manual 2A, table 2-7. The displacement has already been output.
285     unsigned IndexRegNo;
286     if (IndexReg.getReg())
287       IndexRegNo = GetX86RegNum(IndexReg);
288     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
289       IndexRegNo = 4;
290     EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
291   } else {
292     unsigned IndexRegNo;
293     if (IndexReg.getReg())
294       IndexRegNo = GetX86RegNum(IndexReg);
295     else
296       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
297     EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
298   }
299   
300   // Do we need to output a displacement?
301   if (ForceDisp8)
302     EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
303   else if (ForceDisp32 || Disp.getImm() != 0)
304     EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
305 }
306
307 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
308 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
309 /// size, and 3) use of X86-64 extended registers.
310 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
311                                    const TargetInstrDesc &Desc) {
312   // Pseudo instructions shouldn't get here.
313   assert((TSFlags & X86II::FormMask) != X86II::Pseudo &&
314          "Can't encode pseudo instrs");
315   
316   unsigned REX = 0;
317   if (TSFlags & X86II::REX_W)
318     REX |= 1 << 3;
319   
320   if (MI.getNumOperands() == 0) return REX;
321   
322   unsigned NumOps = MI.getNumOperands();
323   // FIXME: MCInst should explicitize the two-addrness.
324   bool isTwoAddr = NumOps > 1 &&
325                       Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
326   
327   // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
328   unsigned i = isTwoAddr ? 1 : 0;
329   for (; i != NumOps; ++i) {
330     const MCOperand &MO = MI.getOperand(i);
331     if (!MO.isReg()) continue;
332     unsigned Reg = MO.getReg();
333     if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
334     // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
335     // that returns non-zero.
336     REX |= 0x40;
337     break;
338   }
339   
340   switch (TSFlags & X86II::FormMask) {
341   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
342   case X86II::MRMSrcReg:
343     if (MI.getOperand(0).isReg() &&
344         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
345       REX |= 1 << 2;
346     i = isTwoAddr ? 2 : 1;
347     for (; i != NumOps; ++i) {
348       const MCOperand &MO = MI.getOperand(i);
349       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
350         REX |= 1 << 0;
351     }
352     break;
353   case X86II::MRMSrcMem: {
354     if (MI.getOperand(0).isReg() &&
355         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
356       REX |= 1 << 2;
357     unsigned Bit = 0;
358     i = isTwoAddr ? 2 : 1;
359     for (; i != NumOps; ++i) {
360       const MCOperand &MO = MI.getOperand(i);
361       if (MO.isReg()) {
362         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
363           REX |= 1 << Bit;
364         Bit++;
365       }
366     }
367     break;
368   }
369   case X86II::MRM0m: case X86II::MRM1m:
370   case X86II::MRM2m: case X86II::MRM3m:
371   case X86II::MRM4m: case X86II::MRM5m:
372   case X86II::MRM6m: case X86II::MRM7m:
373   case X86II::MRMDestMem: {
374     unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
375     i = isTwoAddr ? 1 : 0;
376     if (NumOps > e && MI.getOperand(e).isReg() &&
377         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
378       REX |= 1 << 2;
379     unsigned Bit = 0;
380     for (; i != e; ++i) {
381       const MCOperand &MO = MI.getOperand(i);
382       if (MO.isReg()) {
383         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
384           REX |= 1 << Bit;
385         Bit++;
386       }
387     }
388     break;
389   }
390   default:
391     if (MI.getOperand(0).isReg() &&
392         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
393       REX |= 1 << 0;
394     i = isTwoAddr ? 2 : 1;
395     for (unsigned e = NumOps; i != e; ++i) {
396       const MCOperand &MO = MI.getOperand(i);
397       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
398         REX |= 1 << 2;
399     }
400     break;
401   }
402   return REX;
403 }
404
405 void X86MCCodeEmitter::
406 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
407                   SmallVectorImpl<MCFixup> &Fixups) const {
408   unsigned Opcode = MI.getOpcode();
409   const TargetInstrDesc &Desc = TII.get(Opcode);
410   unsigned TSFlags = Desc.TSFlags;
411
412   // Keep track of the current byte being emitted.
413   unsigned CurByte = 0;
414   
415   // FIXME: We should emit the prefixes in exactly the same order as GAS does,
416   // in order to provide diffability.
417
418   // Emit the lock opcode prefix as needed.
419   if (TSFlags & X86II::LOCK)
420     EmitByte(0xF0, CurByte, OS);
421   
422   // Emit segment override opcode prefix as needed.
423   switch (TSFlags & X86II::SegOvrMask) {
424   default: assert(0 && "Invalid segment!");
425   case 0: break;  // No segment override!
426   case X86II::FS:
427     EmitByte(0x64, CurByte, OS);
428     break;
429   case X86II::GS:
430     EmitByte(0x65, CurByte, OS);
431     break;
432   }
433   
434   // Emit the repeat opcode prefix as needed.
435   if ((TSFlags & X86II::Op0Mask) == X86II::REP)
436     EmitByte(0xF3, CurByte, OS);
437   
438   // Emit the operand size opcode prefix as needed.
439   if (TSFlags & X86II::OpSize)
440     EmitByte(0x66, CurByte, OS);
441   
442   // Emit the address size opcode prefix as needed.
443   if (TSFlags & X86II::AdSize)
444     EmitByte(0x67, CurByte, OS);
445   
446   bool Need0FPrefix = false;
447   switch (TSFlags & X86II::Op0Mask) {
448   default: assert(0 && "Invalid prefix!");
449   case 0: break;  // No prefix!
450   case X86II::REP: break; // already handled.
451   case X86II::TB:  // Two-byte opcode prefix
452   case X86II::T8:  // 0F 38
453   case X86II::TA:  // 0F 3A
454     Need0FPrefix = true;
455     break;
456   case X86II::TF: // F2 0F 38
457     EmitByte(0xF2, CurByte, OS);
458     Need0FPrefix = true;
459     break;
460   case X86II::XS:   // F3 0F
461     EmitByte(0xF3, CurByte, OS);
462     Need0FPrefix = true;
463     break;
464   case X86II::XD:   // F2 0F
465     EmitByte(0xF2, CurByte, OS);
466     Need0FPrefix = true;
467     break;
468   case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
469   case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
470   case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
471   case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
472   case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
473   case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
474   case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
475   case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
476   }
477   
478   // Handle REX prefix.
479   // FIXME: Can this come before F2 etc to simplify emission?
480   if (Is64BitMode) {
481     if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
482       EmitByte(0x40 | REX, CurByte, OS);
483   }
484   
485   // 0x0F escape code must be emitted just before the opcode.
486   if (Need0FPrefix)
487     EmitByte(0x0F, CurByte, OS);
488   
489   // FIXME: Pull this up into previous switch if REX can be moved earlier.
490   switch (TSFlags & X86II::Op0Mask) {
491   case X86II::TF:    // F2 0F 38
492   case X86II::T8:    // 0F 38
493     EmitByte(0x38, CurByte, OS);
494     break;
495   case X86II::TA:    // 0F 3A
496     EmitByte(0x3A, CurByte, OS);
497     break;
498   }
499   
500   // If this is a two-address instruction, skip one of the register operands.
501   unsigned NumOps = Desc.getNumOperands();
502   unsigned CurOp = 0;
503   if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
504     ++CurOp;
505   else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
506     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
507     --NumOps;
508   
509   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
510   switch (TSFlags & X86II::FormMask) {
511   case X86II::MRMInitReg:
512     assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
513   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
514     assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
515   case X86II::RawFrm:
516     EmitByte(BaseOpcode, CurByte, OS);
517     break;
518       
519   case X86II::AddRegFrm:
520     EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
521     break;
522       
523   case X86II::MRMDestReg:
524     EmitByte(BaseOpcode, CurByte, OS);
525     EmitRegModRMByte(MI.getOperand(CurOp),
526                      GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
527     CurOp += 2;
528     break;
529   
530   case X86II::MRMDestMem:
531     EmitByte(BaseOpcode, CurByte, OS);
532     EmitMemModRMByte(MI, CurOp,
533                      GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
534                      TSFlags, CurByte, OS, Fixups);
535     CurOp += X86AddrNumOperands + 1;
536     break;
537       
538   case X86II::MRMSrcReg:
539     EmitByte(BaseOpcode, CurByte, OS);
540     EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
541                      CurByte, OS);
542     CurOp += 2;
543     break;
544     
545   case X86II::MRMSrcMem: {
546     EmitByte(BaseOpcode, CurByte, OS);
547
548     // FIXME: Maybe lea should have its own form?  This is a horrible hack.
549     int AddrOperands;
550     if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
551         Opcode == X86::LEA16r || Opcode == X86::LEA32r)
552       AddrOperands = X86AddrNumOperands - 1; // No segment register
553     else
554       AddrOperands = X86AddrNumOperands;
555     
556     EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
557                      TSFlags, CurByte, OS, Fixups);
558     CurOp += AddrOperands + 1;
559     break;
560   }
561
562   case X86II::MRM0r: case X86II::MRM1r:
563   case X86II::MRM2r: case X86II::MRM3r:
564   case X86II::MRM4r: case X86II::MRM5r:
565   case X86II::MRM6r: case X86II::MRM7r:
566     EmitByte(BaseOpcode, CurByte, OS);
567
568     // Special handling of lfence, mfence, monitor, and mwait.
569     // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
570     if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
571         Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
572       EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r,
573                          Opcode == X86::MWAIT),
574                CurByte, OS);
575     } else {
576       EmitRegModRMByte(MI.getOperand(CurOp++),
577                        (TSFlags & X86II::FormMask)-X86II::MRM0r,
578                        CurByte, OS);
579     }
580     break;
581   case X86II::MRM0m: case X86II::MRM1m:
582   case X86II::MRM2m: case X86II::MRM3m:
583   case X86II::MRM4m: case X86II::MRM5m:
584   case X86II::MRM6m: case X86II::MRM7m:
585     EmitByte(BaseOpcode, CurByte, OS);
586     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
587                      TSFlags, CurByte, OS, Fixups);
588     CurOp += X86AddrNumOperands;
589     break;
590   case X86II::MRM_C1:
591     EmitByte(BaseOpcode, CurByte, OS);
592     EmitByte(0xC1, CurByte, OS);
593     break;
594   case X86II::MRM_C8:
595     EmitByte(BaseOpcode, CurByte, OS);
596     EmitByte(0xC8, CurByte, OS);
597     break;
598   case X86II::MRM_C9:
599     EmitByte(BaseOpcode, CurByte, OS);
600     EmitByte(0xC9, CurByte, OS);
601     break;
602   case X86II::MRM_E8:
603     EmitByte(BaseOpcode, CurByte, OS);
604     EmitByte(0xE8, CurByte, OS);
605     break;
606   case X86II::MRM_F0:
607     EmitByte(BaseOpcode, CurByte, OS);
608     EmitByte(0xF0, CurByte, OS);
609     break;
610   }
611   
612   // If there is a remaining operand, it must be a trailing immediate.  Emit it
613   // according to the right size for the instruction.
614   // FIXME: This should pass in whether the value is pc relative or not.  This
615   // information should be aquired from TSFlags as well.
616   if (CurOp != NumOps)
617     EmitImmediate(MI.getOperand(CurOp++),
618                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
619                   CurByte, OS, Fixups);
620   
621 #ifndef NDEBUG
622   // FIXME: Verify.
623   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
624     errs() << "Cannot encode all operands of: ";
625     MI.dump();
626     errs() << '\n';
627     abort();
628   }
629 #endif
630 }