1 //===-- X86MCCodeEmitter.cpp - Convert X86 code to machine code -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the X86MCCodeEmitter class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MCTargetDesc/X86BaseInfo.h"
14 #include "MCTargetDesc/X86FixupKinds.h"
15 #include "MCTargetDesc/X86MCTargetDesc.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixup.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstrDesc.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <cassert>
31 #include <cstdint>
32 #include <cstdlib>
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "mccodeemitter"
37 
38 namespace {
39 
40 class X86MCCodeEmitter : public MCCodeEmitter {
41   const MCInstrInfo &MCII;
42   MCContext &Ctx;
43 
44 public:
45   X86MCCodeEmitter(const MCInstrInfo &mcii, MCContext &ctx)
46       : MCII(mcii), Ctx(ctx) {}
47   X86MCCodeEmitter(const X86MCCodeEmitter &) = delete;
48   X86MCCodeEmitter &operator=(const X86MCCodeEmitter &) = delete;
49   ~X86MCCodeEmitter() override = default;
50 
51   void emitPrefix(const MCInst &MI, raw_ostream &OS,
52                   const MCSubtargetInfo &STI) const override;
53 
54   void encodeInstruction(const MCInst &MI, raw_ostream &OS,
55                          SmallVectorImpl<MCFixup> &Fixups,
56                          const MCSubtargetInfo &STI) const override;
57 
58 private:
59   unsigned getX86RegNum(const MCOperand &MO) const;
60 
61   unsigned getX86RegEncoding(const MCInst &MI, unsigned OpNum) const;
62 
63   /// \param MI a single low-level machine instruction.
64   /// \param OpNum the operand #.
65   /// \returns true if the OpNumth operand of MI  require a bit to be set in
66   /// REX prefix.
67   bool isREXExtendedReg(const MCInst &MI, unsigned OpNum) const;
68 
69   void emitImmediate(const MCOperand &Disp, SMLoc Loc, unsigned ImmSize,
70                      MCFixupKind FixupKind, uint64_t StartByte, raw_ostream &OS,
71                      SmallVectorImpl<MCFixup> &Fixups, int ImmOffset = 0) const;
72 
73   void emitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
74                         raw_ostream &OS) const;
75 
76   void emitSIBByte(unsigned SS, unsigned Index, unsigned Base,
77                    raw_ostream &OS) const;
78 
79   void emitMemModRMByte(const MCInst &MI, unsigned Op, unsigned RegOpcodeField,
80                         uint64_t TSFlags, bool HasREX, uint64_t StartByte,
81                         raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
82                         const MCSubtargetInfo &STI,
83                         bool ForceSIB = false) const;
84 
85   bool emitPrefixImpl(unsigned &CurOp, const MCInst &MI,
86                       const MCSubtargetInfo &STI, raw_ostream &OS) const;
87 
88   void emitVEXOpcodePrefix(int MemOperand, const MCInst &MI,
89                            raw_ostream &OS) const;
90 
91   void emitSegmentOverridePrefix(unsigned SegOperand, const MCInst &MI,
92                                  raw_ostream &OS) const;
93 
94   bool emitOpcodePrefix(int MemOperand, const MCInst &MI,
95                         const MCSubtargetInfo &STI, raw_ostream &OS) const;
96 
97   bool emitREXPrefix(int MemOperand, const MCInst &MI,
98                      const MCSubtargetInfo &STI, raw_ostream &OS) const;
99 };
100 
101 } // end anonymous namespace
102 
103 static uint8_t modRMByte(unsigned Mod, unsigned RegOpcode, unsigned RM) {
104   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
105   return RM | (RegOpcode << 3) | (Mod << 6);
106 }
107 
108 static void emitByte(uint8_t C, raw_ostream &OS) { OS << static_cast<char>(C); }
109 
110 static void emitConstant(uint64_t Val, unsigned Size, raw_ostream &OS) {
111   // Output the constant in little endian byte order.
112   for (unsigned i = 0; i != Size; ++i) {
113     emitByte(Val & 255, OS);
114     Val >>= 8;
115   }
116 }
117 
118 /// Determine if this immediate can fit in a disp8 or a compressed disp8 for
119 /// EVEX instructions. \p will be set to the value to pass to the ImmOffset
120 /// parameter of emitImmediate.
121 static bool isDispOrCDisp8(uint64_t TSFlags, int Value, int &ImmOffset) {
122   bool HasEVEX = (TSFlags & X86II::EncodingMask) == X86II::EVEX;
123 
124   int CD8_Scale =
125       (TSFlags & X86II::CD8_Scale_Mask) >> X86II::CD8_Scale_Shift;
126   if (!HasEVEX || CD8_Scale == 0)
127     return isInt<8>(Value);
128 
129   assert(isPowerOf2_32(CD8_Scale) && "Unexpected CD8 scale!");
130   if (Value & (CD8_Scale - 1)) // Unaligned offset
131     return false;
132 
133   int CDisp8 = Value / CD8_Scale;
134   if (!isInt<8>(CDisp8))
135     return false;
136 
137   // ImmOffset will be added to Value in emitImmediate leaving just CDisp8.
138   ImmOffset = CDisp8 - Value;
139   return true;
140 }
141 
142 /// \returns the appropriate fixup kind to use for an immediate in an
143 /// instruction with the specified TSFlags.
144 static MCFixupKind getImmFixupKind(uint64_t TSFlags) {
145   unsigned Size = X86II::getSizeOfImm(TSFlags);
146   bool isPCRel = X86II::isImmPCRel(TSFlags);
147 
148   if (X86II::isImmSigned(TSFlags)) {
149     switch (Size) {
150     default:
151       llvm_unreachable("Unsupported signed fixup size!");
152     case 4:
153       return MCFixupKind(X86::reloc_signed_4byte);
154     }
155   }
156   return MCFixup::getKindForSize(Size, isPCRel);
157 }
158 
159 /// \param Op operand # of the memory operand.
160 ///
161 /// \returns true if the specified instruction has a 16-bit memory operand.
162 static bool is16BitMemOperand(const MCInst &MI, unsigned Op,
163                               const MCSubtargetInfo &STI) {
164   const MCOperand &Base = MI.getOperand(Op + X86::AddrBaseReg);
165   const MCOperand &Index = MI.getOperand(Op + X86::AddrIndexReg);
166 
167   unsigned BaseReg = Base.getReg();
168   unsigned IndexReg = Index.getReg();
169 
170   if (STI.hasFeature(X86::Mode16Bit) && BaseReg == 0 && IndexReg == 0)
171     return true;
172   if ((BaseReg != 0 &&
173        X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) ||
174       (IndexReg != 0 &&
175        X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)))
176     return true;
177   return false;
178 }
179 
180 /// \param Op operand # of the memory operand.
181 ///
182 /// \returns true if the specified instruction has a 32-bit memory operand.
183 static bool is32BitMemOperand(const MCInst &MI, unsigned Op) {
184   const MCOperand &BaseReg = MI.getOperand(Op + X86::AddrBaseReg);
185   const MCOperand &IndexReg = MI.getOperand(Op + X86::AddrIndexReg);
186 
187   if ((BaseReg.getReg() != 0 &&
188        X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
189       (IndexReg.getReg() != 0 &&
190        X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
191     return true;
192   if (BaseReg.getReg() == X86::EIP) {
193     assert(IndexReg.getReg() == 0 && "Invalid eip-based address.");
194     return true;
195   }
196   if (IndexReg.getReg() == X86::EIZ)
197     return true;
198   return false;
199 }
200 
201 /// \param Op operand # of the memory operand.
202 ///
203 /// \returns true if the specified instruction has a 64-bit memory operand.
204 #ifndef NDEBUG
205 static bool is64BitMemOperand(const MCInst &MI, unsigned Op) {
206   const MCOperand &BaseReg = MI.getOperand(Op + X86::AddrBaseReg);
207   const MCOperand &IndexReg = MI.getOperand(Op + X86::AddrIndexReg);
208 
209   if ((BaseReg.getReg() != 0 &&
210        X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg())) ||
211       (IndexReg.getReg() != 0 &&
212        X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg())))
213     return true;
214   return false;
215 }
216 #endif
217 
218 enum GlobalOffsetTableExprKind { GOT_None, GOT_Normal, GOT_SymDiff };
219 
220 /// Check if this expression starts with  _GLOBAL_OFFSET_TABLE_ and if it is
221 /// of the form _GLOBAL_OFFSET_TABLE_-symbol. This is needed to support PIC on
222 /// ELF i386 as _GLOBAL_OFFSET_TABLE_ is magical. We check only simple case that
223 /// are know to be used: _GLOBAL_OFFSET_TABLE_ by itself or at the start of a
224 /// binary expression.
225 static GlobalOffsetTableExprKind
226 startsWithGlobalOffsetTable(const MCExpr *Expr) {
227   const MCExpr *RHS = nullptr;
228   if (Expr->getKind() == MCExpr::Binary) {
229     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Expr);
230     Expr = BE->getLHS();
231     RHS = BE->getRHS();
232   }
233 
234   if (Expr->getKind() != MCExpr::SymbolRef)
235     return GOT_None;
236 
237   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
238   const MCSymbol &S = Ref->getSymbol();
239   if (S.getName() != "_GLOBAL_OFFSET_TABLE_")
240     return GOT_None;
241   if (RHS && RHS->getKind() == MCExpr::SymbolRef)
242     return GOT_SymDiff;
243   return GOT_Normal;
244 }
245 
246 static bool hasSecRelSymbolRef(const MCExpr *Expr) {
247   if (Expr->getKind() == MCExpr::SymbolRef) {
248     const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
249     return Ref->getKind() == MCSymbolRefExpr::VK_SECREL;
250   }
251   return false;
252 }
253 
254 static bool isPCRel32Branch(const MCInst &MI, const MCInstrInfo &MCII) {
255   unsigned Opcode = MI.getOpcode();
256   const MCInstrDesc &Desc = MCII.get(Opcode);
257   if ((Opcode != X86::CALL64pcrel32 && Opcode != X86::JMP_4 &&
258        Opcode != X86::JCC_4) ||
259       getImmFixupKind(Desc.TSFlags) != FK_PCRel_4)
260     return false;
261 
262   unsigned CurOp = X86II::getOperandBias(Desc);
263   const MCOperand &Op = MI.getOperand(CurOp);
264   if (!Op.isExpr())
265     return false;
266 
267   const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Op.getExpr());
268   return Ref && Ref->getKind() == MCSymbolRefExpr::VK_None;
269 }
270 
271 unsigned X86MCCodeEmitter::getX86RegNum(const MCOperand &MO) const {
272   return Ctx.getRegisterInfo()->getEncodingValue(MO.getReg()) & 0x7;
273 }
274 
275 unsigned X86MCCodeEmitter::getX86RegEncoding(const MCInst &MI,
276                                              unsigned OpNum) const {
277   return Ctx.getRegisterInfo()->getEncodingValue(MI.getOperand(OpNum).getReg());
278 }
279 
280 /// \param MI a single low-level machine instruction.
281 /// \param OpNum the operand #.
282 /// \returns true if the OpNumth operand of MI  require a bit to be set in
283 /// REX prefix.
284 bool X86MCCodeEmitter::isREXExtendedReg(const MCInst &MI,
285                                         unsigned OpNum) const {
286   return (getX86RegEncoding(MI, OpNum) >> 3) & 1;
287 }
288 
289 void X86MCCodeEmitter::emitImmediate(const MCOperand &DispOp, SMLoc Loc,
290                                      unsigned Size, MCFixupKind FixupKind,
291                                      uint64_t StartByte, raw_ostream &OS,
292                                      SmallVectorImpl<MCFixup> &Fixups,
293                                      int ImmOffset) const {
294   const MCExpr *Expr = nullptr;
295   if (DispOp.isImm()) {
296     // If this is a simple integer displacement that doesn't require a
297     // relocation, emit it now.
298     if (FixupKind != FK_PCRel_1 && FixupKind != FK_PCRel_2 &&
299         FixupKind != FK_PCRel_4) {
300       emitConstant(DispOp.getImm() + ImmOffset, Size, OS);
301       return;
302     }
303     Expr = MCConstantExpr::create(DispOp.getImm(), Ctx);
304   } else {
305     Expr = DispOp.getExpr();
306   }
307 
308   // If we have an immoffset, add it to the expression.
309   if ((FixupKind == FK_Data_4 || FixupKind == FK_Data_8 ||
310        FixupKind == MCFixupKind(X86::reloc_signed_4byte))) {
311     GlobalOffsetTableExprKind Kind = startsWithGlobalOffsetTable(Expr);
312     if (Kind != GOT_None) {
313       assert(ImmOffset == 0);
314 
315       if (Size == 8) {
316         FixupKind = MCFixupKind(X86::reloc_global_offset_table8);
317       } else {
318         assert(Size == 4);
319         FixupKind = MCFixupKind(X86::reloc_global_offset_table);
320       }
321 
322       if (Kind == GOT_Normal)
323         ImmOffset = static_cast<int>(OS.tell() - StartByte);
324     } else if (Expr->getKind() == MCExpr::SymbolRef) {
325       if (hasSecRelSymbolRef(Expr)) {
326         FixupKind = MCFixupKind(FK_SecRel_4);
327       }
328     } else if (Expr->getKind() == MCExpr::Binary) {
329       const MCBinaryExpr *Bin = static_cast<const MCBinaryExpr *>(Expr);
330       if (hasSecRelSymbolRef(Bin->getLHS()) ||
331           hasSecRelSymbolRef(Bin->getRHS())) {
332         FixupKind = MCFixupKind(FK_SecRel_4);
333       }
334     }
335   }
336 
337   // If the fixup is pc-relative, we need to bias the value to be relative to
338   // the start of the field, not the end of the field.
339   if (FixupKind == FK_PCRel_4 ||
340       FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
341       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load) ||
342       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_relax) ||
343       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_relax_rex) ||
344       FixupKind == MCFixupKind(X86::reloc_branch_4byte_pcrel)) {
345     ImmOffset -= 4;
346     // If this is a pc-relative load off _GLOBAL_OFFSET_TABLE_:
347     // leaq _GLOBAL_OFFSET_TABLE_(%rip), %r15
348     // this needs to be a GOTPC32 relocation.
349     if (startsWithGlobalOffsetTable(Expr) != GOT_None)
350       FixupKind = MCFixupKind(X86::reloc_global_offset_table);
351   }
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(static_cast<uint32_t>(OS.tell() - StartByte),
363                                    Expr, FixupKind, Loc));
364   emitConstant(0, Size, OS);
365 }
366 
367 void X86MCCodeEmitter::emitRegModRMByte(const MCOperand &ModRMReg,
368                                         unsigned RegOpcodeFld,
369                                         raw_ostream &OS) const {
370   emitByte(modRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)), OS);
371 }
372 
373 void X86MCCodeEmitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base,
374                                    raw_ostream &OS) const {
375   // SIB byte is in the same format as the modRMByte.
376   emitByte(modRMByte(SS, Index, Base), OS);
377 }
378 
379 void X86MCCodeEmitter::emitMemModRMByte(const MCInst &MI, unsigned Op,
380                                         unsigned RegOpcodeField,
381                                         uint64_t TSFlags, bool HasREX,
382                                         uint64_t StartByte, raw_ostream &OS,
383                                         SmallVectorImpl<MCFixup> &Fixups,
384                                         const MCSubtargetInfo &STI,
385                                         bool ForceSIB) const {
386   const MCOperand &Disp = MI.getOperand(Op + X86::AddrDisp);
387   const MCOperand &Base = MI.getOperand(Op + X86::AddrBaseReg);
388   const MCOperand &Scale = MI.getOperand(Op + X86::AddrScaleAmt);
389   const MCOperand &IndexReg = MI.getOperand(Op + X86::AddrIndexReg);
390   unsigned BaseReg = Base.getReg();
391 
392   // Handle %rip relative addressing.
393   if (BaseReg == X86::RIP ||
394       BaseReg == X86::EIP) { // [disp32+rIP] in X86-64 mode
395     assert(STI.hasFeature(X86::Mode64Bit) &&
396            "Rip-relative addressing requires 64-bit mode");
397     assert(IndexReg.getReg() == 0 && !ForceSIB &&
398            "Invalid rip-relative address");
399     emitByte(modRMByte(0, RegOpcodeField, 5), OS);
400 
401     unsigned Opcode = MI.getOpcode();
402     unsigned FixupKind = [&]() {
403       // Enable relaxed relocation only for a MCSymbolRefExpr.  We cannot use a
404       // relaxed relocation if an offset is present (e.g. x@GOTPCREL+4).
405       if (!(Disp.isExpr() && isa<MCSymbolRefExpr>(Disp.getExpr())))
406         return X86::reloc_riprel_4byte;
407 
408       // Certain loads for GOT references can be relocated against the symbol
409       // directly if the symbol ends up in the same linkage unit.
410       switch (Opcode) {
411       default:
412         return X86::reloc_riprel_4byte;
413       case X86::MOV64rm:
414         // movq loads is a subset of reloc_riprel_4byte_relax_rex. It is a
415         // special case because COFF and Mach-O don't support ELF's more
416         // flexible R_X86_64_REX_GOTPCRELX relaxation.
417         assert(HasREX);
418         return X86::reloc_riprel_4byte_movq_load;
419       case X86::ADC32rm:
420       case X86::ADD32rm:
421       case X86::AND32rm:
422       case X86::CMP32rm:
423       case X86::MOV32rm:
424       case X86::OR32rm:
425       case X86::SBB32rm:
426       case X86::SUB32rm:
427       case X86::TEST32mr:
428       case X86::XOR32rm:
429       case X86::CALL64m:
430       case X86::JMP64m:
431       case X86::TAILJMPm64:
432       case X86::TEST64mr:
433       case X86::ADC64rm:
434       case X86::ADD64rm:
435       case X86::AND64rm:
436       case X86::CMP64rm:
437       case X86::OR64rm:
438       case X86::SBB64rm:
439       case X86::SUB64rm:
440       case X86::XOR64rm:
441         return HasREX ? X86::reloc_riprel_4byte_relax_rex
442                       : X86::reloc_riprel_4byte_relax;
443       }
444     }();
445 
446     // rip-relative addressing is actually relative to the *next* instruction.
447     // Since an immediate can follow the mod/rm byte for an instruction, this
448     // means that we need to bias the displacement field of the instruction with
449     // the size of the immediate field. If we have this case, add it into the
450     // expression to emit.
451     // Note: rip-relative addressing using immediate displacement values should
452     // not be adjusted, assuming it was the user's intent.
453     int ImmSize = !Disp.isImm() && X86II::hasImm(TSFlags)
454                       ? X86II::getSizeOfImm(TSFlags)
455                       : 0;
456 
457     emitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(FixupKind), StartByte, OS,
458                   Fixups, -ImmSize);
459     return;
460   }
461 
462   unsigned BaseRegNo = BaseReg ? getX86RegNum(Base) : -1U;
463 
464   // 16-bit addressing forms of the ModR/M byte have a different encoding for
465   // the R/M field and are far more limited in which registers can be used.
466   if (is16BitMemOperand(MI, Op, STI)) {
467     if (BaseReg) {
468       // For 32-bit addressing, the row and column values in Table 2-2 are
469       // basically the same. It's AX/CX/DX/BX/SP/BP/SI/DI in that order, with
470       // some special cases. And getX86RegNum reflects that numbering.
471       // For 16-bit addressing it's more fun, as shown in the SDM Vol 2A,
472       // Table 2-1 "16-Bit Addressing Forms with the ModR/M byte". We can only
473       // use SI/DI/BP/BX, which have "row" values 4-7 in no particular order,
474       // while values 0-3 indicate the allowed combinations (base+index) of
475       // those: 0 for BX+SI, 1 for BX+DI, 2 for BP+SI, 3 for BP+DI.
476       //
477       // R16Table[] is a lookup from the normal RegNo, to the row values from
478       // Table 2-1 for 16-bit addressing modes. Where zero means disallowed.
479       static const unsigned R16Table[] = {0, 0, 0, 7, 0, 6, 4, 5};
480       unsigned RMfield = R16Table[BaseRegNo];
481 
482       assert(RMfield && "invalid 16-bit base register");
483 
484       if (IndexReg.getReg()) {
485         unsigned IndexReg16 = R16Table[getX86RegNum(IndexReg)];
486 
487         assert(IndexReg16 && "invalid 16-bit index register");
488         // We must have one of SI/DI (4,5), and one of BP/BX (6,7).
489         assert(((IndexReg16 ^ RMfield) & 2) &&
490                "invalid 16-bit base/index register combination");
491         assert(Scale.getImm() == 1 &&
492                "invalid scale for 16-bit memory reference");
493 
494         // Allow base/index to appear in either order (although GAS doesn't).
495         if (IndexReg16 & 2)
496           RMfield = (RMfield & 1) | ((7 - IndexReg16) << 1);
497         else
498           RMfield = (IndexReg16 & 1) | ((7 - RMfield) << 1);
499       }
500 
501       if (Disp.isImm() && isInt<8>(Disp.getImm())) {
502         if (Disp.getImm() == 0 && RMfield != 6) {
503           // There is no displacement; just the register.
504           emitByte(modRMByte(0, RegOpcodeField, RMfield), OS);
505           return;
506         }
507         // Use the [REG]+disp8 form, including for [BP] which cannot be encoded.
508         emitByte(modRMByte(1, RegOpcodeField, RMfield), OS);
509         emitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, StartByte, OS, Fixups);
510         return;
511       }
512       // This is the [REG]+disp16 case.
513       emitByte(modRMByte(2, RegOpcodeField, RMfield), OS);
514     } else {
515       assert(IndexReg.getReg() == 0 && "Unexpected index register!");
516       // There is no BaseReg; this is the plain [disp16] case.
517       emitByte(modRMByte(0, RegOpcodeField, 6), OS);
518     }
519 
520     // Emit 16-bit displacement for plain disp16 or [REG]+disp16 cases.
521     emitImmediate(Disp, MI.getLoc(), 2, FK_Data_2, StartByte, OS, Fixups);
522     return;
523   }
524 
525   // Check for presence of {disp8} or {disp32} pseudo prefixes.
526   bool UseDisp8 = MI.getFlags() & X86::IP_USE_DISP8;
527   bool UseDisp32 = MI.getFlags() & X86::IP_USE_DISP32;
528 
529   // We only allow no displacement if no pseudo prefix is present.
530   bool AllowNoDisp = !UseDisp8 && !UseDisp32;
531   // Disp8 is allowed unless the {disp32} prefix is present.
532   bool AllowDisp8 = !UseDisp32;
533 
534   // Determine whether a SIB byte is needed.
535   if (// The SIB byte must be used if there is an index register or the
536       // encoding requires a SIB byte.
537       !ForceSIB && IndexReg.getReg() == 0 &&
538       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
539       // encode to an R/M value of 4, which indicates that a SIB byte is
540       // present.
541       BaseRegNo != N86::ESP &&
542       // If there is no base register and we're in 64-bit mode, we need a SIB
543       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
544       (!STI.hasFeature(X86::Mode64Bit) || BaseReg != 0)) {
545 
546     if (BaseReg == 0) { // [disp32]     in X86-32 mode
547       emitByte(modRMByte(0, RegOpcodeField, 5), OS);
548       emitImmediate(Disp, MI.getLoc(), 4, FK_Data_4, StartByte, OS, Fixups);
549       return;
550     }
551 
552     // If the base is not EBP/ESP/R12/R13 and there is no displacement, use
553     // simple indirect register encoding, this handles addresses like [EAX].
554     // The encoding for [EBP] or[R13] with no displacement means [disp32] so we
555     // handle it by emitting a displacement of 0 later.
556     if (BaseRegNo != N86::EBP) {
557       if (Disp.isImm() && Disp.getImm() == 0 && AllowNoDisp) {
558         emitByte(modRMByte(0, RegOpcodeField, BaseRegNo), OS);
559         return;
560       }
561 
562       // If the displacement is @tlscall, treat it as a zero.
563       if (Disp.isExpr()) {
564         auto *Sym = dyn_cast<MCSymbolRefExpr>(Disp.getExpr());
565         if (Sym && Sym->getKind() == MCSymbolRefExpr::VK_TLSCALL) {
566           // This is exclusively used by call *a@tlscall(base). The relocation
567           // (R_386_TLSCALL or R_X86_64_TLSCALL) applies to the beginning.
568           Fixups.push_back(MCFixup::create(0, Sym, FK_NONE, MI.getLoc()));
569           emitByte(modRMByte(0, RegOpcodeField, BaseRegNo), OS);
570           return;
571         }
572       }
573     }
574 
575     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
576     // Including a compressed disp8 for EVEX instructions that support it.
577     // This also handles the 0 displacement for [EBP] or [R13]. We can't use
578     // disp8 if the {disp32} pseudo prefix is present.
579     if (Disp.isImm() && AllowDisp8) {
580       int ImmOffset = 0;
581       if (isDispOrCDisp8(TSFlags, Disp.getImm(), ImmOffset)) {
582         emitByte(modRMByte(1, RegOpcodeField, BaseRegNo), OS);
583         emitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, StartByte, OS, Fixups,
584                       ImmOffset);
585         return;
586       }
587     }
588 
589     // Otherwise, emit the most general non-SIB encoding: [REG+disp32].
590     // Displacement may be 0 for [EBP] or [R13] case if {disp32} pseudo prefix
591     // prevented using disp8 above.
592     emitByte(modRMByte(2, RegOpcodeField, BaseRegNo), OS);
593     unsigned Opcode = MI.getOpcode();
594     unsigned FixupKind = Opcode == X86::MOV32rm ? X86::reloc_signed_4byte_relax
595                                                 : X86::reloc_signed_4byte;
596     emitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(FixupKind), StartByte, OS,
597                   Fixups);
598     return;
599   }
600 
601   // We need a SIB byte, so start by outputting the ModR/M byte first
602   assert(IndexReg.getReg() != X86::ESP && IndexReg.getReg() != X86::RSP &&
603          "Cannot use ESP as index reg!");
604 
605   bool ForceDisp32 = false;
606   bool ForceDisp8 = false;
607   int ImmOffset = 0;
608   if (BaseReg == 0) {
609     // If there is no base register, we emit the special case SIB byte with
610     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
611     BaseRegNo = 5;
612     emitByte(modRMByte(0, RegOpcodeField, 4), OS);
613     ForceDisp32 = true;
614   } else if (Disp.isImm() && Disp.getImm() == 0 && AllowNoDisp &&
615              // Base reg can't be EBP/RBP/R13 as that would end up with '5' as
616              // the base field, but that is the magic [*] nomenclature that
617              // indicates no base when mod=0. For these cases we'll emit a 0
618              // displacement instead.
619              BaseRegNo != N86::EBP) {
620     // Emit no displacement ModR/M byte
621     emitByte(modRMByte(0, RegOpcodeField, 4), OS);
622   } else if (Disp.isImm() && AllowDisp8 &&
623              isDispOrCDisp8(TSFlags, Disp.getImm(), ImmOffset)) {
624     // Displacement fits in a byte or matches an EVEX compressed disp8, use
625     // disp8 encoding. This also handles EBP/R13 base with 0 displacement unless
626     // {disp32} pseudo prefix was used.
627     emitByte(modRMByte(1, RegOpcodeField, 4), OS);
628     ForceDisp8 = true;
629   } else {
630     // Otherwise, emit the normal disp32 encoding.
631     emitByte(modRMByte(2, RegOpcodeField, 4), OS);
632     ForceDisp32 = true;
633   }
634 
635   // Calculate what the SS field value should be...
636   static const unsigned SSTable[] = {~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3};
637   unsigned SS = SSTable[Scale.getImm()];
638 
639   unsigned IndexRegNo = IndexReg.getReg() ? getX86RegNum(IndexReg) : 4;
640 
641   emitSIBByte(SS, IndexRegNo, BaseRegNo, OS);
642 
643   // Do we need to output a displacement?
644   if (ForceDisp8)
645     emitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, StartByte, OS, Fixups,
646                   ImmOffset);
647   else if (ForceDisp32)
648     emitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byte),
649                   StartByte, OS, Fixups);
650 }
651 
652 /// Emit all instruction prefixes.
653 ///
654 /// \returns true if REX prefix is used, otherwise returns false.
655 bool X86MCCodeEmitter::emitPrefixImpl(unsigned &CurOp, const MCInst &MI,
656                                       const MCSubtargetInfo &STI,
657                                       raw_ostream &OS) const {
658   uint64_t TSFlags = MCII.get(MI.getOpcode()).TSFlags;
659   // Determine where the memory operand starts, if present.
660   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
661   // Emit segment override opcode prefix as needed.
662   if (MemoryOperand != -1) {
663     MemoryOperand += CurOp;
664     emitSegmentOverridePrefix(MemoryOperand + X86::AddrSegmentReg, MI, OS);
665   }
666 
667   // Emit the repeat opcode prefix as needed.
668   unsigned Flags = MI.getFlags();
669   if (TSFlags & X86II::REP || Flags & X86::IP_HAS_REPEAT)
670     emitByte(0xF3, OS);
671   if (Flags & X86::IP_HAS_REPEAT_NE)
672     emitByte(0xF2, OS);
673 
674   // Emit the address size opcode prefix as needed.
675   bool NeedAddressOverride;
676   uint64_t AdSize = TSFlags & X86II::AdSizeMask;
677   if ((STI.hasFeature(X86::Mode16Bit) && AdSize == X86II::AdSize32) ||
678       (STI.hasFeature(X86::Mode32Bit) && AdSize == X86II::AdSize16) ||
679       (STI.hasFeature(X86::Mode64Bit) && AdSize == X86II::AdSize32)) {
680     NeedAddressOverride = true;
681   } else if (MemoryOperand < 0) {
682     NeedAddressOverride = false;
683   } else if (STI.hasFeature(X86::Mode64Bit)) {
684     assert(!is16BitMemOperand(MI, MemoryOperand, STI));
685     NeedAddressOverride = is32BitMemOperand(MI, MemoryOperand);
686   } else if (STI.hasFeature(X86::Mode32Bit)) {
687     assert(!is64BitMemOperand(MI, MemoryOperand));
688     NeedAddressOverride = is16BitMemOperand(MI, MemoryOperand, STI);
689   } else {
690     assert(STI.hasFeature(X86::Mode16Bit));
691     assert(!is64BitMemOperand(MI, MemoryOperand));
692     NeedAddressOverride = !is16BitMemOperand(MI, MemoryOperand, STI);
693   }
694 
695   if (NeedAddressOverride)
696     emitByte(0x67, OS);
697 
698   // Encoding type for this instruction.
699   uint64_t Encoding = TSFlags & X86II::EncodingMask;
700   bool HasREX = false;
701   if (Encoding)
702     emitVEXOpcodePrefix(MemoryOperand, MI, OS);
703   else
704     HasREX = emitOpcodePrefix(MemoryOperand, MI, STI, OS);
705 
706   uint64_t Form = TSFlags & X86II::FormMask;
707   switch (Form) {
708   default:
709     break;
710   case X86II::RawFrmDstSrc: {
711     unsigned siReg = MI.getOperand(1).getReg();
712     assert(((siReg == X86::SI && MI.getOperand(0).getReg() == X86::DI) ||
713             (siReg == X86::ESI && MI.getOperand(0).getReg() == X86::EDI) ||
714             (siReg == X86::RSI && MI.getOperand(0).getReg() == X86::RDI)) &&
715            "SI and DI register sizes do not match");
716     // Emit segment override opcode prefix as needed (not for %ds).
717     if (MI.getOperand(2).getReg() != X86::DS)
718       emitSegmentOverridePrefix(2, MI, OS);
719     // Emit AdSize prefix as needed.
720     if ((!STI.hasFeature(X86::Mode32Bit) && siReg == X86::ESI) ||
721         (STI.hasFeature(X86::Mode32Bit) && siReg == X86::SI))
722       emitByte(0x67, OS);
723     CurOp += 3; // Consume operands.
724     break;
725   }
726   case X86II::RawFrmSrc: {
727     unsigned siReg = MI.getOperand(0).getReg();
728     // Emit segment override opcode prefix as needed (not for %ds).
729     if (MI.getOperand(1).getReg() != X86::DS)
730       emitSegmentOverridePrefix(1, MI, OS);
731     // Emit AdSize prefix as needed.
732     if ((!STI.hasFeature(X86::Mode32Bit) && siReg == X86::ESI) ||
733         (STI.hasFeature(X86::Mode32Bit) && siReg == X86::SI))
734       emitByte(0x67, OS);
735     CurOp += 2; // Consume operands.
736     break;
737   }
738   case X86II::RawFrmDst: {
739     unsigned siReg = MI.getOperand(0).getReg();
740     // Emit AdSize prefix as needed.
741     if ((!STI.hasFeature(X86::Mode32Bit) && siReg == X86::EDI) ||
742         (STI.hasFeature(X86::Mode32Bit) && siReg == X86::DI))
743       emitByte(0x67, OS);
744     ++CurOp; // Consume operand.
745     break;
746   }
747   case X86II::RawFrmMemOffs: {
748     // Emit segment override opcode prefix as needed.
749     emitSegmentOverridePrefix(1, MI, OS);
750     break;
751   }
752   }
753 
754   return HasREX;
755 }
756 
757 /// AVX instructions are encoded using a opcode prefix called VEX.
758 void X86MCCodeEmitter::emitVEXOpcodePrefix(int MemOperand, const MCInst &MI,
759                                            raw_ostream &OS) const {
760   const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
761   uint64_t TSFlags = Desc.TSFlags;
762 
763   assert(!(TSFlags & X86II::LOCK) && "Can't have LOCK VEX.");
764 
765   uint64_t Encoding = TSFlags & X86II::EncodingMask;
766   bool HasEVEX_K = TSFlags & X86II::EVEX_K;
767   bool HasVEX_4V = TSFlags & X86II::VEX_4V;
768   bool HasEVEX_RC = TSFlags & X86II::EVEX_RC;
769 
770   // VEX_R: opcode externsion equivalent to REX.R in
771   // 1's complement (inverted) form
772   //
773   //  1: Same as REX_R=0 (must be 1 in 32-bit mode)
774   //  0: Same as REX_R=1 (64 bit mode only)
775   //
776   uint8_t VEX_R = 0x1;
777   uint8_t EVEX_R2 = 0x1;
778 
779   // VEX_X: equivalent to REX.X, only used when a
780   // register is used for index in SIB Byte.
781   //
782   //  1: Same as REX.X=0 (must be 1 in 32-bit mode)
783   //  0: Same as REX.X=1 (64-bit mode only)
784   uint8_t VEX_X = 0x1;
785 
786   // VEX_B:
787   //
788   //  1: Same as REX_B=0 (ignored in 32-bit mode)
789   //  0: Same as REX_B=1 (64 bit mode only)
790   //
791   uint8_t VEX_B = 0x1;
792 
793   // VEX_W: opcode specific (use like REX.W, or used for
794   // opcode extension, or ignored, depending on the opcode byte)
795   uint8_t VEX_W = (TSFlags & X86II::VEX_W) ? 1 : 0;
796 
797   // VEX_5M (VEX m-mmmmm field):
798   //
799   //  0b00000: Reserved for future use
800   //  0b00001: implied 0F leading opcode
801   //  0b00010: implied 0F 38 leading opcode bytes
802   //  0b00011: implied 0F 3A leading opcode bytes
803   //  0b00100: Reserved for future use
804   //  0b00101: VEX MAP5
805   //  0b00110: VEX MAP6
806   //  0b00111-0b11111: Reserved for future use
807   //  0b01000: XOP map select - 08h instructions with imm byte
808   //  0b01001: XOP map select - 09h instructions with no imm byte
809   //  0b01010: XOP map select - 0Ah instructions with imm dword
810   uint8_t VEX_5M;
811   switch (TSFlags & X86II::OpMapMask) {
812   default:
813     llvm_unreachable("Invalid prefix!");
814   case X86II::TB:
815     VEX_5M = 0x1;
816     break; // 0F
817   case X86II::T8:
818     VEX_5M = 0x2;
819     break; // 0F 38
820   case X86II::TA:
821     VEX_5M = 0x3;
822     break; // 0F 3A
823   case X86II::XOP8:
824     VEX_5M = 0x8;
825     break;
826   case X86II::XOP9:
827     VEX_5M = 0x9;
828     break;
829   case X86II::XOPA:
830     VEX_5M = 0xA;
831     break;
832   case X86II::T_MAP5:
833     VEX_5M = 0x5;
834     break;
835   case X86II::T_MAP6:
836     VEX_5M = 0x6;
837     break;
838   }
839 
840   // VEX_4V (VEX vvvv field): a register specifier
841   // (in 1's complement form) or 1111 if unused.
842   uint8_t VEX_4V = 0xf;
843   uint8_t EVEX_V2 = 0x1;
844 
845   // EVEX_L2/VEX_L (Vector Length):
846   //
847   // L2 L
848   //  0 0: scalar or 128-bit vector
849   //  0 1: 256-bit vector
850   //  1 0: 512-bit vector
851   //
852   uint8_t VEX_L = (TSFlags & X86II::VEX_L) ? 1 : 0;
853   uint8_t EVEX_L2 = (TSFlags & X86II::EVEX_L2) ? 1 : 0;
854 
855   // VEX_PP: opcode extension providing equivalent
856   // functionality of a SIMD prefix
857   //
858   //  0b00: None
859   //  0b01: 66
860   //  0b10: F3
861   //  0b11: F2
862   //
863   uint8_t VEX_PP = 0;
864   switch (TSFlags & X86II::OpPrefixMask) {
865   case X86II::PD:
866     VEX_PP = 0x1;
867     break; // 66
868   case X86II::XS:
869     VEX_PP = 0x2;
870     break; // F3
871   case X86II::XD:
872     VEX_PP = 0x3;
873     break; // F2
874   }
875 
876   // EVEX_U
877   uint8_t EVEX_U = 1; // Always '1' so far
878 
879   // EVEX_z
880   uint8_t EVEX_z = (HasEVEX_K && (TSFlags & X86II::EVEX_Z)) ? 1 : 0;
881 
882   // EVEX_b
883   uint8_t EVEX_b = (TSFlags & X86II::EVEX_B) ? 1 : 0;
884 
885   // EVEX_rc
886   uint8_t EVEX_rc = 0;
887 
888   // EVEX_aaa
889   uint8_t EVEX_aaa = 0;
890 
891   bool EncodeRC = false;
892 
893   // Classify VEX_B, VEX_4V, VEX_R, VEX_X
894   unsigned NumOps = Desc.getNumOperands();
895   unsigned CurOp = X86II::getOperandBias(Desc);
896 
897   switch (TSFlags & X86II::FormMask) {
898   default:
899     llvm_unreachable("Unexpected form in emitVEXOpcodePrefix!");
900   case X86II::MRM_C0:
901   case X86II::RawFrm:
902   case X86II::PrefixByte:
903     break;
904   case X86II::MRMDestMemFSIB:
905   case X86II::MRMDestMem: {
906     // MRMDestMem instructions forms:
907     //  MemAddr, src1(ModR/M)
908     //  MemAddr, src1(VEX_4V), src2(ModR/M)
909     //  MemAddr, src1(ModR/M), imm8
910     //
911     unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
912     VEX_B = ~(BaseRegEnc >> 3) & 1;
913     unsigned IndexRegEnc =
914         getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
915     VEX_X = ~(IndexRegEnc >> 3) & 1;
916     if (!HasVEX_4V) // Only needed with VSIB which don't use VVVV.
917       EVEX_V2 = ~(IndexRegEnc >> 4) & 1;
918 
919     CurOp += X86::AddrNumOperands;
920 
921     if (HasEVEX_K)
922       EVEX_aaa = getX86RegEncoding(MI, CurOp++);
923 
924     if (HasVEX_4V) {
925       unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
926       VEX_4V = ~VRegEnc & 0xf;
927       EVEX_V2 = ~(VRegEnc >> 4) & 1;
928     }
929 
930     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
931     VEX_R = ~(RegEnc >> 3) & 1;
932     EVEX_R2 = ~(RegEnc >> 4) & 1;
933     break;
934   }
935   case X86II::MRMSrcMemFSIB:
936   case X86II::MRMSrcMem: {
937     // MRMSrcMem instructions forms:
938     //  src1(ModR/M), MemAddr
939     //  src1(ModR/M), src2(VEX_4V), MemAddr
940     //  src1(ModR/M), MemAddr, imm8
941     //  src1(ModR/M), MemAddr, src2(Imm[7:4])
942     //
943     //  FMA4:
944     //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(Imm[7:4])
945     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
946     VEX_R = ~(RegEnc >> 3) & 1;
947     EVEX_R2 = ~(RegEnc >> 4) & 1;
948 
949     if (HasEVEX_K)
950       EVEX_aaa = getX86RegEncoding(MI, CurOp++);
951 
952     if (HasVEX_4V) {
953       unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
954       VEX_4V = ~VRegEnc & 0xf;
955       EVEX_V2 = ~(VRegEnc >> 4) & 1;
956     }
957 
958     unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
959     VEX_B = ~(BaseRegEnc >> 3) & 1;
960     unsigned IndexRegEnc =
961         getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
962     VEX_X = ~(IndexRegEnc >> 3) & 1;
963     if (!HasVEX_4V) // Only needed with VSIB which don't use VVVV.
964       EVEX_V2 = ~(IndexRegEnc >> 4) & 1;
965 
966     break;
967   }
968   case X86II::MRMSrcMem4VOp3: {
969     // Instruction format for 4VOp3:
970     //   src1(ModR/M), MemAddr, src3(VEX_4V)
971     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
972     VEX_R = ~(RegEnc >> 3) & 1;
973 
974     unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
975     VEX_B = ~(BaseRegEnc >> 3) & 1;
976     unsigned IndexRegEnc =
977         getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
978     VEX_X = ~(IndexRegEnc >> 3) & 1;
979 
980     VEX_4V = ~getX86RegEncoding(MI, CurOp + X86::AddrNumOperands) & 0xf;
981     break;
982   }
983   case X86II::MRMSrcMemOp4: {
984     //  dst(ModR/M.reg), src1(VEX_4V), src2(Imm[7:4]), src3(ModR/M),
985     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
986     VEX_R = ~(RegEnc >> 3) & 1;
987 
988     unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
989     VEX_4V = ~VRegEnc & 0xf;
990 
991     unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
992     VEX_B = ~(BaseRegEnc >> 3) & 1;
993     unsigned IndexRegEnc =
994         getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
995     VEX_X = ~(IndexRegEnc >> 3) & 1;
996     break;
997   }
998   case X86II::MRM0m:
999   case X86II::MRM1m:
1000   case X86II::MRM2m:
1001   case X86II::MRM3m:
1002   case X86II::MRM4m:
1003   case X86II::MRM5m:
1004   case X86II::MRM6m:
1005   case X86II::MRM7m: {
1006     // MRM[0-9]m instructions forms:
1007     //  MemAddr
1008     //  src1(VEX_4V), MemAddr
1009     if (HasVEX_4V) {
1010       unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
1011       VEX_4V = ~VRegEnc & 0xf;
1012       EVEX_V2 = ~(VRegEnc >> 4) & 1;
1013     }
1014 
1015     if (HasEVEX_K)
1016       EVEX_aaa = getX86RegEncoding(MI, CurOp++);
1017 
1018     unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
1019     VEX_B = ~(BaseRegEnc >> 3) & 1;
1020     unsigned IndexRegEnc =
1021         getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
1022     VEX_X = ~(IndexRegEnc >> 3) & 1;
1023     if (!HasVEX_4V) // Only needed with VSIB which don't use VVVV.
1024       EVEX_V2 = ~(IndexRegEnc >> 4) & 1;
1025 
1026     break;
1027   }
1028   case X86II::MRMSrcReg: {
1029     // MRMSrcReg instructions forms:
1030     //  dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(Imm[7:4])
1031     //  dst(ModR/M), src1(ModR/M)
1032     //  dst(ModR/M), src1(ModR/M), imm8
1033     //
1034     //  FMA4:
1035     //  dst(ModR/M.reg), src1(VEX_4V), src2(Imm[7:4]), src3(ModR/M),
1036     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
1037     VEX_R = ~(RegEnc >> 3) & 1;
1038     EVEX_R2 = ~(RegEnc >> 4) & 1;
1039 
1040     if (HasEVEX_K)
1041       EVEX_aaa = getX86RegEncoding(MI, CurOp++);
1042 
1043     if (HasVEX_4V) {
1044       unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
1045       VEX_4V = ~VRegEnc & 0xf;
1046       EVEX_V2 = ~(VRegEnc >> 4) & 1;
1047     }
1048 
1049     RegEnc = getX86RegEncoding(MI, CurOp++);
1050     VEX_B = ~(RegEnc >> 3) & 1;
1051     VEX_X = ~(RegEnc >> 4) & 1;
1052 
1053     if (EVEX_b) {
1054       if (HasEVEX_RC) {
1055         unsigned RcOperand = NumOps - 1;
1056         assert(RcOperand >= CurOp);
1057         EVEX_rc = MI.getOperand(RcOperand).getImm();
1058         assert(EVEX_rc <= 3 && "Invalid rounding control!");
1059       }
1060       EncodeRC = true;
1061     }
1062     break;
1063   }
1064   case X86II::MRMSrcReg4VOp3: {
1065     // Instruction format for 4VOp3:
1066     //   src1(ModR/M), src2(ModR/M), src3(VEX_4V)
1067     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
1068     VEX_R = ~(RegEnc >> 3) & 1;
1069 
1070     RegEnc = getX86RegEncoding(MI, CurOp++);
1071     VEX_B = ~(RegEnc >> 3) & 1;
1072 
1073     VEX_4V = ~getX86RegEncoding(MI, CurOp++) & 0xf;
1074     break;
1075   }
1076   case X86II::MRMSrcRegOp4: {
1077     //  dst(ModR/M.reg), src1(VEX_4V), src2(Imm[7:4]), src3(ModR/M),
1078     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
1079     VEX_R = ~(RegEnc >> 3) & 1;
1080 
1081     unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
1082     VEX_4V = ~VRegEnc & 0xf;
1083 
1084     // Skip second register source (encoded in Imm[7:4])
1085     ++CurOp;
1086 
1087     RegEnc = getX86RegEncoding(MI, CurOp++);
1088     VEX_B = ~(RegEnc >> 3) & 1;
1089     VEX_X = ~(RegEnc >> 4) & 1;
1090     break;
1091   }
1092   case X86II::MRMDestReg: {
1093     // MRMDestReg instructions forms:
1094     //  dst(ModR/M), src(ModR/M)
1095     //  dst(ModR/M), src(ModR/M), imm8
1096     //  dst(ModR/M), src1(VEX_4V), src2(ModR/M)
1097     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
1098     VEX_B = ~(RegEnc >> 3) & 1;
1099     VEX_X = ~(RegEnc >> 4) & 1;
1100 
1101     if (HasEVEX_K)
1102       EVEX_aaa = getX86RegEncoding(MI, CurOp++);
1103 
1104     if (HasVEX_4V) {
1105       unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
1106       VEX_4V = ~VRegEnc & 0xf;
1107       EVEX_V2 = ~(VRegEnc >> 4) & 1;
1108     }
1109 
1110     RegEnc = getX86RegEncoding(MI, CurOp++);
1111     VEX_R = ~(RegEnc >> 3) & 1;
1112     EVEX_R2 = ~(RegEnc >> 4) & 1;
1113     if (EVEX_b)
1114       EncodeRC = true;
1115     break;
1116   }
1117   case X86II::MRMr0: {
1118     // MRMr0 instructions forms:
1119     //  11:rrr:000
1120     //  dst(ModR/M)
1121     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
1122     VEX_R = ~(RegEnc >> 3) & 1;
1123     EVEX_R2 = ~(RegEnc >> 4) & 1;
1124     break;
1125   }
1126   case X86II::MRM0r:
1127   case X86II::MRM1r:
1128   case X86II::MRM2r:
1129   case X86II::MRM3r:
1130   case X86II::MRM4r:
1131   case X86II::MRM5r:
1132   case X86II::MRM6r:
1133   case X86II::MRM7r: {
1134     // MRM0r-MRM7r instructions forms:
1135     //  dst(VEX_4V), src(ModR/M), imm8
1136     if (HasVEX_4V) {
1137       unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
1138       VEX_4V = ~VRegEnc & 0xf;
1139       EVEX_V2 = ~(VRegEnc >> 4) & 1;
1140     }
1141     if (HasEVEX_K)
1142       EVEX_aaa = getX86RegEncoding(MI, CurOp++);
1143 
1144     unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
1145     VEX_B = ~(RegEnc >> 3) & 1;
1146     VEX_X = ~(RegEnc >> 4) & 1;
1147     break;
1148   }
1149   }
1150 
1151   if (Encoding == X86II::VEX || Encoding == X86II::XOP) {
1152     // VEX opcode prefix can have 2 or 3 bytes
1153     //
1154     //  3 bytes:
1155     //    +-----+ +--------------+ +-------------------+
1156     //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
1157     //    +-----+ +--------------+ +-------------------+
1158     //  2 bytes:
1159     //    +-----+ +-------------------+
1160     //    | C5h | | R | vvvv | L | pp |
1161     //    +-----+ +-------------------+
1162     //
1163     //  XOP uses a similar prefix:
1164     //    +-----+ +--------------+ +-------------------+
1165     //    | 8Fh | | RXB | m-mmmm | | W | vvvv | L | pp |
1166     //    +-----+ +--------------+ +-------------------+
1167     uint8_t LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
1168 
1169     // Can we use the 2 byte VEX prefix?
1170     if (!(MI.getFlags() & X86::IP_USE_VEX3) && Encoding == X86II::VEX &&
1171         VEX_B && VEX_X && !VEX_W && (VEX_5M == 1)) {
1172       emitByte(0xC5, OS);
1173       emitByte(LastByte | (VEX_R << 7), OS);
1174       return;
1175     }
1176 
1177     // 3 byte VEX prefix
1178     emitByte(Encoding == X86II::XOP ? 0x8F : 0xC4, OS);
1179     emitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, OS);
1180     emitByte(LastByte | (VEX_W << 7), OS);
1181   } else {
1182     assert(Encoding == X86II::EVEX && "unknown encoding!");
1183     // EVEX opcode prefix can have 4 bytes
1184     //
1185     // +-----+ +--------------+ +-------------------+ +------------------------+
1186     // | 62h | | RXBR' | 0mmm | | W | vvvv | U | pp | | z | L'L | b | v' | aaa |
1187     // +-----+ +--------------+ +-------------------+ +------------------------+
1188     assert((VEX_5M & 0x7) == VEX_5M &&
1189            "More than 3 significant bits in VEX.m-mmmm fields for EVEX!");
1190 
1191     emitByte(0x62, OS);
1192     emitByte((VEX_R << 7) | (VEX_X << 6) | (VEX_B << 5) | (EVEX_R2 << 4) |
1193                  VEX_5M,
1194              OS);
1195     emitByte((VEX_W << 7) | (VEX_4V << 3) | (EVEX_U << 2) | VEX_PP, OS);
1196     if (EncodeRC)
1197       emitByte((EVEX_z << 7) | (EVEX_rc << 5) | (EVEX_b << 4) | (EVEX_V2 << 3) |
1198                    EVEX_aaa,
1199                OS);
1200     else
1201       emitByte((EVEX_z << 7) | (EVEX_L2 << 6) | (VEX_L << 5) | (EVEX_b << 4) |
1202                    (EVEX_V2 << 3) | EVEX_aaa,
1203                OS);
1204   }
1205 }
1206 
1207 /// Emit REX prefix which specifies
1208 ///   1) 64-bit instructions,
1209 ///   2) non-default operand size, and
1210 ///   3) use of X86-64 extended registers.
1211 ///
1212 /// \returns true if REX prefix is used, otherwise returns false.
1213 bool X86MCCodeEmitter::emitREXPrefix(int MemOperand, const MCInst &MI,
1214                                      const MCSubtargetInfo &STI,
1215                                      raw_ostream &OS) const {
1216   uint8_t REX = [&, MemOperand]() {
1217     uint8_t REX = 0;
1218     bool UsesHighByteReg = false;
1219 
1220     const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
1221     uint64_t TSFlags = Desc.TSFlags;
1222 
1223     if (TSFlags & X86II::REX_W)
1224       REX |= 1 << 3; // set REX.W
1225 
1226     if (MI.getNumOperands() == 0)
1227       return REX;
1228 
1229     unsigned NumOps = MI.getNumOperands();
1230     unsigned CurOp = X86II::getOperandBias(Desc);
1231 
1232     // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
1233     for (unsigned i = CurOp; i != NumOps; ++i) {
1234       const MCOperand &MO = MI.getOperand(i);
1235       if (MO.isReg()) {
1236         unsigned Reg = MO.getReg();
1237         if (Reg == X86::AH || Reg == X86::BH || Reg == X86::CH ||
1238             Reg == X86::DH)
1239           UsesHighByteReg = true;
1240         if (X86II::isX86_64NonExtLowByteReg(Reg))
1241           // FIXME: The caller of determineREXPrefix slaps this prefix onto
1242           // anything that returns non-zero.
1243           REX |= 0x40; // REX fixed encoding prefix
1244       } else if (MO.isExpr() && STI.getTargetTriple().isX32()) {
1245         // GOTTPOFF and TLSDESC relocations require a REX prefix to allow
1246         // linker optimizations: even if the instructions we see may not require
1247         // any prefix, they may be replaced by instructions that do. This is
1248         // handled as a special case here so that it also works for hand-written
1249         // assembly without the user needing to write REX, as with GNU as.
1250         const auto *Ref = dyn_cast<MCSymbolRefExpr>(MO.getExpr());
1251         if (Ref && (Ref->getKind() == MCSymbolRefExpr::VK_GOTTPOFF ||
1252                     Ref->getKind() == MCSymbolRefExpr::VK_TLSDESC)) {
1253           REX |= 0x40; // REX fixed encoding prefix
1254         }
1255       }
1256     }
1257 
1258     switch (TSFlags & X86II::FormMask) {
1259     case X86II::AddRegFrm:
1260       REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
1261       break;
1262     case X86II::MRMSrcReg:
1263     case X86II::MRMSrcRegCC:
1264       REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
1265       REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
1266       break;
1267     case X86II::MRMSrcMem:
1268     case X86II::MRMSrcMemCC:
1269       REX |= isREXExtendedReg(MI, CurOp++) << 2;                        // REX.R
1270       REX |= isREXExtendedReg(MI, MemOperand + X86::AddrBaseReg) << 0;  // REX.B
1271       REX |= isREXExtendedReg(MI, MemOperand + X86::AddrIndexReg) << 1; // REX.X
1272       CurOp += X86::AddrNumOperands;
1273       break;
1274     case X86II::MRMDestReg:
1275       REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
1276       REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
1277       break;
1278     case X86II::MRMDestMem:
1279       REX |= isREXExtendedReg(MI, MemOperand + X86::AddrBaseReg) << 0;  // REX.B
1280       REX |= isREXExtendedReg(MI, MemOperand + X86::AddrIndexReg) << 1; // REX.X
1281       CurOp += X86::AddrNumOperands;
1282       REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
1283       break;
1284     case X86II::MRMXmCC:
1285     case X86II::MRMXm:
1286     case X86II::MRM0m:
1287     case X86II::MRM1m:
1288     case X86II::MRM2m:
1289     case X86II::MRM3m:
1290     case X86II::MRM4m:
1291     case X86II::MRM5m:
1292     case X86II::MRM6m:
1293     case X86II::MRM7m:
1294       REX |= isREXExtendedReg(MI, MemOperand + X86::AddrBaseReg) << 0;  // REX.B
1295       REX |= isREXExtendedReg(MI, MemOperand + X86::AddrIndexReg) << 1; // REX.X
1296       break;
1297     case X86II::MRMXrCC:
1298     case X86II::MRMXr:
1299     case X86II::MRM0r:
1300     case X86II::MRM1r:
1301     case X86II::MRM2r:
1302     case X86II::MRM3r:
1303     case X86II::MRM4r:
1304     case X86II::MRM5r:
1305     case X86II::MRM6r:
1306     case X86II::MRM7r:
1307       REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
1308       break;
1309     case X86II::MRMr0:
1310       REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
1311       break;
1312     case X86II::MRMDestMemFSIB:
1313       llvm_unreachable("FSIB format never need REX prefix!");
1314     }
1315     if (REX && UsesHighByteReg)
1316       report_fatal_error(
1317           "Cannot encode high byte register in REX-prefixed instruction");
1318     return REX;
1319   }();
1320 
1321   if (!REX)
1322     return false;
1323 
1324   emitByte(0x40 | REX, OS);
1325   return true;
1326 }
1327 
1328 /// Emit segment override opcode prefix as needed.
1329 void X86MCCodeEmitter::emitSegmentOverridePrefix(unsigned SegOperand,
1330                                                  const MCInst &MI,
1331                                                  raw_ostream &OS) const {
1332   // Check for explicit segment override on memory operand.
1333   if (unsigned Reg = MI.getOperand(SegOperand).getReg())
1334     emitByte(X86::getSegmentOverridePrefixForReg(Reg), OS);
1335 }
1336 
1337 /// Emit all instruction prefixes prior to the opcode.
1338 ///
1339 /// \param MemOperand the operand # of the start of a memory operand if present.
1340 /// If not present, it is -1.
1341 ///
1342 /// \returns true if REX prefix is used, otherwise returns false.
1343 bool X86MCCodeEmitter::emitOpcodePrefix(int MemOperand, const MCInst &MI,
1344                                         const MCSubtargetInfo &STI,
1345                                         raw_ostream &OS) const {
1346   const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
1347   uint64_t TSFlags = Desc.TSFlags;
1348 
1349   // Emit the operand size opcode prefix as needed.
1350   if ((TSFlags & X86II::OpSizeMask) ==
1351       (STI.hasFeature(X86::Mode16Bit) ? X86II::OpSize32 : X86II::OpSize16))
1352     emitByte(0x66, OS);
1353 
1354   // Emit the LOCK opcode prefix.
1355   if (TSFlags & X86II::LOCK || MI.getFlags() & X86::IP_HAS_LOCK)
1356     emitByte(0xF0, OS);
1357 
1358   // Emit the NOTRACK opcode prefix.
1359   if (TSFlags & X86II::NOTRACK || MI.getFlags() & X86::IP_HAS_NOTRACK)
1360     emitByte(0x3E, OS);
1361 
1362   switch (TSFlags & X86II::OpPrefixMask) {
1363   case X86II::PD: // 66
1364     emitByte(0x66, OS);
1365     break;
1366   case X86II::XS: // F3
1367     emitByte(0xF3, OS);
1368     break;
1369   case X86II::XD: // F2
1370     emitByte(0xF2, OS);
1371     break;
1372   }
1373 
1374   // Handle REX prefix.
1375   assert((STI.hasFeature(X86::Mode64Bit) || !(TSFlags & X86II::REX_W)) &&
1376          "REX.W requires 64bit mode.");
1377   bool HasREX = STI.hasFeature(X86::Mode64Bit)
1378                     ? emitREXPrefix(MemOperand, MI, STI, OS)
1379                     : false;
1380 
1381   // 0x0F escape code must be emitted just before the opcode.
1382   switch (TSFlags & X86II::OpMapMask) {
1383   case X86II::TB:        // Two-byte opcode map
1384   case X86II::T8:        // 0F 38
1385   case X86II::TA:        // 0F 3A
1386   case X86II::ThreeDNow: // 0F 0F, second 0F emitted by caller.
1387     emitByte(0x0F, OS);
1388     break;
1389   }
1390 
1391   switch (TSFlags & X86II::OpMapMask) {
1392   case X86II::T8: // 0F 38
1393     emitByte(0x38, OS);
1394     break;
1395   case X86II::TA: // 0F 3A
1396     emitByte(0x3A, OS);
1397     break;
1398   }
1399 
1400   return HasREX;
1401 }
1402 
1403 void X86MCCodeEmitter::emitPrefix(const MCInst &MI, raw_ostream &OS,
1404                                   const MCSubtargetInfo &STI) const {
1405   unsigned Opcode = MI.getOpcode();
1406   const MCInstrDesc &Desc = MCII.get(Opcode);
1407   uint64_t TSFlags = Desc.TSFlags;
1408 
1409   // Pseudo instructions don't get encoded.
1410   if (X86II::isPseudo(TSFlags))
1411     return;
1412 
1413   unsigned CurOp = X86II::getOperandBias(Desc);
1414 
1415   emitPrefixImpl(CurOp, MI, STI, OS);
1416 }
1417 
1418 void X86MCCodeEmitter::encodeInstruction(const MCInst &MI, raw_ostream &OS,
1419                                          SmallVectorImpl<MCFixup> &Fixups,
1420                                          const MCSubtargetInfo &STI) const {
1421   unsigned Opcode = MI.getOpcode();
1422   const MCInstrDesc &Desc = MCII.get(Opcode);
1423   uint64_t TSFlags = Desc.TSFlags;
1424 
1425   // Pseudo instructions don't get encoded.
1426   if (X86II::isPseudo(TSFlags))
1427     return;
1428 
1429   unsigned NumOps = Desc.getNumOperands();
1430   unsigned CurOp = X86II::getOperandBias(Desc);
1431 
1432   uint64_t StartByte = OS.tell();
1433 
1434   bool HasREX = emitPrefixImpl(CurOp, MI, STI, OS);
1435 
1436   // It uses the VEX.VVVV field?
1437   bool HasVEX_4V = TSFlags & X86II::VEX_4V;
1438   bool HasVEX_I8Reg = (TSFlags & X86II::ImmMask) == X86II::Imm8Reg;
1439 
1440   // It uses the EVEX.aaa field?
1441   bool HasEVEX_K = TSFlags & X86II::EVEX_K;
1442   bool HasEVEX_RC = TSFlags & X86II::EVEX_RC;
1443 
1444   // Used if a register is encoded in 7:4 of immediate.
1445   unsigned I8RegNum = 0;
1446 
1447   uint8_t BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
1448 
1449   if ((TSFlags & X86II::OpMapMask) == X86II::ThreeDNow)
1450     BaseOpcode = 0x0F; // Weird 3DNow! encoding.
1451 
1452   unsigned OpcodeOffset = 0;
1453 
1454   uint64_t Form = TSFlags & X86II::FormMask;
1455   switch (Form) {
1456   default:
1457     errs() << "FORM: " << Form << "\n";
1458     llvm_unreachable("Unknown FormMask value in X86MCCodeEmitter!");
1459   case X86II::Pseudo:
1460     llvm_unreachable("Pseudo instruction shouldn't be emitted");
1461   case X86II::RawFrmDstSrc:
1462   case X86II::RawFrmSrc:
1463   case X86II::RawFrmDst:
1464   case X86II::PrefixByte:
1465     emitByte(BaseOpcode, OS);
1466     break;
1467   case X86II::AddCCFrm: {
1468     // This will be added to the opcode in the fallthrough.
1469     OpcodeOffset = MI.getOperand(NumOps - 1).getImm();
1470     assert(OpcodeOffset < 16 && "Unexpected opcode offset!");
1471     --NumOps; // Drop the operand from the end.
1472     LLVM_FALLTHROUGH;
1473   case X86II::RawFrm:
1474     emitByte(BaseOpcode + OpcodeOffset, OS);
1475 
1476     if (!STI.hasFeature(X86::Mode64Bit) || !isPCRel32Branch(MI, MCII))
1477       break;
1478 
1479     const MCOperand &Op = MI.getOperand(CurOp++);
1480     emitImmediate(Op, MI.getLoc(), X86II::getSizeOfImm(TSFlags),
1481                   MCFixupKind(X86::reloc_branch_4byte_pcrel), StartByte, OS,
1482                   Fixups);
1483     break;
1484   }
1485   case X86II::RawFrmMemOffs:
1486     emitByte(BaseOpcode, OS);
1487     emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
1488                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
1489                   StartByte, OS, Fixups);
1490     ++CurOp; // skip segment operand
1491     break;
1492   case X86II::RawFrmImm8:
1493     emitByte(BaseOpcode, OS);
1494     emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
1495                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
1496                   StartByte, OS, Fixups);
1497     emitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 1, FK_Data_1, StartByte,
1498                   OS, Fixups);
1499     break;
1500   case X86II::RawFrmImm16:
1501     emitByte(BaseOpcode, OS);
1502     emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
1503                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
1504                   StartByte, OS, Fixups);
1505     emitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 2, FK_Data_2, StartByte,
1506                   OS, Fixups);
1507     break;
1508 
1509   case X86II::AddRegFrm:
1510     emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++)), OS);
1511     break;
1512 
1513   case X86II::MRMDestReg: {
1514     emitByte(BaseOpcode, OS);
1515     unsigned SrcRegNum = CurOp + 1;
1516 
1517     if (HasEVEX_K) // Skip writemask
1518       ++SrcRegNum;
1519 
1520     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1521       ++SrcRegNum;
1522 
1523     emitRegModRMByte(MI.getOperand(CurOp),
1524                      getX86RegNum(MI.getOperand(SrcRegNum)), OS);
1525     CurOp = SrcRegNum + 1;
1526     break;
1527   }
1528   case X86II::MRMDestMemFSIB:
1529   case X86II::MRMDestMem: {
1530     emitByte(BaseOpcode, OS);
1531     unsigned SrcRegNum = CurOp + X86::AddrNumOperands;
1532 
1533     if (HasEVEX_K) // Skip writemask
1534       ++SrcRegNum;
1535 
1536     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1537       ++SrcRegNum;
1538 
1539     bool ForceSIB = (Form == X86II::MRMDestMemFSIB);
1540     emitMemModRMByte(MI, CurOp, getX86RegNum(MI.getOperand(SrcRegNum)), TSFlags,
1541                      HasREX, StartByte, OS, Fixups, STI, ForceSIB);
1542     CurOp = SrcRegNum + 1;
1543     break;
1544   }
1545   case X86II::MRMSrcReg: {
1546     emitByte(BaseOpcode, OS);
1547     unsigned SrcRegNum = CurOp + 1;
1548 
1549     if (HasEVEX_K) // Skip writemask
1550       ++SrcRegNum;
1551 
1552     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1553       ++SrcRegNum;
1554 
1555     emitRegModRMByte(MI.getOperand(SrcRegNum),
1556                      getX86RegNum(MI.getOperand(CurOp)), OS);
1557     CurOp = SrcRegNum + 1;
1558     if (HasVEX_I8Reg)
1559       I8RegNum = getX86RegEncoding(MI, CurOp++);
1560     // do not count the rounding control operand
1561     if (HasEVEX_RC)
1562       --NumOps;
1563     break;
1564   }
1565   case X86II::MRMSrcReg4VOp3: {
1566     emitByte(BaseOpcode, OS);
1567     unsigned SrcRegNum = CurOp + 1;
1568 
1569     emitRegModRMByte(MI.getOperand(SrcRegNum),
1570                      getX86RegNum(MI.getOperand(CurOp)), OS);
1571     CurOp = SrcRegNum + 1;
1572     ++CurOp; // Encoded in VEX.VVVV
1573     break;
1574   }
1575   case X86II::MRMSrcRegOp4: {
1576     emitByte(BaseOpcode, OS);
1577     unsigned SrcRegNum = CurOp + 1;
1578 
1579     // Skip 1st src (which is encoded in VEX_VVVV)
1580     ++SrcRegNum;
1581 
1582     // Capture 2nd src (which is encoded in Imm[7:4])
1583     assert(HasVEX_I8Reg && "MRMSrcRegOp4 should imply VEX_I8Reg");
1584     I8RegNum = getX86RegEncoding(MI, SrcRegNum++);
1585 
1586     emitRegModRMByte(MI.getOperand(SrcRegNum),
1587                      getX86RegNum(MI.getOperand(CurOp)), OS);
1588     CurOp = SrcRegNum + 1;
1589     break;
1590   }
1591   case X86II::MRMSrcRegCC: {
1592     unsigned FirstOp = CurOp++;
1593     unsigned SecondOp = CurOp++;
1594 
1595     unsigned CC = MI.getOperand(CurOp++).getImm();
1596     emitByte(BaseOpcode + CC, OS);
1597 
1598     emitRegModRMByte(MI.getOperand(SecondOp),
1599                      getX86RegNum(MI.getOperand(FirstOp)), OS);
1600     break;
1601   }
1602   case X86II::MRMSrcMemFSIB:
1603   case X86II::MRMSrcMem: {
1604     unsigned FirstMemOp = CurOp + 1;
1605 
1606     if (HasEVEX_K) // Skip writemask
1607       ++FirstMemOp;
1608 
1609     if (HasVEX_4V)
1610       ++FirstMemOp; // Skip the register source (which is encoded in VEX_VVVV).
1611 
1612     emitByte(BaseOpcode, OS);
1613 
1614     bool ForceSIB = (Form == X86II::MRMSrcMemFSIB);
1615     emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(CurOp)),
1616                      TSFlags, HasREX, StartByte, OS, Fixups, STI, ForceSIB);
1617     CurOp = FirstMemOp + X86::AddrNumOperands;
1618     if (HasVEX_I8Reg)
1619       I8RegNum = getX86RegEncoding(MI, CurOp++);
1620     break;
1621   }
1622   case X86II::MRMSrcMem4VOp3: {
1623     unsigned FirstMemOp = CurOp + 1;
1624 
1625     emitByte(BaseOpcode, OS);
1626 
1627     emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(CurOp)),
1628                      TSFlags, HasREX, StartByte, OS, Fixups, STI);
1629     CurOp = FirstMemOp + X86::AddrNumOperands;
1630     ++CurOp; // Encoded in VEX.VVVV.
1631     break;
1632   }
1633   case X86II::MRMSrcMemOp4: {
1634     unsigned FirstMemOp = CurOp + 1;
1635 
1636     ++FirstMemOp; // Skip the register source (which is encoded in VEX_VVVV).
1637 
1638     // Capture second register source (encoded in Imm[7:4])
1639     assert(HasVEX_I8Reg && "MRMSrcRegOp4 should imply VEX_I8Reg");
1640     I8RegNum = getX86RegEncoding(MI, FirstMemOp++);
1641 
1642     emitByte(BaseOpcode, OS);
1643 
1644     emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(CurOp)),
1645                      TSFlags, HasREX, StartByte, OS, Fixups, STI);
1646     CurOp = FirstMemOp + X86::AddrNumOperands;
1647     break;
1648   }
1649   case X86II::MRMSrcMemCC: {
1650     unsigned RegOp = CurOp++;
1651     unsigned FirstMemOp = CurOp;
1652     CurOp = FirstMemOp + X86::AddrNumOperands;
1653 
1654     unsigned CC = MI.getOperand(CurOp++).getImm();
1655     emitByte(BaseOpcode + CC, OS);
1656 
1657     emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(RegOp)),
1658                      TSFlags, HasREX, StartByte, OS, Fixups, STI);
1659     break;
1660   }
1661 
1662   case X86II::MRMXrCC: {
1663     unsigned RegOp = CurOp++;
1664 
1665     unsigned CC = MI.getOperand(CurOp++).getImm();
1666     emitByte(BaseOpcode + CC, OS);
1667     emitRegModRMByte(MI.getOperand(RegOp), 0, OS);
1668     break;
1669   }
1670 
1671   case X86II::MRMXr:
1672   case X86II::MRM0r:
1673   case X86II::MRM1r:
1674   case X86II::MRM2r:
1675   case X86II::MRM3r:
1676   case X86II::MRM4r:
1677   case X86II::MRM5r:
1678   case X86II::MRM6r:
1679   case X86II::MRM7r:
1680     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1681       ++CurOp;
1682     if (HasEVEX_K) // Skip writemask
1683       ++CurOp;
1684     emitByte(BaseOpcode, OS);
1685     emitRegModRMByte(MI.getOperand(CurOp++),
1686                      (Form == X86II::MRMXr) ? 0 : Form - X86II::MRM0r, OS);
1687     break;
1688   case X86II::MRMr0:
1689     emitByte(BaseOpcode, OS);
1690     emitByte(modRMByte(3, getX86RegNum(MI.getOperand(CurOp++)),0), OS);
1691     break;
1692 
1693   case X86II::MRMXmCC: {
1694     unsigned FirstMemOp = CurOp;
1695     CurOp = FirstMemOp + X86::AddrNumOperands;
1696 
1697     unsigned CC = MI.getOperand(CurOp++).getImm();
1698     emitByte(BaseOpcode + CC, OS);
1699 
1700     emitMemModRMByte(MI, FirstMemOp, 0, TSFlags, HasREX, StartByte, OS, Fixups,
1701                      STI);
1702     break;
1703   }
1704 
1705   case X86II::MRMXm:
1706   case X86II::MRM0m:
1707   case X86II::MRM1m:
1708   case X86II::MRM2m:
1709   case X86II::MRM3m:
1710   case X86II::MRM4m:
1711   case X86II::MRM5m:
1712   case X86II::MRM6m:
1713   case X86II::MRM7m:
1714     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1715       ++CurOp;
1716     if (HasEVEX_K) // Skip writemask
1717       ++CurOp;
1718     emitByte(BaseOpcode, OS);
1719     emitMemModRMByte(MI, CurOp,
1720                      (Form == X86II::MRMXm) ? 0 : Form - X86II::MRM0m, TSFlags,
1721                      HasREX, StartByte, OS, Fixups, STI);
1722     CurOp += X86::AddrNumOperands;
1723     break;
1724 
1725   case X86II::MRM0X:
1726   case X86II::MRM1X:
1727   case X86II::MRM2X:
1728   case X86II::MRM3X:
1729   case X86II::MRM4X:
1730   case X86II::MRM5X:
1731   case X86II::MRM6X:
1732   case X86II::MRM7X:
1733     emitByte(BaseOpcode, OS);
1734     emitByte(0xC0 + ((Form - X86II::MRM0X) << 3), OS);
1735     break;
1736 
1737   case X86II::MRM_C0:
1738   case X86II::MRM_C1:
1739   case X86II::MRM_C2:
1740   case X86II::MRM_C3:
1741   case X86II::MRM_C4:
1742   case X86II::MRM_C5:
1743   case X86II::MRM_C6:
1744   case X86II::MRM_C7:
1745   case X86II::MRM_C8:
1746   case X86II::MRM_C9:
1747   case X86II::MRM_CA:
1748   case X86II::MRM_CB:
1749   case X86II::MRM_CC:
1750   case X86II::MRM_CD:
1751   case X86II::MRM_CE:
1752   case X86II::MRM_CF:
1753   case X86II::MRM_D0:
1754   case X86II::MRM_D1:
1755   case X86II::MRM_D2:
1756   case X86II::MRM_D3:
1757   case X86II::MRM_D4:
1758   case X86II::MRM_D5:
1759   case X86II::MRM_D6:
1760   case X86II::MRM_D7:
1761   case X86II::MRM_D8:
1762   case X86II::MRM_D9:
1763   case X86II::MRM_DA:
1764   case X86II::MRM_DB:
1765   case X86II::MRM_DC:
1766   case X86II::MRM_DD:
1767   case X86II::MRM_DE:
1768   case X86II::MRM_DF:
1769   case X86II::MRM_E0:
1770   case X86II::MRM_E1:
1771   case X86II::MRM_E2:
1772   case X86II::MRM_E3:
1773   case X86II::MRM_E4:
1774   case X86II::MRM_E5:
1775   case X86II::MRM_E6:
1776   case X86II::MRM_E7:
1777   case X86II::MRM_E8:
1778   case X86II::MRM_E9:
1779   case X86II::MRM_EA:
1780   case X86II::MRM_EB:
1781   case X86II::MRM_EC:
1782   case X86II::MRM_ED:
1783   case X86II::MRM_EE:
1784   case X86II::MRM_EF:
1785   case X86II::MRM_F0:
1786   case X86II::MRM_F1:
1787   case X86II::MRM_F2:
1788   case X86II::MRM_F3:
1789   case X86II::MRM_F4:
1790   case X86II::MRM_F5:
1791   case X86II::MRM_F6:
1792   case X86II::MRM_F7:
1793   case X86II::MRM_F8:
1794   case X86II::MRM_F9:
1795   case X86II::MRM_FA:
1796   case X86II::MRM_FB:
1797   case X86II::MRM_FC:
1798   case X86II::MRM_FD:
1799   case X86II::MRM_FE:
1800   case X86II::MRM_FF:
1801     emitByte(BaseOpcode, OS);
1802     emitByte(0xC0 + Form - X86II::MRM_C0, OS);
1803     break;
1804   }
1805 
1806   if (HasVEX_I8Reg) {
1807     // The last source register of a 4 operand instruction in AVX is encoded
1808     // in bits[7:4] of a immediate byte.
1809     assert(I8RegNum < 16 && "Register encoding out of range");
1810     I8RegNum <<= 4;
1811     if (CurOp != NumOps) {
1812       unsigned Val = MI.getOperand(CurOp++).getImm();
1813       assert(Val < 16 && "Immediate operand value out of range");
1814       I8RegNum |= Val;
1815     }
1816     emitImmediate(MCOperand::createImm(I8RegNum), MI.getLoc(), 1, FK_Data_1,
1817                   StartByte, OS, Fixups);
1818   } else {
1819     // If there is a remaining operand, it must be a trailing immediate. Emit it
1820     // according to the right size for the instruction. Some instructions
1821     // (SSE4a extrq and insertq) have two trailing immediates.
1822     while (CurOp != NumOps && NumOps - CurOp <= 2) {
1823       emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
1824                     X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
1825                     StartByte, OS, Fixups);
1826     }
1827   }
1828 
1829   if ((TSFlags & X86II::OpMapMask) == X86II::ThreeDNow)
1830     emitByte(X86II::getBaseOpcodeFor(TSFlags), OS);
1831 
1832   assert(OS.tell() - StartByte <= 15 &&
1833          "The size of instruction must be no longer than 15.");
1834 #ifndef NDEBUG
1835   // FIXME: Verify.
1836   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
1837     errs() << "Cannot encode all operands of: ";
1838     MI.dump();
1839     errs() << '\n';
1840     abort();
1841   }
1842 #endif
1843 }
1844 
1845 MCCodeEmitter *llvm::createX86MCCodeEmitter(const MCInstrInfo &MCII,
1846                                             MCContext &Ctx) {
1847   return new X86MCCodeEmitter(MCII, Ctx);
1848 }
1849