Fix comment from previous patch
[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 "X86FixupKinds.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/Support/raw_ostream.h"
22 using namespace llvm;
23
24 namespace {
25 class X86MCCodeEmitter : public MCCodeEmitter {
26   X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
27   void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
28   const TargetMachine &TM;
29   const TargetInstrInfo &TII;
30   MCContext &Ctx;
31   bool Is64BitMode;
32 public:
33   X86MCCodeEmitter(TargetMachine &tm, MCContext &ctx, bool is64Bit) 
34     : TM(tm), TII(*TM.getInstrInfo()), Ctx(ctx) {
35     Is64BitMode = is64Bit;
36   }
37
38   ~X86MCCodeEmitter() {}
39
40   unsigned getNumFixupKinds() const {
41     return 4;
42   }
43
44   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
45     const static MCFixupKindInfo Infos[] = {
46       { "reloc_pcrel_4byte", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel },
47       { "reloc_pcrel_1byte", 0, 1 * 8, MCFixupKindInfo::FKF_IsPCRel },
48       { "reloc_riprel_4byte", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel },
49       { "reloc_riprel_4byte_movq_load", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel }
50     };
51     
52     if (Kind < FirstTargetFixupKind)
53       return MCCodeEmitter::getFixupKindInfo(Kind);
54
55     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
56            "Invalid kind!");
57     return Infos[Kind - FirstTargetFixupKind];
58   }
59   
60   static unsigned GetX86RegNum(const MCOperand &MO) {
61     return X86RegisterInfo::getX86RegNum(MO.getReg());
62   }
63
64   // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
65   // 0-7 and the difference between the 2 groups is given by the REX prefix.
66   // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
67   // in 1's complement form, example:
68   //
69   //  ModRM field => XMM9 => 1
70   //  VEX.VVVV    => XMM9 => ~9
71   //
72   // See table 4-35 of Intel AVX Programming Reference for details.
73   static unsigned char getVEXRegisterEncoding(const MCInst &MI,
74                                               unsigned OpNum) {
75     unsigned SrcReg = MI.getOperand(OpNum).getReg();
76     unsigned SrcRegNum = GetX86RegNum(MI.getOperand(OpNum));
77     if (SrcReg >= X86::XMM8 && SrcReg <= X86::XMM15)
78       SrcRegNum += 8;
79   
80     // The registers represented through VEX_VVVV should
81     // be encoded in 1's complement form.
82     return (~SrcRegNum) & 0xf;
83   }
84   
85   void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
86     OS << (char)C;
87     ++CurByte;
88   }
89   
90   void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
91                     raw_ostream &OS) const {
92     // Output the constant in little endian byte order.
93     for (unsigned i = 0; i != Size; ++i) {
94       EmitByte(Val & 255, CurByte, OS);
95       Val >>= 8;
96     }
97   }
98
99   void EmitImmediate(const MCOperand &Disp, 
100                      unsigned ImmSize, MCFixupKind FixupKind,
101                      unsigned &CurByte, raw_ostream &OS,
102                      SmallVectorImpl<MCFixup> &Fixups,
103                      int ImmOffset = 0) const;
104   
105   inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
106                                         unsigned RM) {
107     assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
108     return RM | (RegOpcode << 3) | (Mod << 6);
109   }
110   
111   void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
112                         unsigned &CurByte, raw_ostream &OS) const {
113     EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
114   }
115   
116   void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
117                    unsigned &CurByte, raw_ostream &OS) const {
118     // SIB byte is in the same format as the ModRMByte.
119     EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
120   }
121   
122   
123   void EmitSegmentOverridePrefix(const MCOperand &Op, unsigned TSFlags,
124                                  unsigned &CurByte, raw_ostream &OS) const;
125
126   void EmitMemModRMByte(const MCInst &MI, unsigned Op,
127                         unsigned RegOpcodeField, 
128                         uint64_t TSFlags, unsigned &CurByte, raw_ostream &OS,
129                         SmallVectorImpl<MCFixup> &Fixups) const;
130   
131   void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
132                          SmallVectorImpl<MCFixup> &Fixups) const;
133   
134   void EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
135                            const MCInst &MI, const TargetInstrDesc &Desc,
136                            raw_ostream &OS) const;
137
138   void EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
139                         const MCInst &MI, const TargetInstrDesc &Desc,
140                         raw_ostream &OS) const;
141 };
142
143 } // end anonymous namespace
144
145
146 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
147                                                TargetMachine &TM,
148                                                MCContext &Ctx) {
149   return new X86MCCodeEmitter(TM, Ctx, false);
150 }
151
152 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
153                                                TargetMachine &TM,
154                                                MCContext &Ctx) {
155   return new X86MCCodeEmitter(TM, Ctx, true);
156 }
157
158 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
159 /// sign-extended field. 
160 static bool isDisp8(int Value) {
161   return Value == (signed char)Value;
162 }
163
164 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
165 /// in an instruction with the specified TSFlags.
166 static MCFixupKind getImmFixupKind(uint64_t TSFlags) {
167   unsigned Size = X86II::getSizeOfImm(TSFlags);
168   bool isPCRel = X86II::isImmPCRel(TSFlags);
169   
170   switch (Size) {
171   default: assert(0 && "Unknown immediate size");
172   case 1: return isPCRel ? MCFixupKind(X86::reloc_pcrel_1byte) : FK_Data_1;
173   case 4: return isPCRel ? MCFixupKind(X86::reloc_pcrel_4byte) : FK_Data_4;
174   case 2: assert(!isPCRel); return FK_Data_2;
175   case 8: assert(!isPCRel); return FK_Data_8;
176   }
177 }
178
179
180 void X86MCCodeEmitter::
181 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
182               unsigned &CurByte, raw_ostream &OS,
183               SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
184   // If this is a simple integer displacement that doesn't require a relocation,
185   // emit it now.
186   if (DispOp.isImm()) {
187     // FIXME: is this right for pc-rel encoding??  Probably need to emit this as
188     // a fixup if so.
189     EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
190     return;
191   }
192
193   // If we have an immoffset, add it to the expression.
194   const MCExpr *Expr = DispOp.getExpr();
195   
196   // If the fixup is pc-relative, we need to bias the value to be relative to
197   // the start of the field, not the end of the field.
198   if (FixupKind == MCFixupKind(X86::reloc_pcrel_4byte) ||
199       FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
200       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load))
201     ImmOffset -= 4;
202   if (FixupKind == MCFixupKind(X86::reloc_pcrel_1byte))
203     ImmOffset -= 1;
204   
205   if (ImmOffset)
206     Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(ImmOffset, Ctx),
207                                    Ctx);
208   
209   // Emit a symbolic constant as a fixup and 4 zeros.
210   Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
211   EmitConstant(0, Size, CurByte, OS);
212 }
213
214 void X86MCCodeEmitter::EmitSegmentOverridePrefix(const MCOperand &Op,
215                                                  unsigned TSFlags,
216                                                  unsigned &CurByte,
217                                                  raw_ostream &OS) const {
218   // If no segment register is present, we don't need anything.
219   if (Op.getReg() == 0)
220     return;
221
222   // Check if we need an override.
223   switch (Op.getReg()) {
224   case X86::CS: EmitByte(0x2E, CurByte, OS); return;
225   case X86::SS: EmitByte(0x36, CurByte, OS); return;
226   case X86::DS: EmitByte(0x3E, CurByte, OS); return;
227   case X86::ES: EmitByte(0x26, CurByte, OS); return;
228   case X86::FS: EmitByte(0x64, CurByte, OS); return;
229   case X86::GS: EmitByte(0x65, CurByte, OS); return;
230   }
231
232   assert(0 && "Invalid segment register!");
233 }
234
235 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
236                                         unsigned RegOpcodeField,
237                                         uint64_t TSFlags, unsigned &CurByte,
238                                         raw_ostream &OS,
239                                         SmallVectorImpl<MCFixup> &Fixups) const{
240   const MCOperand &Disp     = MI.getOperand(Op+3);
241   const MCOperand &Base     = MI.getOperand(Op);
242   const MCOperand &Scale    = MI.getOperand(Op+1);
243   const MCOperand &IndexReg = MI.getOperand(Op+2);
244   unsigned BaseReg = Base.getReg();
245   
246   // Handle %rip relative addressing.
247   if (BaseReg == X86::RIP) {    // [disp32+RIP] in X86-64 mode
248     assert(Is64BitMode && "Rip-relative addressing requires 64-bit mode");
249     assert(IndexReg.getReg() == 0 && "Invalid rip-relative address");
250     EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
251     
252     unsigned FixupKind = X86::reloc_riprel_4byte;
253     
254     // movq loads are handled with a special relocation form which allows the
255     // linker to eliminate some loads for GOT references which end up in the
256     // same linkage unit.
257     if (MI.getOpcode() == X86::MOV64rm ||
258         MI.getOpcode() == X86::MOV64rm_TC)
259       FixupKind = X86::reloc_riprel_4byte_movq_load;
260     
261     // rip-relative addressing is actually relative to the *next* instruction.
262     // Since an immediate can follow the mod/rm byte for an instruction, this
263     // means that we need to bias the immediate field of the instruction with
264     // the size of the immediate field.  If we have this case, add it into the
265     // expression to emit.
266     int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
267     
268     EmitImmediate(Disp, 4, MCFixupKind(FixupKind),
269                   CurByte, OS, Fixups, -ImmSize);
270     return;
271   }
272   
273   unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
274   
275   // Determine whether a SIB byte is needed.
276   // If no BaseReg, issue a RIP relative instruction only if the MCE can 
277   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
278   // 2-7) and absolute references.
279
280   if (// The SIB byte must be used if there is an index register.
281       IndexReg.getReg() == 0 && 
282       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
283       // encode to an R/M value of 4, which indicates that a SIB byte is
284       // present.
285       BaseRegNo != N86::ESP &&
286       // If there is no base register and we're in 64-bit mode, we need a SIB
287       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
288       (!Is64BitMode || BaseReg != 0)) {
289
290     if (BaseReg == 0) {          // [disp32]     in X86-32 mode
291       EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
292       EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
293       return;
294     }
295     
296     // If the base is not EBP/ESP and there is no displacement, use simple
297     // indirect register encoding, this handles addresses like [EAX].  The
298     // encoding for [EBP] with no displacement means [disp32] so we handle it
299     // by emitting a displacement of 0 below.
300     if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
301       EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
302       return;
303     }
304     
305     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
306     if (Disp.isImm() && isDisp8(Disp.getImm())) {
307       EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
308       EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
309       return;
310     }
311     
312     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
313     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
314     EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
315     return;
316   }
317     
318   // We need a SIB byte, so start by outputting the ModR/M byte first
319   assert(IndexReg.getReg() != X86::ESP &&
320          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
321   
322   bool ForceDisp32 = false;
323   bool ForceDisp8  = false;
324   if (BaseReg == 0) {
325     // If there is no base register, we emit the special case SIB byte with
326     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
327     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
328     ForceDisp32 = true;
329   } else if (!Disp.isImm()) {
330     // Emit the normal disp32 encoding.
331     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
332     ForceDisp32 = true;
333   } else if (Disp.getImm() == 0 &&
334              // Base reg can't be anything that ends up with '5' as the base
335              // reg, it is the magic [*] nomenclature that indicates no base.
336              BaseRegNo != N86::EBP) {
337     // Emit no displacement ModR/M byte
338     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
339   } else if (isDisp8(Disp.getImm())) {
340     // Emit the disp8 encoding.
341     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
342     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
343   } else {
344     // Emit the normal disp32 encoding.
345     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
346   }
347   
348   // Calculate what the SS field value should be...
349   static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
350   unsigned SS = SSTable[Scale.getImm()];
351   
352   if (BaseReg == 0) {
353     // Handle the SIB byte for the case where there is no base, see Intel 
354     // Manual 2A, table 2-7. The displacement has already been output.
355     unsigned IndexRegNo;
356     if (IndexReg.getReg())
357       IndexRegNo = GetX86RegNum(IndexReg);
358     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
359       IndexRegNo = 4;
360     EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
361   } else {
362     unsigned IndexRegNo;
363     if (IndexReg.getReg())
364       IndexRegNo = GetX86RegNum(IndexReg);
365     else
366       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
367     EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
368   }
369   
370   // Do we need to output a displacement?
371   if (ForceDisp8)
372     EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
373   else if (ForceDisp32 || Disp.getImm() != 0)
374     EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
375 }
376
377 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode prefix
378 /// called VEX.
379 void X86MCCodeEmitter::EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
380                             const MCInst &MI, const TargetInstrDesc &Desc,
381                             raw_ostream &OS) const {
382
383   // Pseudo instructions never have a VEX prefix.
384   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
385     return;
386
387   bool HasVEX_4V = false;
388   if ((TSFlags >> 32) & X86II::VEX_4V)
389     HasVEX_4V = true;
390
391   // VEX_R: opcode externsion equivalent to REX.R in
392   // 1's complement (inverted) form
393   //
394   //  1: Same as REX_R=0 (must be 1 in 32-bit mode)
395   //  0: Same as REX_R=1 (64 bit mode only)
396   //
397   unsigned char VEX_R = 0x1;
398
399   // VEX_X: equivalent to REX.X, only used when a
400   // register is used for index in SIB Byte.
401   //
402   //  1: Same as REX.X=0 (must be 1 in 32-bit mode)
403   //  0: Same as REX.X=1 (64-bit mode only)
404   unsigned char VEX_X = 0x1;
405
406   // VEX_B:
407   //
408   //  1: Same as REX_B=0 (ignored in 32-bit mode)
409   //  0: Same as REX_B=1 (64 bit mode only)
410   //
411   unsigned char VEX_B = 0x1;
412
413   // VEX_W: opcode specific (use like REX.W, or used for
414   // opcode extension, or ignored, depending on the opcode byte)
415   unsigned char VEX_W = 0;
416
417   // VEX_5M (VEX m-mmmmm field):
418   //
419   //  0b00000: Reserved for future use
420   //  0b00001: implied 0F leading opcode
421   //  0b00010: implied 0F 38 leading opcode bytes
422   //  0b00011: implied 0F 3A leading opcode bytes
423   //  0b00100-0b11111: Reserved for future use
424   //
425   unsigned char VEX_5M = 0x1;
426
427   // VEX_4V (VEX vvvv field): a register specifier
428   // (in 1's complement form) or 1111 if unused.
429   unsigned char VEX_4V = 0xf;
430
431   // VEX_L (Vector Length):
432   //
433   //  0: scalar or 128-bit vector
434   //  1: 256-bit vector
435   //
436   unsigned char VEX_L = 0;
437
438   // VEX_PP: opcode extension providing equivalent
439   // functionality of a SIMD prefix
440   //
441   //  0b00: None
442   //  0b01: 66
443   //  0b10: F3
444   //  0b11: F2
445   //
446   unsigned char VEX_PP = 0;
447
448   // Encode the operand size opcode prefix as needed.
449   if (TSFlags & X86II::OpSize)
450     VEX_PP = 0x01;
451
452   if ((TSFlags >> 32) & X86II::VEX_W)
453     VEX_W = 1;
454
455   switch (TSFlags & X86II::Op0Mask) {
456   default: assert(0 && "Invalid prefix!");
457   case X86II::T8:  // 0F 38
458     VEX_5M = 0x2;
459     break;
460   case X86II::TA:  // 0F 3A
461     VEX_5M = 0x3;
462     break;
463   case X86II::TF:  // F2 0F 38
464     VEX_PP = 0x3;
465     VEX_5M = 0x2;
466     break;
467   case X86II::XS:  // F3 0F
468     VEX_PP = 0x2;
469     break;
470   case X86II::XD:  // F2 0F
471     VEX_PP = 0x3;
472     break;
473   case X86II::TB:  // Bypass: Not used by VEX
474   case 0:
475     break;  // No prefix!
476   }
477
478   unsigned NumOps = MI.getNumOperands();
479   unsigned CurOp = 0;
480
481   switch (TSFlags & X86II::FormMask) {
482   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
483   case X86II::MRM0m: case X86II::MRM1m:
484   case X86II::MRM2m: case X86II::MRM3m:
485   case X86II::MRM4m: case X86II::MRM5m:
486   case X86II::MRM6m: case X86II::MRM7m:
487   case X86II::MRMDestMem:
488     NumOps = CurOp = X86AddrNumOperands;
489   case X86II::MRMSrcMem:
490   case X86II::MRMSrcReg:
491     if (MI.getNumOperands() > CurOp && MI.getOperand(CurOp).isReg() &&
492         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
493       VEX_R = 0x0;
494
495     // CurOp and NumOps are equal when VEX_R represents a register used
496     // to index a memory destination (which is the last operand)
497     CurOp = (CurOp == NumOps) ? 0 : CurOp+1;
498
499     if (HasVEX_4V) {
500       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
501       CurOp++;
502     }
503
504     // If the last register should be encoded in the immediate field
505     // do not use any bit from VEX prefix to this register, ignore it
506     if ((TSFlags >> 32) & X86II::VEX_I8IMM)
507       NumOps--;
508
509     for (; CurOp != NumOps; ++CurOp) {
510       const MCOperand &MO = MI.getOperand(CurOp);
511       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
512         VEX_B = 0x0;
513       if (!VEX_B && MO.isReg() &&
514           ((TSFlags & X86II::FormMask) == X86II::MRMSrcMem) &&
515           X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
516         VEX_X = 0x0;
517     }
518     break;
519   default: // MRMDestReg, MRM0r-MRM7r
520     if (MI.getOperand(CurOp).isReg() &&
521         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
522       VEX_B = 0;
523
524     if (HasVEX_4V)
525       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
526
527     CurOp++;
528     for (; CurOp != NumOps; ++CurOp) {
529       const MCOperand &MO = MI.getOperand(CurOp);
530       if (MO.isReg() && !HasVEX_4V &&
531           X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
532         VEX_R = 0x0;
533     }
534     break;
535     assert(0 && "Not implemented!");
536   }
537
538   // VEX opcode prefix can have 2 or 3 bytes
539   //
540   //  3 bytes:
541   //    +-----+ +--------------+ +-------------------+
542   //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
543   //    +-----+ +--------------+ +-------------------+
544   //  2 bytes:
545   //    +-----+ +-------------------+
546   //    | C5h | | R | vvvv | L | pp |
547   //    +-----+ +-------------------+
548   //
549   unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
550
551   if (VEX_B && VEX_X && !VEX_W && (VEX_5M == 1)) { // 2 byte VEX prefix
552     EmitByte(0xC5, CurByte, OS);
553     EmitByte(LastByte | (VEX_R << 7), CurByte, OS);
554     return;
555   }
556
557   // 3 byte VEX prefix
558   EmitByte(0xC4, CurByte, OS);
559   EmitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, CurByte, OS);
560   EmitByte(LastByte | (VEX_W << 7), CurByte, OS);
561 }
562
563 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
564 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
565 /// size, and 3) use of X86-64 extended registers.
566 static unsigned DetermineREXPrefix(const MCInst &MI, uint64_t TSFlags,
567                                    const TargetInstrDesc &Desc) {
568   // Pseudo instructions never have a rex byte.
569   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
570     return 0;
571   
572   unsigned REX = 0;
573   if (TSFlags & X86II::REX_W)
574     REX |= 1 << 3; // set REX.W
575   
576   if (MI.getNumOperands() == 0) return REX;
577   
578   unsigned NumOps = MI.getNumOperands();
579   // FIXME: MCInst should explicitize the two-addrness.
580   bool isTwoAddr = NumOps > 1 &&
581                       Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
582   
583   // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
584   unsigned i = isTwoAddr ? 1 : 0;
585   for (; i != NumOps; ++i) {
586     const MCOperand &MO = MI.getOperand(i);
587     if (!MO.isReg()) continue;
588     unsigned Reg = MO.getReg();
589     if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
590     // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
591     // that returns non-zero.
592     REX |= 0x40; // REX fixed encoding prefix
593     break;
594   }
595   
596   switch (TSFlags & X86II::FormMask) {
597   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
598   case X86II::MRMSrcReg:
599     if (MI.getOperand(0).isReg() &&
600         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
601       REX |= 1 << 2; // set REX.R
602     i = isTwoAddr ? 2 : 1;
603     for (; i != NumOps; ++i) {
604       const MCOperand &MO = MI.getOperand(i);
605       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
606         REX |= 1 << 0; // set REX.B
607     }
608     break;
609   case X86II::MRMSrcMem: {
610     if (MI.getOperand(0).isReg() &&
611         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
612       REX |= 1 << 2; // set REX.R
613     unsigned Bit = 0;
614     i = isTwoAddr ? 2 : 1;
615     for (; i != NumOps; ++i) {
616       const MCOperand &MO = MI.getOperand(i);
617       if (MO.isReg()) {
618         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
619           REX |= 1 << Bit; // set REX.B (Bit=0) and REX.X (Bit=1)
620         Bit++;
621       }
622     }
623     break;
624   }
625   case X86II::MRM0m: case X86II::MRM1m:
626   case X86II::MRM2m: case X86II::MRM3m:
627   case X86II::MRM4m: case X86II::MRM5m:
628   case X86II::MRM6m: case X86II::MRM7m:
629   case X86II::MRMDestMem: {
630     unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
631     i = isTwoAddr ? 1 : 0;
632     if (NumOps > e && MI.getOperand(e).isReg() &&
633         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
634       REX |= 1 << 2; // set REX.R
635     unsigned Bit = 0;
636     for (; i != e; ++i) {
637       const MCOperand &MO = MI.getOperand(i);
638       if (MO.isReg()) {
639         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
640           REX |= 1 << Bit; // REX.B (Bit=0) and REX.X (Bit=1)
641         Bit++;
642       }
643     }
644     break;
645   }
646   default:
647     if (MI.getOperand(0).isReg() &&
648         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
649       REX |= 1 << 0; // set REX.B
650     i = isTwoAddr ? 2 : 1;
651     for (unsigned e = NumOps; i != e; ++i) {
652       const MCOperand &MO = MI.getOperand(i);
653       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
654         REX |= 1 << 2; // set REX.R
655     }
656     break;
657   }
658   return REX;
659 }
660
661 /// EmitOpcodePrefix - Emit all instruction prefixes prior to the opcode.
662 void X86MCCodeEmitter::EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
663                                         const MCInst &MI, 
664                                         const TargetInstrDesc &Desc,
665                                         raw_ostream &OS) const {
666
667   // Emit the lock opcode prefix as needed.
668   if (TSFlags & X86II::LOCK)
669     EmitByte(0xF0, CurByte, OS);
670   
671   // Emit segment override opcode prefix as needed.
672   switch (TSFlags & X86II::SegOvrMask) {
673   default: assert(0 && "Invalid segment!");
674   case 0: break;  // No segment override!
675   case X86II::FS:
676     EmitByte(0x64, CurByte, OS);
677     break;
678   case X86II::GS:
679     EmitByte(0x65, CurByte, OS);
680     break;
681   }
682   
683   // Emit the repeat opcode prefix as needed.
684   if ((TSFlags & X86II::Op0Mask) == X86II::REP)
685     EmitByte(0xF3, CurByte, OS);
686   
687   // Emit the operand size opcode prefix as needed.
688   if (TSFlags & X86II::OpSize)
689     EmitByte(0x66, CurByte, OS);
690   
691   // Emit the address size opcode prefix as needed.
692   if (TSFlags & X86II::AdSize)
693     EmitByte(0x67, CurByte, OS);
694   
695   bool Need0FPrefix = false;
696   switch (TSFlags & X86II::Op0Mask) {
697   default: assert(0 && "Invalid prefix!");
698   case 0: break;  // No prefix!
699   case X86II::REP: break; // already handled.
700   case X86II::TB:  // Two-byte opcode prefix
701   case X86II::T8:  // 0F 38
702   case X86II::TA:  // 0F 3A
703     Need0FPrefix = true;
704     break;
705   case X86II::TF: // F2 0F 38
706     EmitByte(0xF2, CurByte, OS);
707     Need0FPrefix = true;
708     break;
709   case X86II::XS:   // F3 0F
710     EmitByte(0xF3, CurByte, OS);
711     Need0FPrefix = true;
712     break;
713   case X86II::XD:   // F2 0F
714     EmitByte(0xF2, CurByte, OS);
715     Need0FPrefix = true;
716     break;
717   case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
718   case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
719   case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
720   case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
721   case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
722   case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
723   case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
724   case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
725   }
726   
727   // Handle REX prefix.
728   // FIXME: Can this come before F2 etc to simplify emission?
729   if (Is64BitMode) {
730     if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
731       EmitByte(0x40 | REX, CurByte, OS);
732   }
733   
734   // 0x0F escape code must be emitted just before the opcode.
735   if (Need0FPrefix)
736     EmitByte(0x0F, CurByte, OS);
737   
738   // FIXME: Pull this up into previous switch if REX can be moved earlier.
739   switch (TSFlags & X86II::Op0Mask) {
740   case X86II::TF:    // F2 0F 38
741   case X86II::T8:    // 0F 38
742     EmitByte(0x38, CurByte, OS);
743     break;
744   case X86II::TA:    // 0F 3A
745     EmitByte(0x3A, CurByte, OS);
746     break;
747   }
748 }
749
750 void X86MCCodeEmitter::
751 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
752                   SmallVectorImpl<MCFixup> &Fixups) const {
753   unsigned Opcode = MI.getOpcode();
754   const TargetInstrDesc &Desc = TII.get(Opcode);
755   uint64_t TSFlags = Desc.TSFlags;
756
757   // Keep track of the current byte being emitted.
758   unsigned CurByte = 0;
759   
760   // Is this instruction encoded using the AVX VEX prefix?
761   bool HasVEXPrefix = false;
762
763   // It uses the VEX.VVVV field?
764   bool HasVEX_4V = false;
765
766   if ((TSFlags >> 32) & X86II::VEX)
767     HasVEXPrefix = true;
768   if ((TSFlags >> 32) & X86II::VEX_4V)
769     HasVEX_4V = true;
770
771   // FIXME: We should emit the prefixes in exactly the same order as GAS does,
772   // in order to provide diffability.
773
774   if (!HasVEXPrefix)
775     EmitOpcodePrefix(TSFlags, CurByte, MI, Desc, OS);
776   else
777     EmitVEXOpcodePrefix(TSFlags, CurByte, MI, Desc, OS);
778   
779   // If this is a two-address instruction, skip one of the register operands.
780   unsigned NumOps = Desc.getNumOperands();
781   unsigned CurOp = 0;
782   if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
783     ++CurOp;
784   else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
785     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
786     --NumOps;
787   
788   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
789   unsigned SrcRegNum = 0;
790   switch (TSFlags & X86II::FormMask) {
791   case X86II::MRMInitReg:
792     assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
793   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
794     assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
795   case X86II::Pseudo: return; // Pseudo instructions encode to nothing.
796   case X86II::RawFrm:
797     EmitByte(BaseOpcode, CurByte, OS);
798     break;
799       
800   case X86II::AddRegFrm:
801     EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
802     break;
803       
804   case X86II::MRMDestReg:
805     EmitByte(BaseOpcode, CurByte, OS);
806     EmitRegModRMByte(MI.getOperand(CurOp),
807                      GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
808     CurOp += 2;
809     break;
810   
811   case X86II::MRMDestMem:
812     EmitSegmentOverridePrefix(MI.getOperand(CurOp + 4), TSFlags, CurByte, OS);
813     EmitByte(BaseOpcode, CurByte, OS);
814     EmitMemModRMByte(MI, CurOp,
815                      GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
816                      TSFlags, CurByte, OS, Fixups);
817     CurOp += X86AddrNumOperands + 1;
818     break;
819       
820   case X86II::MRMSrcReg:
821     EmitByte(BaseOpcode, CurByte, OS);
822     SrcRegNum = CurOp + 1;
823
824     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
825       SrcRegNum++;
826
827     EmitRegModRMByte(MI.getOperand(SrcRegNum),
828                      GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
829     CurOp = SrcRegNum + 1;
830     break;
831     
832   case X86II::MRMSrcMem: {
833     int AddrOperands = X86AddrNumOperands;
834     unsigned FirstMemOp = CurOp+1;
835     if (HasVEX_4V) {
836       ++AddrOperands;
837       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_VVVV).
838     }
839
840     // FIXME: Maybe lea should have its own form?  This is a horrible hack.
841     if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
842         Opcode == X86::LEA16r || Opcode == X86::LEA32r)
843       --AddrOperands; // No segment register
844     else
845       EmitSegmentOverridePrefix(MI.getOperand(FirstMemOp+4),
846                                 TSFlags, CurByte, OS);
847
848     EmitByte(BaseOpcode, CurByte, OS);
849
850     
851     EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
852                      TSFlags, CurByte, OS, Fixups);
853     CurOp += AddrOperands + 1;
854     break;
855   }
856
857   case X86II::MRM0r: case X86II::MRM1r:
858   case X86II::MRM2r: case X86II::MRM3r:
859   case X86II::MRM4r: case X86II::MRM5r:
860   case X86II::MRM6r: case X86II::MRM7r:
861     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
862       CurOp++;
863     EmitByte(BaseOpcode, CurByte, OS);
864     EmitRegModRMByte(MI.getOperand(CurOp++),
865                      (TSFlags & X86II::FormMask)-X86II::MRM0r,
866                      CurByte, OS);
867     break;
868   case X86II::MRM0m: case X86II::MRM1m:
869   case X86II::MRM2m: case X86II::MRM3m:
870   case X86II::MRM4m: case X86II::MRM5m:
871   case X86II::MRM6m: case X86II::MRM7m:
872     EmitSegmentOverridePrefix(MI.getOperand(CurOp+4), TSFlags, CurByte, OS);
873     EmitByte(BaseOpcode, CurByte, OS);
874     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
875                      TSFlags, CurByte, OS, Fixups);
876     CurOp += X86AddrNumOperands;
877     break;
878   case X86II::MRM_C1:
879     EmitByte(BaseOpcode, CurByte, OS);
880     EmitByte(0xC1, CurByte, OS);
881     break;
882   case X86II::MRM_C2:
883     EmitByte(BaseOpcode, CurByte, OS);
884     EmitByte(0xC2, CurByte, OS);
885     break;
886   case X86II::MRM_C3:
887     EmitByte(BaseOpcode, CurByte, OS);
888     EmitByte(0xC3, CurByte, OS);
889     break;
890   case X86II::MRM_C4:
891     EmitByte(BaseOpcode, CurByte, OS);
892     EmitByte(0xC4, CurByte, OS);
893     break;
894   case X86II::MRM_C8:
895     EmitByte(BaseOpcode, CurByte, OS);
896     EmitByte(0xC8, CurByte, OS);
897     break;
898   case X86II::MRM_C9:
899     EmitByte(BaseOpcode, CurByte, OS);
900     EmitByte(0xC9, CurByte, OS);
901     break;
902   case X86II::MRM_E8:
903     EmitByte(BaseOpcode, CurByte, OS);
904     EmitByte(0xE8, CurByte, OS);
905     break;
906   case X86II::MRM_F0:
907     EmitByte(BaseOpcode, CurByte, OS);
908     EmitByte(0xF0, CurByte, OS);
909     break;
910   case X86II::MRM_F8:
911     EmitByte(BaseOpcode, CurByte, OS);
912     EmitByte(0xF8, CurByte, OS);
913     break;
914   case X86II::MRM_F9:
915     EmitByte(BaseOpcode, CurByte, OS);
916     EmitByte(0xF9, CurByte, OS);
917     break;
918   }
919   
920   // If there is a remaining operand, it must be a trailing immediate.  Emit it
921   // according to the right size for the instruction.
922   if (CurOp != NumOps) {
923     // The last source register of a 4 operand instruction in AVX is encoded
924     // in bits[7:4] of a immediate byte, and bits[3:0] are ignored.
925     if ((TSFlags >> 32) & X86II::VEX_I8IMM) {
926       const MCOperand &MO = MI.getOperand(CurOp++);
927       bool IsExtReg =
928         X86InstrInfo::isX86_64ExtendedReg(MO.getReg());
929       unsigned RegNum = (IsExtReg ? (1 << 7) : 0);
930       RegNum |= GetX86RegNum(MO) << 4;
931       EmitImmediate(MCOperand::CreateImm(RegNum), 1, FK_Data_1, CurByte, OS,
932                     Fixups);
933     } else
934       EmitImmediate(MI.getOperand(CurOp++),
935                     X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
936                     CurByte, OS, Fixups);
937   }
938
939
940 #ifndef NDEBUG
941   // FIXME: Verify.
942   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
943     errs() << "Cannot encode all operands of: ";
944     MI.dump();
945     errs() << '\n';
946     abort();
947   }
948 #endif
949 }