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