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