Fix ModR/M byte output for 16-bit addressing modes (PR18220)
[oota-llvm.git] / lib / Target / X86 / MCTargetDesc / X86MCCodeEmitter.cpp
1 //===-- 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/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/raw_ostream.h"
27
28 using namespace llvm;
29
30 namespace {
31 class X86MCCodeEmitter : public MCCodeEmitter {
32   X86MCCodeEmitter(const X86MCCodeEmitter &) LLVM_DELETED_FUNCTION;
33   void operator=(const X86MCCodeEmitter &) LLVM_DELETED_FUNCTION;
34   const MCInstrInfo &MCII;
35   const MCSubtargetInfo &STI;
36   MCContext &Ctx;
37 public:
38   X86MCCodeEmitter(const MCInstrInfo &mcii, const MCSubtargetInfo &sti,
39                    MCContext &ctx)
40     : MCII(mcii), STI(sti), Ctx(ctx) {
41   }
42
43   ~X86MCCodeEmitter() {}
44
45   bool is64BitMode() const {
46     // FIXME: Can tablegen auto-generate this?
47     return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
48   }
49
50   bool is32BitMode() const {
51     // FIXME: Can tablegen auto-generate this?
52     return (STI.getFeatureBits() & X86::Mode64Bit) == 0;
53   }
54
55   unsigned GetX86RegNum(const MCOperand &MO) const {
56     return Ctx.getRegisterInfo()->getEncodingValue(MO.getReg()) & 0x7;
57   }
58
59   // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
60   // 0-7 and the difference between the 2 groups is given by the REX prefix.
61   // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
62   // in 1's complement form, example:
63   //
64   //  ModRM field => XMM9 => 1
65   //  VEX.VVVV    => XMM9 => ~9
66   //
67   // See table 4-35 of Intel AVX Programming Reference for details.
68   unsigned char getVEXRegisterEncoding(const MCInst &MI,
69                                        unsigned OpNum) const {
70     unsigned SrcReg = MI.getOperand(OpNum).getReg();
71     unsigned SrcRegNum = GetX86RegNum(MI.getOperand(OpNum));
72     if (X86II::isX86_64ExtendedReg(SrcReg))
73       SrcRegNum |= 8;
74
75     // The registers represented through VEX_VVVV should
76     // be encoded in 1's complement form.
77     return (~SrcRegNum) & 0xf;
78   }
79
80   unsigned char getWriteMaskRegisterEncoding(const MCInst &MI,
81                                              unsigned OpNum) const {
82     assert(X86::K0 != MI.getOperand(OpNum).getReg() &&
83            "Invalid mask register as write-mask!");
84     unsigned MaskRegNum = GetX86RegNum(MI.getOperand(OpNum));
85     return MaskRegNum;
86   }
87
88   void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
89     OS << (char)C;
90     ++CurByte;
91   }
92
93   void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
94                     raw_ostream &OS) const {
95     // Output the constant in little endian byte order.
96     for (unsigned i = 0; i != Size; ++i) {
97       EmitByte(Val & 255, CurByte, OS);
98       Val >>= 8;
99     }
100   }
101
102   void EmitImmediate(const MCOperand &Disp, SMLoc Loc,
103                      unsigned ImmSize, MCFixupKind FixupKind,
104                      unsigned &CurByte, raw_ostream &OS,
105                      SmallVectorImpl<MCFixup> &Fixups,
106                      int ImmOffset = 0) const;
107
108   inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
109                                         unsigned RM) {
110     assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
111     return RM | (RegOpcode << 3) | (Mod << 6);
112   }
113
114   void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
115                         unsigned &CurByte, raw_ostream &OS) const {
116     EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
117   }
118
119   void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
120                    unsigned &CurByte, raw_ostream &OS) const {
121     // SIB byte is in the same format as the ModRMByte.
122     EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
123   }
124
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, int MemOperand,
135                            const MCInst &MI, const MCInstrDesc &Desc,
136                            raw_ostream &OS) const;
137
138   void EmitSegmentOverridePrefix(uint64_t TSFlags, unsigned &CurByte,
139                                  int MemOperand, const MCInst &MI,
140                                  raw_ostream &OS) const;
141
142   void EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
143                         const MCInst &MI, const MCInstrDesc &Desc,
144                         raw_ostream &OS) const;
145 };
146
147 } // end anonymous namespace
148
149
150 MCCodeEmitter *llvm::createX86MCCodeEmitter(const MCInstrInfo &MCII,
151                                             const MCRegisterInfo &MRI,
152                                             const MCSubtargetInfo &STI,
153                                             MCContext &Ctx) {
154   return new X86MCCodeEmitter(MCII, STI, Ctx);
155 }
156
157 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
158 /// sign-extended field.
159 static bool isDisp8(int Value) {
160   return Value == (signed char)Value;
161 }
162
163 /// isCDisp8 - Return true if this signed displacement fits in a 8-bit
164 /// compressed dispacement field.
165 static bool isCDisp8(uint64_t TSFlags, int Value, int& CValue) {
166   assert(((TSFlags >> X86II::VEXShift) & X86II::EVEX) &&
167          "Compressed 8-bit displacement is only valid for EVEX inst.");
168
169   unsigned CD8E = (TSFlags >> X86II::EVEX_CD8EShift) & X86II::EVEX_CD8EMask;
170   unsigned CD8V = (TSFlags >> X86II::EVEX_CD8VShift) & X86II::EVEX_CD8VMask;
171
172   if (CD8V == 0 && CD8E == 0) {
173     CValue = Value;
174     return isDisp8(Value);
175   }
176   
177   unsigned MemObjSize = 1U << CD8E;
178   if (CD8V & 4) {
179     // Fixed vector length
180     MemObjSize *= 1U << (CD8V & 0x3);
181   } else {
182     // Modified vector length
183     bool EVEX_b = (TSFlags >> X86II::VEXShift) & X86II::EVEX_B;
184     if (!EVEX_b) {
185       unsigned EVEX_LL = ((TSFlags >> X86II::VEXShift) & X86II::VEX_L) ? 1 : 0;
186       EVEX_LL += ((TSFlags >> X86II::VEXShift) & X86II::EVEX_L2) ? 2 : 0;
187       assert(EVEX_LL < 3 && "");
188
189       unsigned NumElems = (1U << (EVEX_LL + 4)) / MemObjSize;
190       NumElems /= 1U << (CD8V & 0x3);
191
192       MemObjSize *= NumElems;
193     }
194   }
195
196   unsigned MemObjMask = MemObjSize - 1;
197   assert((MemObjSize & MemObjMask) == 0 && "Invalid memory object size.");
198
199   if (Value & MemObjMask) // Unaligned offset
200     return false;
201   Value /= MemObjSize;
202   bool Ret = (Value == (signed char)Value);
203
204   if (Ret)
205     CValue = Value;
206   return Ret;
207 }
208
209 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
210 /// in an instruction with the specified TSFlags.
211 static MCFixupKind getImmFixupKind(uint64_t TSFlags) {
212   unsigned Size = X86II::getSizeOfImm(TSFlags);
213   bool isPCRel = X86II::isImmPCRel(TSFlags);
214
215   return MCFixup::getKindForSize(Size, isPCRel);
216 }
217
218 /// Is32BitMemOperand - Return true if the specified instruction has
219 /// a 32-bit memory operand. Op specifies the operand # of the memoperand.
220 static bool Is32BitMemOperand(const MCInst &MI, unsigned Op) {
221   const MCOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
222   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
223
224   if ((BaseReg.getReg() != 0 &&
225        X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
226       (IndexReg.getReg() != 0 &&
227        X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
228     return true;
229   return false;
230 }
231
232 /// Is64BitMemOperand - Return true if the specified instruction has
233 /// a 64-bit memory operand. Op specifies the operand # of the memoperand.
234 #ifndef NDEBUG
235 static bool Is64BitMemOperand(const MCInst &MI, unsigned Op) {
236   const MCOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
237   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
238
239   if ((BaseReg.getReg() != 0 &&
240        X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg())) ||
241       (IndexReg.getReg() != 0 &&
242        X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg())))
243     return true;
244   return false;
245 }
246 #endif
247
248 /// Is16BitMemOperand - Return true if the specified instruction has
249 /// a 16-bit memory operand. Op specifies the operand # of the memoperand.
250 static bool Is16BitMemOperand(const MCInst &MI, unsigned Op) {
251   const MCOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
252   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
253
254   if ((BaseReg.getReg() != 0 &&
255        X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg.getReg())) ||
256       (IndexReg.getReg() != 0 &&
257        X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg.getReg())))
258     return true;
259   return false;
260 }
261
262 /// StartsWithGlobalOffsetTable - Check if this expression starts with
263 ///  _GLOBAL_OFFSET_TABLE_ and if it is of the form
264 ///  _GLOBAL_OFFSET_TABLE_-symbol. This is needed to support PIC on ELF
265 /// i386 as _GLOBAL_OFFSET_TABLE_ is magical. We check only simple case that
266 /// are know to be used: _GLOBAL_OFFSET_TABLE_ by itself or at the start
267 /// of a binary expression.
268 enum GlobalOffsetTableExprKind {
269   GOT_None,
270   GOT_Normal,
271   GOT_SymDiff
272 };
273 static GlobalOffsetTableExprKind
274 StartsWithGlobalOffsetTable(const MCExpr *Expr) {
275   const MCExpr *RHS = 0;
276   if (Expr->getKind() == MCExpr::Binary) {
277     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Expr);
278     Expr = BE->getLHS();
279     RHS = BE->getRHS();
280   }
281
282   if (Expr->getKind() != MCExpr::SymbolRef)
283     return GOT_None;
284
285   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Expr);
286   const MCSymbol &S = Ref->getSymbol();
287   if (S.getName() != "_GLOBAL_OFFSET_TABLE_")
288     return GOT_None;
289   if (RHS && RHS->getKind() == MCExpr::SymbolRef)
290     return GOT_SymDiff;
291   return GOT_Normal;
292 }
293
294 static bool HasSecRelSymbolRef(const MCExpr *Expr) {
295   if (Expr->getKind() == MCExpr::SymbolRef) {
296     const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Expr);
297     return Ref->getKind() == MCSymbolRefExpr::VK_SECREL;
298   }
299   return false;
300 }
301
302 void X86MCCodeEmitter::
303 EmitImmediate(const MCOperand &DispOp, SMLoc Loc, unsigned Size,
304               MCFixupKind FixupKind, unsigned &CurByte, raw_ostream &OS,
305               SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
306   const MCExpr *Expr = NULL;
307   if (DispOp.isImm()) {
308     // If this is a simple integer displacement that doesn't require a
309     // relocation, emit it now.
310     if (FixupKind != FK_PCRel_1 &&
311         FixupKind != FK_PCRel_2 &&
312         FixupKind != FK_PCRel_4) {
313       EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
314       return;
315     }
316     Expr = MCConstantExpr::Create(DispOp.getImm(), Ctx);
317   } else {
318     Expr = DispOp.getExpr();
319   }
320
321   // If we have an immoffset, add it to the expression.
322   if ((FixupKind == FK_Data_4 ||
323        FixupKind == FK_Data_8 ||
324        FixupKind == MCFixupKind(X86::reloc_signed_4byte))) {
325     GlobalOffsetTableExprKind Kind = StartsWithGlobalOffsetTable(Expr);
326     if (Kind != GOT_None) {
327       assert(ImmOffset == 0);
328
329       FixupKind = MCFixupKind(X86::reloc_global_offset_table);
330       if (Kind == GOT_Normal)
331         ImmOffset = CurByte;
332     } else if (Expr->getKind() == MCExpr::SymbolRef) {
333       if (HasSecRelSymbolRef(Expr)) {
334         FixupKind = MCFixupKind(FK_SecRel_4);
335       }
336     } else if (Expr->getKind() == MCExpr::Binary) {
337       const MCBinaryExpr *Bin = static_cast<const MCBinaryExpr*>(Expr);
338       if (HasSecRelSymbolRef(Bin->getLHS())
339           || HasSecRelSymbolRef(Bin->getRHS())) {
340         FixupKind = MCFixupKind(FK_SecRel_4);
341       }
342     }
343   }
344
345   // If the fixup is pc-relative, we need to bias the value to be relative to
346   // the start of the field, not the end of the field.
347   if (FixupKind == FK_PCRel_4 ||
348       FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
349       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load))
350     ImmOffset -= 4;
351   if (FixupKind == FK_PCRel_2)
352     ImmOffset -= 2;
353   if (FixupKind == FK_PCRel_1)
354     ImmOffset -= 1;
355
356   if (ImmOffset)
357     Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(ImmOffset, Ctx),
358                                    Ctx);
359
360   // Emit a symbolic constant as a fixup and 4 zeros.
361   Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind, Loc));
362   EmitConstant(0, Size, CurByte, OS);
363 }
364
365 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
366                                         unsigned RegOpcodeField,
367                                         uint64_t TSFlags, unsigned &CurByte,
368                                         raw_ostream &OS,
369                                         SmallVectorImpl<MCFixup> &Fixups) const{
370   const MCOperand &Disp     = MI.getOperand(Op+X86::AddrDisp);
371   const MCOperand &Base     = MI.getOperand(Op+X86::AddrBaseReg);
372   const MCOperand &Scale    = MI.getOperand(Op+X86::AddrScaleAmt);
373   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
374   unsigned BaseReg = Base.getReg();
375   bool HasEVEX = (TSFlags >> X86II::VEXShift) & X86II::EVEX;
376
377   // Handle %rip relative addressing.
378   if (BaseReg == X86::RIP) {    // [disp32+RIP] in X86-64 mode
379     assert(is64BitMode() && "Rip-relative addressing requires 64-bit mode");
380     assert(IndexReg.getReg() == 0 && "Invalid rip-relative address");
381     EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
382
383     unsigned FixupKind = X86::reloc_riprel_4byte;
384
385     // movq loads are handled with a special relocation form which allows the
386     // linker to eliminate some loads for GOT references which end up in the
387     // same linkage unit.
388     if (MI.getOpcode() == X86::MOV64rm)
389       FixupKind = X86::reloc_riprel_4byte_movq_load;
390
391     // rip-relative addressing is actually relative to the *next* instruction.
392     // Since an immediate can follow the mod/rm byte for an instruction, this
393     // means that we need to bias the immediate field of the instruction with
394     // the size of the immediate field.  If we have this case, add it into the
395     // expression to emit.
396     int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
397
398     EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(FixupKind),
399                   CurByte, OS, Fixups, -ImmSize);
400     return;
401   }
402
403   unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
404
405   // 16-bit addressing forms of the ModR/M byte have a different encoding for
406   // the R/M field and are far more limited in which registers can be used.
407   if (Is16BitMemOperand(MI, Op)) {
408     if (BaseReg) {
409       // For 32-bit addressing, the row and column values in Table 2-2 are
410       // basically the same. It's AX/CX/DX/BX/SP/BP/SI/DI in that order, with
411       // some special cases. And GetX86RegNum reflects that numbering.
412       // For 16-bit addressing it's more fun, as shown in the SDM Vol 2A,
413       // Table 2-1 "16-Bit Addressing Forms with the ModR/M byte". We can only
414       // use SI/DI/BP/BX, which have "row" values 4-7 in no particular order,
415       // while values 0-3 indicate the allowed combinations (base+index) of
416       // those: 0 for BX+SI, 1 for BX+DI, 2 for BP+SI, 3 for BP+DI.
417       //
418       // R16Table[] is a lookup from the normal RegNo, to the row values from
419       // Table 2-1 for 16-bit addressing modes. Where zero means disallowed.
420       static const unsigned R16Table[] = { 0, 0, 0, 7, 0, 6, 4, 5 };
421       unsigned RMfield = R16Table[BaseRegNo];
422
423       assert(RMfield && "invalid 16-bit base register");
424
425       if (IndexReg.getReg()) {
426         unsigned IndexReg16 = R16Table[GetX86RegNum(IndexReg)];
427
428         assert(IndexReg16 && "invalid 16-bit index register");
429         // We must have one of SI/DI (4,5), and one of BP/BX (6,7).
430         assert(((IndexReg16 ^ RMfield) & 2) &&
431                "invalid 16-bit base/index register combination");
432         assert(Scale.getImm() == 1 &&
433                "invalid scale for 16-bit memory reference");
434
435         // Allow base/index to appear in either order (although GAS doesn't).
436         if (IndexReg16 & 2)
437           RMfield = (RMfield & 1) | ((7 - IndexReg16) << 1);
438         else
439           RMfield = (IndexReg16 & 1) | ((7 - RMfield) << 1);
440       }
441
442       if (Disp.isImm() && isDisp8(Disp.getImm())) {
443         if (Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
444           // There is no displacement; just the register.
445           EmitByte(ModRMByte(0, RegOpcodeField, RMfield), CurByte, OS);
446           return;
447         }
448         // Use the [REG]+disp8 form, including for [BP] which cannot be encoded.
449         EmitByte(ModRMByte(1, RegOpcodeField, RMfield), CurByte, OS);
450         EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups);
451         return;
452       }
453       // This is the [REG]+disp16 case.
454       EmitByte(ModRMByte(2, RegOpcodeField, RMfield), CurByte, OS);
455     } else {
456       // There is no BaseReg; this is the plain [disp16] case.
457       EmitByte(ModRMByte(0, RegOpcodeField, 6), CurByte, OS);
458     }
459
460     // Emit 16-bit displacement for plain disp16 or [REG]+disp16 cases.
461     EmitImmediate(Disp, MI.getLoc(), 2, FK_Data_2, CurByte, OS, Fixups);
462     return;
463   }
464
465   // Determine whether a SIB byte is needed.
466   // If no BaseReg, issue a RIP relative instruction only if the MCE can
467   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
468   // 2-7) and absolute references.
469
470   if (// The SIB byte must be used if there is an index register.
471       IndexReg.getReg() == 0 &&
472       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
473       // encode to an R/M value of 4, which indicates that a SIB byte is
474       // present.
475       BaseRegNo != N86::ESP &&
476       // If there is no base register and we're in 64-bit mode, we need a SIB
477       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
478       (!is64BitMode() || BaseReg != 0)) {
479
480     if (BaseReg == 0) {          // [disp32]     in X86-32 mode
481       EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
482       EmitImmediate(Disp, MI.getLoc(), 4, FK_Data_4, CurByte, OS, Fixups);
483       return;
484     }
485
486     // If the base is not EBP/ESP and there is no displacement, use simple
487     // indirect register encoding, this handles addresses like [EAX].  The
488     // encoding for [EBP] with no displacement means [disp32] so we handle it
489     // by emitting a displacement of 0 below.
490     if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
491       EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
492       return;
493     }
494
495     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
496     if (Disp.isImm()) {
497       if (!HasEVEX && isDisp8(Disp.getImm())) {
498         EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
499         EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups);
500         return;
501       }
502       // Try EVEX compressed 8-bit displacement first; if failed, fall back to
503       // 32-bit displacement.
504       int CDisp8 = 0;
505       if (HasEVEX && isCDisp8(TSFlags, Disp.getImm(), CDisp8)) {
506         EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
507         EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups,
508                       CDisp8 - Disp.getImm());
509         return;
510       }
511     }
512
513     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
514     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
515     EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, OS,
516                   Fixups);
517     return;
518   }
519
520   // We need a SIB byte, so start by outputting the ModR/M byte first
521   assert(IndexReg.getReg() != X86::ESP &&
522          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
523
524   bool ForceDisp32 = false;
525   bool ForceDisp8  = false;
526   int CDisp8 = 0;
527   int ImmOffset = 0;
528   if (BaseReg == 0) {
529     // If there is no base register, we emit the special case SIB byte with
530     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
531     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
532     ForceDisp32 = true;
533   } else if (!Disp.isImm()) {
534     // Emit the normal disp32 encoding.
535     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
536     ForceDisp32 = true;
537   } else if (Disp.getImm() == 0 &&
538              // Base reg can't be anything that ends up with '5' as the base
539              // reg, it is the magic [*] nomenclature that indicates no base.
540              BaseRegNo != N86::EBP) {
541     // Emit no displacement ModR/M byte
542     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
543   } else if (!HasEVEX && isDisp8(Disp.getImm())) {
544     // Emit the disp8 encoding.
545     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
546     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
547   } else if (HasEVEX && isCDisp8(TSFlags, Disp.getImm(), CDisp8)) {
548     // Emit the disp8 encoding.
549     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
550     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
551     ImmOffset = CDisp8 - Disp.getImm();
552   } else {
553     // Emit the normal disp32 encoding.
554     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
555   }
556
557   // Calculate what the SS field value should be...
558   static const unsigned SSTable[] = { ~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3 };
559   unsigned SS = SSTable[Scale.getImm()];
560
561   if (BaseReg == 0) {
562     // Handle the SIB byte for the case where there is no base, see Intel
563     // Manual 2A, table 2-7. The displacement has already been output.
564     unsigned IndexRegNo;
565     if (IndexReg.getReg())
566       IndexRegNo = GetX86RegNum(IndexReg);
567     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
568       IndexRegNo = 4;
569     EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
570   } else {
571     unsigned IndexRegNo;
572     if (IndexReg.getReg())
573       IndexRegNo = GetX86RegNum(IndexReg);
574     else
575       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
576     EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
577   }
578
579   // Do we need to output a displacement?
580   if (ForceDisp8)
581     EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups, ImmOffset);
582   else if (ForceDisp32 || Disp.getImm() != 0)
583     EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byte),
584                   CurByte, OS, Fixups);
585 }
586
587 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode prefix
588 /// called VEX.
589 void X86MCCodeEmitter::EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
590                                            int MemOperand, const MCInst &MI,
591                                            const MCInstrDesc &Desc,
592                                            raw_ostream &OS) const {
593   bool HasEVEX = (TSFlags >> X86II::VEXShift) & X86II::EVEX;
594   bool HasEVEX_K = HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_K);
595   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
596   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
597   bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
598   bool HasEVEX_RC = false;
599
600   // VEX_R: opcode externsion equivalent to REX.R in
601   // 1's complement (inverted) form
602   //
603   //  1: Same as REX_R=0 (must be 1 in 32-bit mode)
604   //  0: Same as REX_R=1 (64 bit mode only)
605   //
606   unsigned char VEX_R = 0x1;
607   unsigned char EVEX_R2 = 0x1;
608
609   // VEX_X: equivalent to REX.X, only used when a
610   // register is used for index in SIB Byte.
611   //
612   //  1: Same as REX.X=0 (must be 1 in 32-bit mode)
613   //  0: Same as REX.X=1 (64-bit mode only)
614   unsigned char VEX_X = 0x1;
615
616   // VEX_B:
617   //
618   //  1: Same as REX_B=0 (ignored in 32-bit mode)
619   //  0: Same as REX_B=1 (64 bit mode only)
620   //
621   unsigned char VEX_B = 0x1;
622
623   // VEX_W: opcode specific (use like REX.W, or used for
624   // opcode extension, or ignored, depending on the opcode byte)
625   unsigned char VEX_W = 0;
626
627   // XOP: Use XOP prefix byte 0x8f instead of VEX.
628   bool XOP = false;
629
630   // VEX_5M (VEX m-mmmmm field):
631   //
632   //  0b00000: Reserved for future use
633   //  0b00001: implied 0F leading opcode
634   //  0b00010: implied 0F 38 leading opcode bytes
635   //  0b00011: implied 0F 3A leading opcode bytes
636   //  0b00100-0b11111: Reserved for future use
637   //  0b01000: XOP map select - 08h instructions with imm byte
638   //  0b01001: XOP map select - 09h instructions with no imm byte
639   //  0b01010: XOP map select - 0Ah instructions with imm dword
640   unsigned char VEX_5M = 0x1;
641
642   // VEX_4V (VEX vvvv field): a register specifier
643   // (in 1's complement form) or 1111 if unused.
644   unsigned char VEX_4V = 0xf;
645   unsigned char EVEX_V2 = 0x1;
646
647   // VEX_L (Vector Length):
648   //
649   //  0: scalar or 128-bit vector
650   //  1: 256-bit vector
651   //
652   unsigned char VEX_L = 0;
653   unsigned char EVEX_L2 = 0;
654
655   // VEX_PP: opcode extension providing equivalent
656   // functionality of a SIMD prefix
657   //
658   //  0b00: None
659   //  0b01: 66
660   //  0b10: F3
661   //  0b11: F2
662   //
663   unsigned char VEX_PP = 0;
664
665   // EVEX_U
666   unsigned char EVEX_U = 1; // Always '1' so far
667
668   // EVEX_z
669   unsigned char EVEX_z = 0;
670
671   // EVEX_b
672   unsigned char EVEX_b = 0;
673
674   // EVEX_rc
675   unsigned char EVEX_rc = 0;
676
677   // EVEX_aaa
678   unsigned char EVEX_aaa = 0;
679
680   // Encode the operand size opcode prefix as needed.
681   if (TSFlags & X86II::OpSize)
682     VEX_PP = 0x01;
683
684   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
685     VEX_W = 1;
686
687   if ((TSFlags >> X86II::VEXShift) & X86II::XOP)
688     XOP = true;
689
690   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
691     VEX_L = 1;
692   if (HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_L2))
693     EVEX_L2 = 1;
694
695   if (HasEVEX_K && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_Z))
696     EVEX_z = 1;
697
698   if (HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_B))
699     EVEX_b = 1;
700
701   switch (TSFlags & X86II::Op0Mask) {
702   default: llvm_unreachable("Invalid prefix!");
703   case X86II::T8:  // 0F 38
704     VEX_5M = 0x2;
705     break;
706   case X86II::TA:  // 0F 3A
707     VEX_5M = 0x3;
708     break;
709   case X86II::T8XS: // F3 0F 38
710     VEX_PP = 0x2;
711     VEX_5M = 0x2;
712     break;
713   case X86II::T8XD: // F2 0F 38
714     VEX_PP = 0x3;
715     VEX_5M = 0x2;
716     break;
717   case X86II::TAXD: // F2 0F 3A
718     VEX_PP = 0x3;
719     VEX_5M = 0x3;
720     break;
721   case X86II::XS:  // F3 0F
722     VEX_PP = 0x2;
723     break;
724   case X86II::XD:  // F2 0F
725     VEX_PP = 0x3;
726     break;
727   case X86II::XOP8:
728     VEX_5M = 0x8;
729     break;
730   case X86II::XOP9:
731     VEX_5M = 0x9;
732     break;
733   case X86II::XOPA:
734     VEX_5M = 0xA;
735     break;
736   case X86II::TB: // VEX_5M/VEX_PP already correct
737     break;
738   }
739
740
741   // Classify VEX_B, VEX_4V, VEX_R, VEX_X
742   unsigned NumOps = Desc.getNumOperands();
743   unsigned RcOperand = NumOps-1;
744   unsigned CurOp = 0;
745   if (NumOps > 1 && Desc.getOperandConstraint(1, MCOI::TIED_TO) == 0)
746     ++CurOp;
747   else if (NumOps > 3 && Desc.getOperandConstraint(2, MCOI::TIED_TO) == 0 &&
748            Desc.getOperandConstraint(3, MCOI::TIED_TO) == 1)
749     // Special case for AVX-512 GATHER with 2 TIED_TO operands
750     // Skip the first 2 operands: dst, mask_wb
751     CurOp += 2;
752   else if (NumOps > 3 && Desc.getOperandConstraint(2, MCOI::TIED_TO) == 0 &&
753            Desc.getOperandConstraint(NumOps - 1, MCOI::TIED_TO) == 1)
754     // Special case for GATHER with 2 TIED_TO operands
755     // Skip the first 2 operands: dst, mask_wb
756     CurOp += 2;
757   else if (NumOps > 2 && Desc.getOperandConstraint(NumOps - 2, MCOI::TIED_TO) == 0)
758     // SCATTER
759     ++CurOp;
760
761   switch (TSFlags & X86II::FormMask) {
762   case X86II::MRMDestMem: {
763     // MRMDestMem instructions forms:
764     //  MemAddr, src1(ModR/M)
765     //  MemAddr, src1(VEX_4V), src2(ModR/M)
766     //  MemAddr, src1(ModR/M), imm8
767     //
768     if (X86II::isX86_64ExtendedReg(MI.getOperand(MemOperand + 
769                                                  X86::AddrBaseReg).getReg()))
770       VEX_B = 0x0;
771     if (X86II::isX86_64ExtendedReg(MI.getOperand(MemOperand +
772                                                  X86::AddrIndexReg).getReg()))
773       VEX_X = 0x0;
774     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(MemOperand +
775                                           X86::AddrIndexReg).getReg()))
776       EVEX_V2 = 0x0;
777
778     CurOp += X86::AddrNumOperands;
779
780     if (HasEVEX_K)
781       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
782
783     if (HasVEX_4V) {
784       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
785       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
786         EVEX_V2 = 0x0;
787       CurOp++;
788     }
789
790     const MCOperand &MO = MI.getOperand(CurOp);
791     if (MO.isReg()) {
792       if (X86II::isX86_64ExtendedReg(MO.getReg()))
793         VEX_R = 0x0;
794       if (HasEVEX && X86II::is32ExtendedReg(MO.getReg()))
795         EVEX_R2 = 0x0;
796     }
797     break;
798   }
799   case X86II::MRMSrcMem:
800     // MRMSrcMem instructions forms:
801     //  src1(ModR/M), MemAddr
802     //  src1(ModR/M), src2(VEX_4V), MemAddr
803     //  src1(ModR/M), MemAddr, imm8
804     //  src1(ModR/M), MemAddr, src2(VEX_I8IMM)
805     //
806     //  FMA4:
807     //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
808     //  dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
809     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
810       VEX_R = 0x0;
811     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
812       EVEX_R2 = 0x0;
813     CurOp++;
814
815     if (HasEVEX_K)
816       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
817
818     if (HasVEX_4V) {
819       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
820       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
821         EVEX_V2 = 0x0;
822       CurOp++;
823     }
824
825     if (X86II::isX86_64ExtendedReg(
826                MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
827       VEX_B = 0x0;
828     if (X86II::isX86_64ExtendedReg(
829                MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
830       VEX_X = 0x0;
831     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(MemOperand +
832                                           X86::AddrIndexReg).getReg()))
833       EVEX_V2 = 0x0;
834
835     if (HasVEX_4VOp3)
836       // Instruction format for 4VOp3:
837       //   src1(ModR/M), MemAddr, src3(VEX_4V)
838       // CurOp points to start of the MemoryOperand,
839       //   it skips TIED_TO operands if exist, then increments past src1.
840       // CurOp + X86::AddrNumOperands will point to src3.
841       VEX_4V = getVEXRegisterEncoding(MI, CurOp+X86::AddrNumOperands);
842     break;
843   case X86II::MRM0m: case X86II::MRM1m:
844   case X86II::MRM2m: case X86II::MRM3m:
845   case X86II::MRM4m: case X86II::MRM5m:
846   case X86II::MRM6m: case X86II::MRM7m: {
847     // MRM[0-9]m instructions forms:
848     //  MemAddr
849     //  src1(VEX_4V), MemAddr
850     if (HasVEX_4V) {
851       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
852       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
853         EVEX_V2 = 0x0;
854       CurOp++;
855     }
856
857     if (HasEVEX_K)
858       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
859
860     if (X86II::isX86_64ExtendedReg(
861                MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
862       VEX_B = 0x0;
863     if (X86II::isX86_64ExtendedReg(
864                MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
865       VEX_X = 0x0;
866     break;
867   }
868   case X86II::MRMSrcReg:
869     // MRMSrcReg instructions forms:
870     //  dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
871     //  dst(ModR/M), src1(ModR/M)
872     //  dst(ModR/M), src1(ModR/M), imm8
873     //
874     //  FMA4:
875     //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
876     //  dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
877     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
878       VEX_R = 0x0;
879     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
880       EVEX_R2 = 0x0;
881     CurOp++;
882
883     if (HasEVEX_K)
884       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
885
886     if (HasVEX_4V) {
887       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
888       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
889         EVEX_V2 = 0x0;
890       CurOp++;
891     }
892
893     if (HasMemOp4) // Skip second register source (encoded in I8IMM)
894       CurOp++;
895
896     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
897       VEX_B = 0x0;
898     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
899       VEX_X = 0x0;
900     CurOp++;
901     if (HasVEX_4VOp3)
902       VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
903     if (EVEX_b) {
904       assert(RcOperand >= CurOp);
905       EVEX_rc = MI.getOperand(RcOperand).getImm() & 0x3;
906       HasEVEX_RC = true;
907     }
908     break;
909   case X86II::MRMDestReg:
910     // MRMDestReg instructions forms:
911     //  dst(ModR/M), src(ModR/M)
912     //  dst(ModR/M), src(ModR/M), imm8
913     //  dst(ModR/M), src1(VEX_4V), src2(ModR/M)
914     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
915       VEX_B = 0x0;
916     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
917       VEX_X = 0x0;
918     CurOp++;
919
920     if (HasEVEX_K)
921       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
922
923     if (HasVEX_4V) {
924       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
925       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
926         EVEX_V2 = 0x0;
927       CurOp++;
928     }
929
930     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
931       VEX_R = 0x0;
932     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
933       EVEX_R2 = 0x0;
934     break;
935   case X86II::MRM0r: case X86II::MRM1r:
936   case X86II::MRM2r: case X86II::MRM3r:
937   case X86II::MRM4r: case X86II::MRM5r:
938   case X86II::MRM6r: case X86II::MRM7r:
939     // MRM0r-MRM7r instructions forms:
940     //  dst(VEX_4V), src(ModR/M), imm8
941     if (HasVEX_4V) {
942       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
943       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
944           EVEX_V2 = 0x0;
945       CurOp++;
946     }    
947     if (HasEVEX_K)
948       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
949
950     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
951       VEX_B = 0x0;
952     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
953       VEX_X = 0x0;
954     break;
955   default: // RawFrm
956     break;
957   }
958
959   // Emit segment override opcode prefix as needed.
960   EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
961
962   if (!HasEVEX) {
963     // VEX opcode prefix can have 2 or 3 bytes
964     //
965     //  3 bytes:
966     //    +-----+ +--------------+ +-------------------+
967     //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
968     //    +-----+ +--------------+ +-------------------+
969     //  2 bytes:
970     //    +-----+ +-------------------+
971     //    | C5h | | R | vvvv | L | pp |
972     //    +-----+ +-------------------+
973     //
974     unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
975
976     if (VEX_B && VEX_X && !VEX_W && !XOP && (VEX_5M == 1)) { // 2 byte VEX prefix
977       EmitByte(0xC5, CurByte, OS);
978       EmitByte(LastByte | (VEX_R << 7), CurByte, OS);
979       return;
980     }
981
982     // 3 byte VEX prefix
983     EmitByte(XOP ? 0x8F : 0xC4, CurByte, OS);
984     EmitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, CurByte, OS);
985     EmitByte(LastByte | (VEX_W << 7), CurByte, OS);
986   } else {
987     // EVEX opcode prefix can have 4 bytes
988     //
989     // +-----+ +--------------+ +-------------------+ +------------------------+
990     // | 62h | | RXBR' | 00mm | | W | vvvv | U | pp | | z | L'L | b | v' | aaa |
991     // +-----+ +--------------+ +-------------------+ +------------------------+
992     assert((VEX_5M & 0x3) == VEX_5M
993            && "More than 2 significant bits in VEX.m-mmmm fields for EVEX!");
994
995     VEX_5M &= 0x3;
996
997     EmitByte(0x62, CurByte, OS);
998     EmitByte((VEX_R   << 7) |
999              (VEX_X   << 6) |
1000              (VEX_B   << 5) |
1001              (EVEX_R2 << 4) |
1002              VEX_5M, CurByte, OS);
1003     EmitByte((VEX_W   << 7) |
1004              (VEX_4V  << 3) |
1005              (EVEX_U  << 2) |
1006              VEX_PP, CurByte, OS);
1007     if (HasEVEX_RC)
1008       EmitByte((EVEX_z  << 7) |
1009               (EVEX_rc << 5) |
1010               (EVEX_b  << 4) |
1011               (EVEX_V2 << 3) |
1012               EVEX_aaa, CurByte, OS);
1013     else
1014       EmitByte((EVEX_z  << 7) |
1015               (EVEX_L2 << 6) |
1016               (VEX_L   << 5) |
1017               (EVEX_b  << 4) |
1018               (EVEX_V2 << 3) |
1019               EVEX_aaa, CurByte, OS);
1020   }
1021 }
1022
1023 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
1024 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
1025 /// size, and 3) use of X86-64 extended registers.
1026 static unsigned DetermineREXPrefix(const MCInst &MI, uint64_t TSFlags,
1027                                    const MCInstrDesc &Desc) {
1028   unsigned REX = 0;
1029   if (TSFlags & X86II::REX_W)
1030     REX |= 1 << 3; // set REX.W
1031
1032   if (MI.getNumOperands() == 0) return REX;
1033
1034   unsigned NumOps = MI.getNumOperands();
1035   // FIXME: MCInst should explicitize the two-addrness.
1036   bool isTwoAddr = NumOps > 1 &&
1037                       Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1;
1038
1039   // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
1040   unsigned i = isTwoAddr ? 1 : 0;
1041   for (; i != NumOps; ++i) {
1042     const MCOperand &MO = MI.getOperand(i);
1043     if (!MO.isReg()) continue;
1044     unsigned Reg = MO.getReg();
1045     if (!X86II::isX86_64NonExtLowByteReg(Reg)) continue;
1046     // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
1047     // that returns non-zero.
1048     REX |= 0x40; // REX fixed encoding prefix
1049     break;
1050   }
1051
1052   switch (TSFlags & X86II::FormMask) {
1053   case X86II::MRMSrcReg:
1054     if (MI.getOperand(0).isReg() &&
1055         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
1056       REX |= 1 << 2; // set REX.R
1057     i = isTwoAddr ? 2 : 1;
1058     for (; i != NumOps; ++i) {
1059       const MCOperand &MO = MI.getOperand(i);
1060       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
1061         REX |= 1 << 0; // set REX.B
1062     }
1063     break;
1064   case X86II::MRMSrcMem: {
1065     if (MI.getOperand(0).isReg() &&
1066         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
1067       REX |= 1 << 2; // set REX.R
1068     unsigned Bit = 0;
1069     i = isTwoAddr ? 2 : 1;
1070     for (; i != NumOps; ++i) {
1071       const MCOperand &MO = MI.getOperand(i);
1072       if (MO.isReg()) {
1073         if (X86II::isX86_64ExtendedReg(MO.getReg()))
1074           REX |= 1 << Bit; // set REX.B (Bit=0) and REX.X (Bit=1)
1075         Bit++;
1076       }
1077     }
1078     break;
1079   }
1080   case X86II::MRM0m: case X86II::MRM1m:
1081   case X86II::MRM2m: case X86II::MRM3m:
1082   case X86II::MRM4m: case X86II::MRM5m:
1083   case X86II::MRM6m: case X86II::MRM7m:
1084   case X86II::MRMDestMem: {
1085     unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
1086     i = isTwoAddr ? 1 : 0;
1087     if (NumOps > e && MI.getOperand(e).isReg() &&
1088         X86II::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
1089       REX |= 1 << 2; // set REX.R
1090     unsigned Bit = 0;
1091     for (; i != e; ++i) {
1092       const MCOperand &MO = MI.getOperand(i);
1093       if (MO.isReg()) {
1094         if (X86II::isX86_64ExtendedReg(MO.getReg()))
1095           REX |= 1 << Bit; // REX.B (Bit=0) and REX.X (Bit=1)
1096         Bit++;
1097       }
1098     }
1099     break;
1100   }
1101   default:
1102     if (MI.getOperand(0).isReg() &&
1103         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
1104       REX |= 1 << 0; // set REX.B
1105     i = isTwoAddr ? 2 : 1;
1106     for (unsigned e = NumOps; i != e; ++i) {
1107       const MCOperand &MO = MI.getOperand(i);
1108       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
1109         REX |= 1 << 2; // set REX.R
1110     }
1111     break;
1112   }
1113   return REX;
1114 }
1115
1116 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
1117 void X86MCCodeEmitter::EmitSegmentOverridePrefix(uint64_t TSFlags,
1118                                         unsigned &CurByte, int MemOperand,
1119                                         const MCInst &MI,
1120                                         raw_ostream &OS) const {
1121   switch (TSFlags & X86II::SegOvrMask) {
1122   default: llvm_unreachable("Invalid segment!");
1123   case 0:
1124     // No segment override, check for explicit one on memory operand.
1125     if (MemOperand != -1) {   // If the instruction has a memory operand.
1126       switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
1127       default: llvm_unreachable("Unknown segment register!");
1128       case 0: break;
1129       case X86::CS: EmitByte(0x2E, CurByte, OS); break;
1130       case X86::SS: EmitByte(0x36, CurByte, OS); break;
1131       case X86::DS: EmitByte(0x3E, CurByte, OS); break;
1132       case X86::ES: EmitByte(0x26, CurByte, OS); break;
1133       case X86::FS: EmitByte(0x64, CurByte, OS); break;
1134       case X86::GS: EmitByte(0x65, CurByte, OS); break;
1135       }
1136     }
1137     break;
1138   case X86II::FS:
1139     EmitByte(0x64, CurByte, OS);
1140     break;
1141   case X86II::GS:
1142     EmitByte(0x65, CurByte, OS);
1143     break;
1144   }
1145 }
1146
1147 /// EmitOpcodePrefix - Emit all instruction prefixes prior to the opcode.
1148 ///
1149 /// MemOperand is the operand # of the start of a memory operand if present.  If
1150 /// Not present, it is -1.
1151 void X86MCCodeEmitter::EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
1152                                         int MemOperand, const MCInst &MI,
1153                                         const MCInstrDesc &Desc,
1154                                         raw_ostream &OS) const {
1155
1156   // Emit the lock opcode prefix as needed.
1157   if (TSFlags & X86II::LOCK)
1158     EmitByte(0xF0, CurByte, OS);
1159
1160   // Emit segment override opcode prefix as needed.
1161   EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
1162
1163   // Emit the repeat opcode prefix as needed.
1164   if ((TSFlags & X86II::Op0Mask) == X86II::REP)
1165     EmitByte(0xF3, CurByte, OS);
1166
1167   // Emit the address size opcode prefix as needed.
1168   bool need_address_override;
1169   if (TSFlags & X86II::AdSize) {
1170     need_address_override = true;
1171   } else if (MemOperand == -1) {
1172     need_address_override = false;
1173   } else if (is64BitMode()) {
1174     assert(!Is16BitMemOperand(MI, MemOperand));
1175     need_address_override = Is32BitMemOperand(MI, MemOperand);
1176   } else if (is32BitMode()) {
1177     assert(!Is64BitMemOperand(MI, MemOperand));
1178     need_address_override = Is16BitMemOperand(MI, MemOperand);
1179   } else {
1180     need_address_override = false;
1181   }
1182
1183   if (need_address_override)
1184     EmitByte(0x67, CurByte, OS);
1185
1186   // Emit the operand size opcode prefix as needed.
1187   if (TSFlags & X86II::OpSize)
1188     EmitByte(0x66, CurByte, OS);
1189
1190   bool Need0FPrefix = false;
1191   switch (TSFlags & X86II::Op0Mask) {
1192   default: llvm_unreachable("Invalid prefix!");
1193   case 0: break;  // No prefix!
1194   case X86II::REP: break; // already handled.
1195   case X86II::TB:  // Two-byte opcode prefix
1196   case X86II::T8:  // 0F 38
1197   case X86II::TA:  // 0F 3A
1198   case X86II::A6:  // 0F A6
1199   case X86II::A7:  // 0F A7
1200     Need0FPrefix = true;
1201     break;
1202   case X86II::XS:   // F3 0F
1203   case X86II::T8XS: // F3 0F 38
1204     EmitByte(0xF3, CurByte, OS);
1205     Need0FPrefix = true;
1206     break;
1207   case X86II::XD:   // F2 0F
1208   case X86II::T8XD: // F2 0F 38
1209   case X86II::TAXD: // F2 0F 3A
1210     EmitByte(0xF2, CurByte, OS);
1211     Need0FPrefix = true;
1212     break;
1213   case X86II::D8:
1214   case X86II::D9:
1215   case X86II::DA:
1216   case X86II::DB:
1217   case X86II::DC:
1218   case X86II::DD:
1219   case X86II::DE:
1220   case X86II::DF:
1221     EmitByte(0xD8+(((TSFlags & X86II::Op0Mask) - X86II::D8) >> X86II::Op0Shift),
1222              CurByte, OS);
1223     break;
1224   }
1225
1226   // Handle REX prefix.
1227   // FIXME: Can this come before F2 etc to simplify emission?
1228   if (is64BitMode()) {
1229     if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
1230       EmitByte(0x40 | REX, CurByte, OS);
1231   }
1232
1233   // 0x0F escape code must be emitted just before the opcode.
1234   if (Need0FPrefix)
1235     EmitByte(0x0F, CurByte, OS);
1236
1237   // FIXME: Pull this up into previous switch if REX can be moved earlier.
1238   switch (TSFlags & X86II::Op0Mask) {
1239   case X86II::T8XS:  // F3 0F 38
1240   case X86II::T8XD:  // F2 0F 38
1241   case X86II::T8:    // 0F 38
1242     EmitByte(0x38, CurByte, OS);
1243     break;
1244   case X86II::TAXD:  // F2 0F 3A
1245   case X86II::TA:    // 0F 3A
1246     EmitByte(0x3A, CurByte, OS);
1247     break;
1248   case X86II::A6:    // 0F A6
1249     EmitByte(0xA6, CurByte, OS);
1250     break;
1251   case X86II::A7:    // 0F A7
1252     EmitByte(0xA7, CurByte, OS);
1253     break;
1254   }
1255 }
1256
1257 void X86MCCodeEmitter::
1258 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
1259                   SmallVectorImpl<MCFixup> &Fixups) const {
1260   unsigned Opcode = MI.getOpcode();
1261   const MCInstrDesc &Desc = MCII.get(Opcode);
1262   uint64_t TSFlags = Desc.TSFlags;
1263
1264   // Pseudo instructions don't get encoded.
1265   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
1266     return;
1267
1268   unsigned NumOps = Desc.getNumOperands();
1269   unsigned CurOp = X86II::getOperandBias(Desc);
1270
1271   // Keep track of the current byte being emitted.
1272   unsigned CurByte = 0;
1273
1274   // Is this instruction encoded using the AVX VEX prefix?
1275   bool HasVEXPrefix = (TSFlags >> X86II::VEXShift) & X86II::VEX;
1276
1277   // It uses the VEX.VVVV field?
1278   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
1279   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
1280   bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
1281   const unsigned MemOp4_I8IMMOperand = 2;
1282
1283   // It uses the EVEX.aaa field?
1284   bool HasEVEX = (TSFlags >> X86II::VEXShift) & X86II::EVEX;
1285   bool HasEVEX_K = HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_K);
1286   bool HasEVEX_B = HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_B);
1287   
1288   // Determine where the memory operand starts, if present.
1289   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags, Opcode);
1290   if (MemoryOperand != -1) MemoryOperand += CurOp;
1291
1292   if (!HasVEXPrefix)
1293     EmitOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
1294   else
1295     EmitVEXOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
1296
1297   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
1298
1299   if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
1300     BaseOpcode = 0x0F;   // Weird 3DNow! encoding.
1301
1302   unsigned SrcRegNum = 0;
1303   switch (TSFlags & X86II::FormMask) {
1304   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
1305     llvm_unreachable("Unknown FormMask value in X86MCCodeEmitter!");
1306   case X86II::Pseudo:
1307     llvm_unreachable("Pseudo instruction shouldn't be emitted");
1308   case X86II::RawFrm:
1309     EmitByte(BaseOpcode, CurByte, OS);
1310     break;
1311   case X86II::RawFrmImm8:
1312     EmitByte(BaseOpcode, CurByte, OS);
1313     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
1314                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
1315                   CurByte, OS, Fixups);
1316     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 1, FK_Data_1, CurByte,
1317                   OS, Fixups);
1318     break;
1319   case X86II::RawFrmImm16:
1320     EmitByte(BaseOpcode, CurByte, OS);
1321     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
1322                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
1323                   CurByte, OS, Fixups);
1324     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 2, FK_Data_2, CurByte,
1325                   OS, Fixups);
1326     break;
1327
1328   case X86II::AddRegFrm:
1329     EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
1330     break;
1331
1332   case X86II::MRMDestReg:
1333     EmitByte(BaseOpcode, CurByte, OS);
1334     SrcRegNum = CurOp + 1;
1335
1336     if (HasEVEX_K) // Skip writemask
1337       SrcRegNum++;
1338
1339     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1340       ++SrcRegNum;
1341
1342     EmitRegModRMByte(MI.getOperand(CurOp),
1343                      GetX86RegNum(MI.getOperand(SrcRegNum)), CurByte, OS);
1344     CurOp = SrcRegNum + 1;
1345     break;
1346
1347   case X86II::MRMDestMem:
1348     EmitByte(BaseOpcode, CurByte, OS);
1349     SrcRegNum = CurOp + X86::AddrNumOperands;
1350
1351     if (HasEVEX_K) // Skip writemask
1352       SrcRegNum++;
1353
1354     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1355       ++SrcRegNum;
1356
1357     EmitMemModRMByte(MI, CurOp,
1358                      GetX86RegNum(MI.getOperand(SrcRegNum)),
1359                      TSFlags, CurByte, OS, Fixups);
1360     CurOp = SrcRegNum + 1;
1361     break;
1362
1363   case X86II::MRMSrcReg:
1364     EmitByte(BaseOpcode, CurByte, OS);
1365     SrcRegNum = CurOp + 1;
1366
1367     if (HasEVEX_K) // Skip writemask
1368       SrcRegNum++;
1369
1370     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1371       ++SrcRegNum;
1372
1373     if (HasMemOp4) // Skip 2nd src (which is encoded in I8IMM)
1374       ++SrcRegNum;
1375
1376     EmitRegModRMByte(MI.getOperand(SrcRegNum),
1377                      GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
1378
1379     // 2 operands skipped with HasMemOp4, compensate accordingly
1380     CurOp = HasMemOp4 ? SrcRegNum : SrcRegNum + 1;
1381     if (HasVEX_4VOp3)
1382       ++CurOp;
1383     // do not count the rounding control operand
1384     if (HasEVEX_B)
1385       NumOps--;
1386     break;
1387
1388   case X86II::MRMSrcMem: {
1389     int AddrOperands = X86::AddrNumOperands;
1390     unsigned FirstMemOp = CurOp+1;
1391
1392     if (HasEVEX_K) { // Skip writemask
1393       ++AddrOperands;
1394       ++FirstMemOp;
1395     }
1396
1397     if (HasVEX_4V) {
1398       ++AddrOperands;
1399       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_VVVV).
1400     }
1401     if (HasMemOp4) // Skip second register source (encoded in I8IMM)
1402       ++FirstMemOp;
1403
1404     EmitByte(BaseOpcode, CurByte, OS);
1405
1406     EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
1407                      TSFlags, CurByte, OS, Fixups);
1408     CurOp += AddrOperands + 1;
1409     if (HasVEX_4VOp3)
1410       ++CurOp;
1411     break;
1412   }
1413
1414   case X86II::MRM0r: case X86II::MRM1r:
1415   case X86II::MRM2r: case X86II::MRM3r:
1416   case X86II::MRM4r: case X86II::MRM5r:
1417   case X86II::MRM6r: case X86II::MRM7r:
1418     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1419       ++CurOp;
1420     EmitByte(BaseOpcode, CurByte, OS);
1421     EmitRegModRMByte(MI.getOperand(CurOp++),
1422                      (TSFlags & X86II::FormMask)-X86II::MRM0r,
1423                      CurByte, OS);
1424     break;
1425   case X86II::MRM0m: case X86II::MRM1m:
1426   case X86II::MRM2m: case X86II::MRM3m:
1427   case X86II::MRM4m: case X86II::MRM5m:
1428   case X86II::MRM6m: case X86II::MRM7m:
1429     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1430       ++CurOp;
1431     EmitByte(BaseOpcode, CurByte, OS);
1432     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
1433                      TSFlags, CurByte, OS, Fixups);
1434     CurOp += X86::AddrNumOperands;
1435     break;
1436   case X86II::MRM_C1: case X86II::MRM_C2: case X86II::MRM_C3:
1437   case X86II::MRM_C4: case X86II::MRM_C8: case X86II::MRM_C9:
1438   case X86II::MRM_CA: case X86II::MRM_CB: case X86II::MRM_D0:
1439   case X86II::MRM_D1: case X86II::MRM_D4: case X86II::MRM_D5:
1440   case X86II::MRM_D6: case X86II::MRM_D8: case X86II::MRM_D9:
1441   case X86II::MRM_DA: case X86II::MRM_DB: case X86II::MRM_DC:
1442   case X86II::MRM_DD: case X86II::MRM_DE: case X86II::MRM_DF:
1443   case X86II::MRM_E8: case X86II::MRM_F0: case X86II::MRM_F8:
1444   case X86II::MRM_F9:
1445     EmitByte(BaseOpcode, CurByte, OS);
1446
1447     unsigned char MRM;
1448     switch (TSFlags & X86II::FormMask) {
1449     default: llvm_unreachable("Invalid Form");
1450     case X86II::MRM_C1: MRM = 0xC1; break;
1451     case X86II::MRM_C2: MRM = 0xC2; break;
1452     case X86II::MRM_C3: MRM = 0xC3; break;
1453     case X86II::MRM_C4: MRM = 0xC4; break;
1454     case X86II::MRM_C8: MRM = 0xC8; break;
1455     case X86II::MRM_C9: MRM = 0xC9; break;
1456     case X86II::MRM_CA: MRM = 0xCA; break;
1457     case X86II::MRM_CB: MRM = 0xCB; break;
1458     case X86II::MRM_D0: MRM = 0xD0; break;
1459     case X86II::MRM_D1: MRM = 0xD1; break;
1460     case X86II::MRM_D4: MRM = 0xD4; break;
1461     case X86II::MRM_D5: MRM = 0xD5; break;
1462     case X86II::MRM_D6: MRM = 0xD6; break;
1463     case X86II::MRM_D8: MRM = 0xD8; break;
1464     case X86II::MRM_D9: MRM = 0xD9; break;
1465     case X86II::MRM_DA: MRM = 0xDA; break;
1466     case X86II::MRM_DB: MRM = 0xDB; break;
1467     case X86II::MRM_DC: MRM = 0xDC; break;
1468     case X86II::MRM_DD: MRM = 0xDD; break;
1469     case X86II::MRM_DE: MRM = 0xDE; break;
1470     case X86II::MRM_DF: MRM = 0xDF; break;
1471     case X86II::MRM_E8: MRM = 0xE8; break;
1472     case X86II::MRM_F0: MRM = 0xF0; break;
1473     case X86II::MRM_F8: MRM = 0xF8; break;
1474     case X86II::MRM_F9: MRM = 0xF9; break;
1475     }
1476     EmitByte(MRM, CurByte, OS);
1477     break;
1478   }
1479
1480   // If there is a remaining operand, it must be a trailing immediate.  Emit it
1481   // according to the right size for the instruction. Some instructions
1482   // (SSE4a extrq and insertq) have two trailing immediates.
1483   while (CurOp != NumOps && NumOps - CurOp <= 2) {
1484     // The last source register of a 4 operand instruction in AVX is encoded
1485     // in bits[7:4] of a immediate byte.
1486     if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM) {
1487       const MCOperand &MO = MI.getOperand(HasMemOp4 ? MemOp4_I8IMMOperand
1488                                                     : CurOp);
1489       ++CurOp;
1490       unsigned RegNum = GetX86RegNum(MO) << 4;
1491       if (X86II::isX86_64ExtendedReg(MO.getReg()))
1492         RegNum |= 1 << 7;
1493       // If there is an additional 5th operand it must be an immediate, which
1494       // is encoded in bits[3:0]
1495       if (CurOp != NumOps) {
1496         const MCOperand &MIMM = MI.getOperand(CurOp++);
1497         if (MIMM.isImm()) {
1498           unsigned Val = MIMM.getImm();
1499           assert(Val < 16 && "Immediate operand value out of range");
1500           RegNum |= Val;
1501         }
1502       }
1503       EmitImmediate(MCOperand::CreateImm(RegNum), MI.getLoc(), 1, FK_Data_1,
1504                     CurByte, OS, Fixups);
1505     } else {
1506       unsigned FixupKind;
1507       // FIXME: Is there a better way to know that we need a signed relocation?
1508       if (MI.getOpcode() == X86::ADD64ri32 ||
1509           MI.getOpcode() == X86::MOV64ri32 ||
1510           MI.getOpcode() == X86::MOV64mi32 ||
1511           MI.getOpcode() == X86::PUSH64i32)
1512         FixupKind = X86::reloc_signed_4byte;
1513       else
1514         FixupKind = getImmFixupKind(TSFlags);
1515       EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
1516                     X86II::getSizeOfImm(TSFlags), MCFixupKind(FixupKind),
1517                     CurByte, OS, Fixups);
1518     }
1519   }
1520
1521   if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
1522     EmitByte(X86II::getBaseOpcodeFor(TSFlags), CurByte, OS);
1523
1524 #ifndef NDEBUG
1525   // FIXME: Verify.
1526   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
1527     errs() << "Cannot encode all operands of: ";
1528     MI.dump();
1529     errs() << '\n';
1530     abort();
1531   }
1532 #endif
1533 }