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