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