MC: First cut at MCFixup, for getting fixup/relocation information out of an MCCodeEm...
[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 *RelocOp, int DispVal,
72                              int64_t Adj, bool IsPCRel, 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 *RelocOp, int DispVal,
123                       int64_t Adj, bool IsPCRel, raw_ostream &OS) const {
124   // If this is a simple integer displacement that doesn't require a relocation,
125   // emit it now.
126   if (!RelocOp) {
127     EmitConstant(DispVal, 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,
163                                         raw_ostream &OS) const {
164   const MCOperand &Op3 = MI.getOperand(Op+3);
165   int DispVal = 0;
166   const MCOperand *DispForReloc = 0;
167   
168   // Figure out what sort of displacement we have to handle here.
169   if (Op3.isImm()) {
170     DispVal = Op3.getImm();
171   } else {
172     assert(0 && "relocatable operand");
173 #if 0
174   if (Op3.isGlobal()) {
175     DispForReloc = &Op3;
176   } else if (Op3.isSymbol()) {
177     DispForReloc = &Op3;
178   } else if (Op3.isCPI()) {
179     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
180       DispForReloc = &Op3;
181     } else {
182       DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
183       DispVal += Op3.getOffset();
184     }
185   } else {
186     assert(Op3.isJTI());
187     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
188       DispForReloc = &Op3;
189     } else {
190       DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
191     }
192 #endif
193   }
194   
195   const MCOperand &Base     = MI.getOperand(Op);
196   const MCOperand &Scale    = MI.getOperand(Op+1);
197   const MCOperand &IndexReg = MI.getOperand(Op+2);
198   unsigned BaseReg = Base.getReg();
199
200   // FIXME: Eliminate!
201   bool IsPCRel = false;
202     
203   // Determine whether a SIB byte is needed.
204   // If no BaseReg, issue a RIP relative instruction only if the MCE can 
205   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
206   // 2-7) and absolute references.
207   if (// The SIB byte must be used if there is an index register.
208       IndexReg.getReg() == 0 && 
209       // The SIB byte must be used if the base is ESP/RSP.
210       BaseReg != X86::ESP && BaseReg != X86::RSP &&
211       // If there is no base register and we're in 64-bit mode, we need a SIB
212       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
213       (!Is64BitMode || BaseReg != 0)) {
214
215     if (BaseReg == 0 ||          // [disp32]     in X86-32 mode
216         BaseReg == X86::RIP) {   // [disp32+RIP] in X86-64 mode
217       EmitByte(ModRMByte(0, RegOpcodeField, 5), OS);
218       EmitDisplacementField(DispForReloc, DispVal, PCAdj, true, OS);
219       return;
220     }
221     
222     unsigned BaseRegNo = GetX86RegNum(Base);
223
224     // If the base is not EBP/ESP and there is no displacement, use simple
225     // indirect register encoding, this handles addresses like [EAX].  The
226     // encoding for [EBP] with no displacement means [disp32] so we handle it
227     // by emitting a displacement of 0 below.
228     if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
229       EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), OS);
230       return;
231     }
232     
233     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
234     if (!DispForReloc && isDisp8(DispVal)) {
235       EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), OS);
236       EmitConstant(DispVal, 1, OS);
237       return;
238     }
239     
240     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
241     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), OS);
242     EmitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel, OS);
243     return;
244   }
245     
246   // We need a SIB byte, so start by outputting the ModR/M byte first
247   assert(IndexReg.getReg() != X86::ESP &&
248          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
249   
250   bool ForceDisp32 = false;
251   bool ForceDisp8  = false;
252   if (BaseReg == 0) {
253     // If there is no base register, we emit the special case SIB byte with
254     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
255     EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
256     ForceDisp32 = true;
257   } else if (DispForReloc) {
258     // Emit the normal disp32 encoding.
259     EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
260     ForceDisp32 = true;
261   } else if (DispVal == 0 && BaseReg != X86::EBP) {
262     // Emit no displacement ModR/M byte
263     EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
264   } else if (isDisp8(DispVal)) {
265     // Emit the disp8 encoding.
266     EmitByte(ModRMByte(1, RegOpcodeField, 4), OS);
267     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
268   } else {
269     // Emit the normal disp32 encoding.
270     EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
271   }
272   
273   // Calculate what the SS field value should be...
274   static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
275   unsigned SS = SSTable[Scale.getImm()];
276   
277   if (BaseReg == 0) {
278     // Handle the SIB byte for the case where there is no base, see Intel 
279     // Manual 2A, table 2-7. The displacement has already been output.
280     unsigned IndexRegNo;
281     if (IndexReg.getReg())
282       IndexRegNo = GetX86RegNum(IndexReg);
283     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
284       IndexRegNo = 4;
285     EmitSIBByte(SS, IndexRegNo, 5, OS);
286   } else {
287     unsigned IndexRegNo;
288     if (IndexReg.getReg())
289       IndexRegNo = GetX86RegNum(IndexReg);
290     else
291       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
292     EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), OS);
293   }
294   
295   // Do we need to output a displacement?
296   if (ForceDisp8)
297     EmitConstant(DispVal, 1, OS);
298   else if (DispVal != 0 || ForceDisp32)
299     EmitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel, OS);
300 }
301
302 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
303 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
304 /// size, and 3) use of X86-64 extended registers.
305 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
306                                    const TargetInstrDesc &Desc) {
307   unsigned REX = 0;
308   
309   // Pseudo instructions do not need REX prefix byte.
310   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
311     return 0;
312   if (TSFlags & X86II::REX_W)
313     REX |= 1 << 3;
314   
315   if (MI.getNumOperands() == 0) return REX;
316   
317   unsigned NumOps = MI.getNumOperands();
318   // FIXME: MCInst should explicitize the two-addrness.
319   bool isTwoAddr = NumOps > 1 &&
320                       Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
321   
322   // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
323   unsigned i = isTwoAddr ? 1 : 0;
324   for (; i != NumOps; ++i) {
325     const MCOperand &MO = MI.getOperand(i);
326     if (!MO.isReg()) continue;
327     unsigned Reg = MO.getReg();
328     if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
329     // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
330     // that returns non-zero.
331     REX |= 0x40;
332     break;
333   }
334   
335   switch (TSFlags & X86II::FormMask) {
336   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
337   case X86II::MRMSrcReg:
338     if (MI.getOperand(0).isReg() &&
339         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
340       REX |= 1 << 2;
341     i = isTwoAddr ? 2 : 1;
342     for (; i != NumOps; ++i) {
343       const MCOperand &MO = MI.getOperand(i);
344       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
345         REX |= 1 << 0;
346     }
347     break;
348   case X86II::MRMSrcMem: {
349     if (MI.getOperand(0).isReg() &&
350         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
351       REX |= 1 << 2;
352     unsigned Bit = 0;
353     i = isTwoAddr ? 2 : 1;
354     for (; i != NumOps; ++i) {
355       const MCOperand &MO = MI.getOperand(i);
356       if (MO.isReg()) {
357         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
358           REX |= 1 << Bit;
359         Bit++;
360       }
361     }
362     break;
363   }
364   case X86II::MRM0m: case X86II::MRM1m:
365   case X86II::MRM2m: case X86II::MRM3m:
366   case X86II::MRM4m: case X86II::MRM5m:
367   case X86II::MRM6m: case X86II::MRM7m:
368   case X86II::MRMDestMem: {
369     unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
370     i = isTwoAddr ? 1 : 0;
371     if (NumOps > e && MI.getOperand(e).isReg() &&
372         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
373       REX |= 1 << 2;
374     unsigned Bit = 0;
375     for (; i != e; ++i) {
376       const MCOperand &MO = MI.getOperand(i);
377       if (MO.isReg()) {
378         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
379           REX |= 1 << Bit;
380         Bit++;
381       }
382     }
383     break;
384   }
385   default:
386     if (MI.getOperand(0).isReg() &&
387         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
388       REX |= 1 << 0;
389     i = isTwoAddr ? 2 : 1;
390     for (unsigned e = NumOps; i != e; ++i) {
391       const MCOperand &MO = MI.getOperand(i);
392       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
393         REX |= 1 << 2;
394     }
395     break;
396   }
397   return REX;
398 }
399
400 void X86MCCodeEmitter::
401 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
402                   SmallVectorImpl<MCFixup> &Fixups) const {
403   unsigned Opcode = MI.getOpcode();
404   const TargetInstrDesc &Desc = TII.get(Opcode);
405   unsigned TSFlags = Desc.TSFlags;
406
407   // FIXME: We should emit the prefixes in exactly the same order as GAS does,
408   // in order to provide diffability.
409
410   // Emit the lock opcode prefix as needed.
411   if (TSFlags & X86II::LOCK)
412     EmitByte(0xF0, OS);
413   
414   // Emit segment override opcode prefix as needed.
415   switch (TSFlags & X86II::SegOvrMask) {
416   default: assert(0 && "Invalid segment!");
417   case 0: break;  // No segment override!
418   case X86II::FS:
419     EmitByte(0x64, OS);
420     break;
421   case X86II::GS:
422     EmitByte(0x65, OS);
423     break;
424   }
425   
426   // Emit the repeat opcode prefix as needed.
427   if ((TSFlags & X86II::Op0Mask) == X86II::REP)
428     EmitByte(0xF3, OS);
429   
430   // Emit the operand size opcode prefix as needed.
431   if (TSFlags & X86II::OpSize)
432     EmitByte(0x66, OS);
433   
434   // Emit the address size opcode prefix as needed.
435   if (TSFlags & X86II::AdSize)
436     EmitByte(0x67, OS);
437   
438   bool Need0FPrefix = false;
439   switch (TSFlags & X86II::Op0Mask) {
440   default: assert(0 && "Invalid prefix!");
441   case 0: break;  // No prefix!
442   case X86II::REP: break; // already handled.
443   case X86II::TB:  // Two-byte opcode prefix
444   case X86II::T8:  // 0F 38
445   case X86II::TA:  // 0F 3A
446     Need0FPrefix = true;
447     break;
448   case X86II::TF: // F2 0F 38
449     EmitByte(0xF2, OS);
450     Need0FPrefix = true;
451     break;
452   case X86II::XS:   // F3 0F
453     EmitByte(0xF3, OS);
454     Need0FPrefix = true;
455     break;
456   case X86II::XD:   // F2 0F
457     EmitByte(0xF2, OS);
458     Need0FPrefix = true;
459     break;
460   case X86II::D8: EmitByte(0xD8, OS); break;
461   case X86II::D9: EmitByte(0xD9, OS); break;
462   case X86II::DA: EmitByte(0xDA, OS); break;
463   case X86II::DB: EmitByte(0xDB, OS); break;
464   case X86II::DC: EmitByte(0xDC, OS); break;
465   case X86II::DD: EmitByte(0xDD, OS); break;
466   case X86II::DE: EmitByte(0xDE, OS); break;
467   case X86II::DF: EmitByte(0xDF, OS); break;
468   }
469   
470   // Handle REX prefix.
471   // FIXME: Can this come before F2 etc to simplify emission?
472   if (Is64BitMode) {
473     if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
474       EmitByte(0x40 | REX, OS);
475   }
476   
477   // 0x0F escape code must be emitted just before the opcode.
478   if (Need0FPrefix)
479     EmitByte(0x0F, OS);
480   
481   // FIXME: Pull this up into previous switch if REX can be moved earlier.
482   switch (TSFlags & X86II::Op0Mask) {
483   case X86II::TF:    // F2 0F 38
484   case X86II::T8:    // 0F 38
485     EmitByte(0x38, OS);
486     break;
487   case X86II::TA:    // 0F 3A
488     EmitByte(0x3A, OS);
489     break;
490   }
491   
492   // If this is a two-address instruction, skip one of the register operands.
493   unsigned NumOps = Desc.getNumOperands();
494   unsigned CurOp = 0;
495   if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
496     ++CurOp;
497   else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
498     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
499     --NumOps;
500   
501   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
502   switch (TSFlags & X86II::FormMask) {
503   case X86II::MRMInitReg:
504     assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
505   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
506       assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
507   case X86II::RawFrm: {
508     EmitByte(BaseOpcode, OS);
509     
510     if (CurOp == NumOps)
511       break;
512     
513     assert(0 && "Unimpl RawFrm expr");
514     break;
515   }
516       
517   case X86II::AddRegFrm: {
518     EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)),OS);
519     if (CurOp == NumOps)
520       break;
521
522     const MCOperand &MO1 = MI.getOperand(CurOp++);
523     if (MO1.isImm()) {
524       unsigned Size = X86II::getSizeOfImm(TSFlags);
525       EmitConstant(MO1.getImm(), Size, OS);
526       break;
527     }
528
529     assert(0 && "Unimpl AddRegFrm expr");
530     break;
531   }
532       
533   case X86II::MRMDestReg:
534     EmitByte(BaseOpcode, OS);
535     EmitRegModRMByte(MI.getOperand(CurOp),
536                      GetX86RegNum(MI.getOperand(CurOp+1)), OS);
537     CurOp += 2;
538     if (CurOp != NumOps)
539       EmitConstant(MI.getOperand(CurOp++).getImm(),
540                    X86II::getSizeOfImm(TSFlags), OS);
541     break;
542   
543   case X86II::MRMDestMem:
544     EmitByte(BaseOpcode, OS);
545     EmitMemModRMByte(MI, CurOp,
546                      GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
547                      0, OS);
548     CurOp += X86AddrNumOperands + 1;
549     if (CurOp != NumOps)
550       EmitConstant(MI.getOperand(CurOp++).getImm(),
551                    X86II::getSizeOfImm(TSFlags), OS);
552     break;
553       
554   case X86II::MRMSrcReg:
555     EmitByte(BaseOpcode, OS);
556     EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
557                      OS);
558     CurOp += 2;
559     if (CurOp != NumOps)
560       EmitConstant(MI.getOperand(CurOp++).getImm(),
561                    X86II::getSizeOfImm(TSFlags), OS);
562     break;
563     
564   case X86II::MRMSrcMem: {
565     EmitByte(BaseOpcode, OS);
566
567     // FIXME: Maybe lea should have its own form?  This is a horrible hack.
568     int AddrOperands;
569     if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
570         Opcode == X86::LEA16r || Opcode == X86::LEA32r)
571       AddrOperands = X86AddrNumOperands - 1; // No segment register
572     else
573       AddrOperands = X86AddrNumOperands;
574     
575     // FIXME: What is this actually doing?
576     intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
577        X86II::getSizeOfImm(TSFlags) : 0;
578     
579     EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
580                      PCAdj, OS);
581     CurOp += AddrOperands + 1;
582     if (CurOp != NumOps)
583       EmitConstant(MI.getOperand(CurOp++).getImm(),
584                    X86II::getSizeOfImm(TSFlags), OS);
585     break;
586   }
587
588   case X86II::MRM0r: case X86II::MRM1r:
589   case X86II::MRM2r: case X86II::MRM3r:
590   case X86II::MRM4r: case X86II::MRM5r:
591   case X86II::MRM6r: case X86II::MRM7r: {
592     EmitByte(BaseOpcode, OS);
593
594     // Special handling of lfence, mfence, monitor, and mwait.
595     // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
596     if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
597         Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
598       EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r, 0), OS);
599
600       switch (Opcode) {
601       default: break;
602       case X86::MONITOR: EmitByte(0xC8, OS); break;
603       case X86::MWAIT:   EmitByte(0xC9, OS); break;
604       }
605     } else {
606       EmitRegModRMByte(MI.getOperand(CurOp++),
607                        (TSFlags & X86II::FormMask)-X86II::MRM0r,
608                        OS);
609     }
610
611     if (CurOp == NumOps)
612       break;
613     
614     const MCOperand &MO1 = MI.getOperand(CurOp++);
615     if (MO1.isImm()) {
616       EmitConstant(MO1.getImm(), X86II::getSizeOfImm(TSFlags), OS);
617       break;
618     }
619
620     assert(0 && "relo unimpl");
621 #if 0
622     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
623       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
624     if (Opcode == X86::MOV64ri32)
625       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
626     if (MO1.isGlobal()) {
627       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
628       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
629                         Indirect);
630     } else if (MO1.isSymbol())
631       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
632     else if (MO1.isCPI())
633       emitConstPoolAddress(MO1.getIndex(), rt);
634     else if (MO1.isJTI())
635       emitJumpTableAddress(MO1.getIndex(), rt);
636     break;
637 #endif
638   }
639   case X86II::MRM0m: case X86II::MRM1m:
640   case X86II::MRM2m: case X86II::MRM3m:
641   case X86II::MRM4m: case X86II::MRM5m:
642   case X86II::MRM6m: case X86II::MRM7m: {
643     intptr_t PCAdj = 0;
644     if (CurOp + X86AddrNumOperands != NumOps) {
645       if (MI.getOperand(CurOp+X86AddrNumOperands).isImm())
646         PCAdj = X86II::getSizeOfImm(TSFlags);
647       else
648         PCAdj = 4;
649     }
650
651     EmitByte(BaseOpcode, OS);
652     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
653                      PCAdj, OS);
654     CurOp += X86AddrNumOperands;
655     
656     if (CurOp == NumOps)
657       break;
658     
659     const MCOperand &MO = MI.getOperand(CurOp++);
660     if (MO.isImm()) {
661       EmitConstant(MO.getImm(), X86II::getSizeOfImm(TSFlags), OS);
662       break;
663     }
664     
665     assert(0 && "relo not handled");
666 #if 0
667     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
668     : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
669     if (Opcode == X86::MOV64mi32)
670       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
671     if (MO.isGlobal()) {
672       bool Indirect = gvNeedsNonLazyPtr(MO, TM);
673       emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
674                         Indirect);
675     } else if (MO.isSymbol())
676       emitExternalSymbolAddress(MO.getSymbolName(), rt);
677     else if (MO.isCPI())
678       emitConstPoolAddress(MO.getIndex(), rt);
679     else if (MO.isJTI())
680       emitJumpTableAddress(MO.getIndex(), rt);
681 #endif
682     break;
683   }
684   }
685   
686 #ifndef NDEBUG
687   // FIXME: Verify.
688   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
689     errs() << "Cannot encode all operands of: ";
690     MI.dump();
691     errs() << '\n';
692     abort();
693   }
694 #endif
695 }