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