1 //===-- X86/X86MCCodeEmitter.cpp - Convert X86 code to machine code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the X86MCCodeEmitter class.
12 //===----------------------------------------------------------------------===//
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/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Support/raw_ostream.h"
30 class X86MCCodeEmitter : public MCCodeEmitter {
31 X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
32 void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
33 const MCInstrInfo &MCII;
34 const MCSubtargetInfo &STI;
37 X86MCCodeEmitter(const MCInstrInfo &mcii, const MCSubtargetInfo &sti,
39 : MCII(mcii), STI(sti), Ctx(ctx) {
42 ~X86MCCodeEmitter() {}
44 bool is64BitMode() const {
45 // FIXME: Can tablegen auto-generate this?
46 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
49 static unsigned GetX86RegNum(const MCOperand &MO) {
50 return X86_MC::getX86RegNum(MO.getReg());
53 // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
54 // 0-7 and the difference between the 2 groups is given by the REX prefix.
55 // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
56 // in 1's complement form, example:
58 // ModRM field => XMM9 => 1
59 // VEX.VVVV => XMM9 => ~9
61 // See table 4-35 of Intel AVX Programming Reference for details.
62 static unsigned char getVEXRegisterEncoding(const MCInst &MI,
64 unsigned SrcReg = MI.getOperand(OpNum).getReg();
65 unsigned SrcRegNum = GetX86RegNum(MI.getOperand(OpNum));
66 if ((SrcReg >= X86::XMM8 && SrcReg <= X86::XMM15) ||
67 (SrcReg >= X86::YMM8 && SrcReg <= X86::YMM15))
70 // The registers represented through VEX_VVVV should
71 // be encoded in 1's complement form.
72 return (~SrcRegNum) & 0xf;
75 void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
80 void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
81 raw_ostream &OS) const {
82 // Output the constant in little endian byte order.
83 for (unsigned i = 0; i != Size; ++i) {
84 EmitByte(Val & 255, CurByte, OS);
89 void EmitImmediate(const MCOperand &Disp,
90 unsigned ImmSize, MCFixupKind FixupKind,
91 unsigned &CurByte, raw_ostream &OS,
92 SmallVectorImpl<MCFixup> &Fixups,
93 int ImmOffset = 0) const;
95 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
97 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
98 return RM | (RegOpcode << 3) | (Mod << 6);
101 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
102 unsigned &CurByte, raw_ostream &OS) const {
103 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
106 void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
107 unsigned &CurByte, raw_ostream &OS) const {
108 // SIB byte is in the same format as the ModRMByte.
109 EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
113 void EmitMemModRMByte(const MCInst &MI, unsigned Op,
114 unsigned RegOpcodeField,
115 uint64_t TSFlags, unsigned &CurByte, raw_ostream &OS,
116 SmallVectorImpl<MCFixup> &Fixups) const;
118 void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
119 SmallVectorImpl<MCFixup> &Fixups) const;
121 void EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
122 const MCInst &MI, const MCInstrDesc &Desc,
123 raw_ostream &OS) const;
125 void EmitSegmentOverridePrefix(uint64_t TSFlags, unsigned &CurByte,
126 int MemOperand, const MCInst &MI,
127 raw_ostream &OS) const;
129 void EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
130 const MCInst &MI, const MCInstrDesc &Desc,
131 raw_ostream &OS) const;
134 } // end anonymous namespace
137 MCCodeEmitter *llvm::createX86MCCodeEmitter(const MCInstrInfo &MCII,
138 const MCSubtargetInfo &STI,
140 return new X86MCCodeEmitter(MCII, STI, Ctx);
143 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
144 /// sign-extended field.
145 static bool isDisp8(int Value) {
146 return Value == (signed char)Value;
149 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
150 /// in an instruction with the specified TSFlags.
151 static MCFixupKind getImmFixupKind(uint64_t TSFlags) {
152 unsigned Size = X86II::getSizeOfImm(TSFlags);
153 bool isPCRel = X86II::isImmPCRel(TSFlags);
155 return MCFixup::getKindForSize(Size, isPCRel);
159 // FIXME: TableGen this?
160 extern MCRegisterClass X86MCRegisterClasses[]; // In X86GenRegisterInfo.inc.
163 /// Is32BitMemOperand - Return true if the specified instruction with a memory
164 /// operand should emit the 0x67 prefix byte in 64-bit mode due to a 32-bit
165 /// memory operand. Op specifies the operand # of the memoperand.
166 static 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);
170 if ((BaseReg.getReg() != 0 &&
171 X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
172 (IndexReg.getReg() != 0 &&
173 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
178 /// StartsWithGlobalOffsetTable - Return true for the simple cases where this
179 /// expression starts with _GLOBAL_OFFSET_TABLE_. This is a needed to support
180 /// PIC on ELF i386 as that symbol is magic. We check only simple case that
181 /// are know to be used: _GLOBAL_OFFSET_TABLE_ by itself or at the start
182 /// of a binary expression.
183 static bool StartsWithGlobalOffsetTable(const MCExpr *Expr) {
184 if (Expr->getKind() == MCExpr::Binary) {
185 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Expr);
189 if (Expr->getKind() != MCExpr::SymbolRef)
192 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Expr);
193 const MCSymbol &S = Ref->getSymbol();
194 return S.getName() == "_GLOBAL_OFFSET_TABLE_";
197 void X86MCCodeEmitter::
198 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
199 unsigned &CurByte, raw_ostream &OS,
200 SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
201 const MCExpr *Expr = NULL;
202 if (DispOp.isImm()) {
203 // If this is a simple integer displacement that doesn't require a relocation,
205 if (FixupKind != FK_PCRel_1 &&
206 FixupKind != FK_PCRel_2 &&
207 FixupKind != FK_PCRel_4) {
208 EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
211 Expr = MCConstantExpr::Create(DispOp.getImm(), Ctx);
213 Expr = DispOp.getExpr();
216 // If we have an immoffset, add it to the expression.
217 if ((FixupKind == FK_Data_4 ||
218 FixupKind == MCFixupKind(X86::reloc_signed_4byte)) &&
219 StartsWithGlobalOffsetTable(Expr)) {
220 assert(ImmOffset == 0);
222 FixupKind = MCFixupKind(X86::reloc_global_offset_table);
226 // If the fixup is pc-relative, we need to bias the value to be relative to
227 // the start of the field, not the end of the field.
228 if (FixupKind == FK_PCRel_4 ||
229 FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
230 FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load))
232 if (FixupKind == FK_PCRel_2)
234 if (FixupKind == FK_PCRel_1)
238 Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(ImmOffset, Ctx),
241 // Emit a symbolic constant as a fixup and 4 zeros.
242 Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
243 EmitConstant(0, Size, CurByte, OS);
246 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
247 unsigned RegOpcodeField,
248 uint64_t TSFlags, unsigned &CurByte,
250 SmallVectorImpl<MCFixup> &Fixups) const{
251 const MCOperand &Disp = MI.getOperand(Op+X86::AddrDisp);
252 const MCOperand &Base = MI.getOperand(Op+X86::AddrBaseReg);
253 const MCOperand &Scale = MI.getOperand(Op+X86::AddrScaleAmt);
254 const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
255 unsigned BaseReg = Base.getReg();
257 // Handle %rip relative addressing.
258 if (BaseReg == X86::RIP) { // [disp32+RIP] in X86-64 mode
259 assert(is64BitMode() && "Rip-relative addressing requires 64-bit mode");
260 assert(IndexReg.getReg() == 0 && "Invalid rip-relative address");
261 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
263 unsigned FixupKind = X86::reloc_riprel_4byte;
265 // movq loads are handled with a special relocation form which allows the
266 // linker to eliminate some loads for GOT references which end up in the
267 // same linkage unit.
268 if (MI.getOpcode() == X86::MOV64rm)
269 FixupKind = X86::reloc_riprel_4byte_movq_load;
271 // rip-relative addressing is actually relative to the *next* instruction.
272 // Since an immediate can follow the mod/rm byte for an instruction, this
273 // means that we need to bias the immediate field of the instruction with
274 // the size of the immediate field. If we have this case, add it into the
275 // expression to emit.
276 int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
278 EmitImmediate(Disp, 4, MCFixupKind(FixupKind),
279 CurByte, OS, Fixups, -ImmSize);
283 unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
285 // Determine whether a SIB byte is needed.
286 // If no BaseReg, issue a RIP relative instruction only if the MCE can
287 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
288 // 2-7) and absolute references.
290 if (// The SIB byte must be used if there is an index register.
291 IndexReg.getReg() == 0 &&
292 // The SIB byte must be used if the base is ESP/RSP/R12, all of which
293 // encode to an R/M value of 4, which indicates that a SIB byte is
295 BaseRegNo != N86::ESP &&
296 // If there is no base register and we're in 64-bit mode, we need a SIB
297 // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
298 (!is64BitMode() || BaseReg != 0)) {
300 if (BaseReg == 0) { // [disp32] in X86-32 mode
301 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
302 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
306 // If the base is not EBP/ESP and there is no displacement, use simple
307 // indirect register encoding, this handles addresses like [EAX]. The
308 // encoding for [EBP] with no displacement means [disp32] so we handle it
309 // by emitting a displacement of 0 below.
310 if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
311 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
315 // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
316 if (Disp.isImm() && isDisp8(Disp.getImm())) {
317 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
318 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
322 // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
323 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
324 EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, OS,
329 // We need a SIB byte, so start by outputting the ModR/M byte first
330 assert(IndexReg.getReg() != X86::ESP &&
331 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
333 bool ForceDisp32 = false;
334 bool ForceDisp8 = false;
336 // If there is no base register, we emit the special case SIB byte with
337 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
338 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
340 } else if (!Disp.isImm()) {
341 // Emit the normal disp32 encoding.
342 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
344 } else if (Disp.getImm() == 0 &&
345 // Base reg can't be anything that ends up with '5' as the base
346 // reg, it is the magic [*] nomenclature that indicates no base.
347 BaseRegNo != N86::EBP) {
348 // Emit no displacement ModR/M byte
349 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
350 } else if (isDisp8(Disp.getImm())) {
351 // Emit the disp8 encoding.
352 EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
353 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
355 // Emit the normal disp32 encoding.
356 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
359 // Calculate what the SS field value should be...
360 static const unsigned SSTable[] = { ~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3 };
361 unsigned SS = SSTable[Scale.getImm()];
364 // Handle the SIB byte for the case where there is no base, see Intel
365 // Manual 2A, table 2-7. The displacement has already been output.
367 if (IndexReg.getReg())
368 IndexRegNo = GetX86RegNum(IndexReg);
369 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
371 EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
374 if (IndexReg.getReg())
375 IndexRegNo = GetX86RegNum(IndexReg);
377 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
378 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
381 // Do we need to output a displacement?
383 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
384 else if (ForceDisp32 || Disp.getImm() != 0)
385 EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, OS,
389 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode prefix
391 void X86MCCodeEmitter::EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
392 int MemOperand, const MCInst &MI,
393 const MCInstrDesc &Desc,
394 raw_ostream &OS) const {
395 bool HasVEX_4V = false;
396 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_4V)
399 // VEX_R: opcode externsion equivalent to REX.R in
400 // 1's complement (inverted) form
402 // 1: Same as REX_R=0 (must be 1 in 32-bit mode)
403 // 0: Same as REX_R=1 (64 bit mode only)
405 unsigned char VEX_R = 0x1;
407 // VEX_X: equivalent to REX.X, only used when a
408 // register is used for index in SIB Byte.
410 // 1: Same as REX.X=0 (must be 1 in 32-bit mode)
411 // 0: Same as REX.X=1 (64-bit mode only)
412 unsigned char VEX_X = 0x1;
416 // 1: Same as REX_B=0 (ignored in 32-bit mode)
417 // 0: Same as REX_B=1 (64 bit mode only)
419 unsigned char VEX_B = 0x1;
421 // VEX_W: opcode specific (use like REX.W, or used for
422 // opcode extension, or ignored, depending on the opcode byte)
423 unsigned char VEX_W = 0;
425 // VEX_5M (VEX m-mmmmm field):
427 // 0b00000: Reserved for future use
428 // 0b00001: implied 0F leading opcode
429 // 0b00010: implied 0F 38 leading opcode bytes
430 // 0b00011: implied 0F 3A leading opcode bytes
431 // 0b00100-0b11111: Reserved for future use
433 unsigned char VEX_5M = 0x1;
435 // VEX_4V (VEX vvvv field): a register specifier
436 // (in 1's complement form) or 1111 if unused.
437 unsigned char VEX_4V = 0xf;
439 // VEX_L (Vector Length):
441 // 0: scalar or 128-bit vector
444 unsigned char VEX_L = 0;
446 // VEX_PP: opcode extension providing equivalent
447 // functionality of a SIMD prefix
454 unsigned char VEX_PP = 0;
456 // Encode the operand size opcode prefix as needed.
457 if (TSFlags & X86II::OpSize)
460 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
463 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
466 switch (TSFlags & X86II::Op0Mask) {
467 default: assert(0 && "Invalid prefix!");
468 case X86II::T8: // 0F 38
471 case X86II::TA: // 0F 3A
474 case X86II::TF: // F2 0F 38
478 case X86II::XS: // F3 0F
481 case X86II::XD: // F2 0F
484 case X86II::A6: // Bypass: Not used by VEX
485 case X86II::A7: // Bypass: Not used by VEX
486 case X86II::TB: // Bypass: Not used by VEX
491 // Set the vector length to 256-bit if YMM0-YMM15 is used
492 for (unsigned i = 0; i != MI.getNumOperands(); ++i) {
493 if (!MI.getOperand(i).isReg())
495 unsigned SrcReg = MI.getOperand(i).getReg();
496 if (SrcReg >= X86::YMM0 && SrcReg <= X86::YMM15)
500 unsigned NumOps = MI.getNumOperands();
502 bool IsDestMem = false;
504 switch (TSFlags & X86II::FormMask) {
505 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
506 case X86II::MRMDestMem:
508 // The important info for the VEX prefix is never beyond the address
509 // registers. Don't check beyond that.
510 NumOps = CurOp = X86::AddrNumOperands;
511 case X86II::MRM0m: case X86II::MRM1m:
512 case X86II::MRM2m: case X86II::MRM3m:
513 case X86II::MRM4m: case X86II::MRM5m:
514 case X86II::MRM6m: case X86II::MRM7m:
515 case X86II::MRMSrcMem:
516 case X86II::MRMSrcReg:
517 if (MI.getNumOperands() > CurOp && MI.getOperand(CurOp).isReg() &&
518 X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
523 VEX_4V = getVEXRegisterEncoding(MI, IsDestMem ? CurOp-1 : CurOp);
527 // To only check operands before the memory address ones, start
528 // the search from the beginning
532 // If the last register should be encoded in the immediate field
533 // do not use any bit from VEX prefix to this register, ignore it
534 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM)
537 for (; CurOp != NumOps; ++CurOp) {
538 const MCOperand &MO = MI.getOperand(CurOp);
539 if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
541 if (!VEX_B && MO.isReg() &&
542 ((TSFlags & X86II::FormMask) == X86II::MRMSrcMem) &&
543 X86II::isX86_64ExtendedReg(MO.getReg()))
547 default: // MRMDestReg, MRM0r-MRM7r, RawFrm
548 if (!MI.getNumOperands())
551 if (MI.getOperand(CurOp).isReg() &&
552 X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
556 VEX_4V = getVEXRegisterEncoding(MI, CurOp);
559 for (; CurOp != NumOps; ++CurOp) {
560 const MCOperand &MO = MI.getOperand(CurOp);
561 if (MO.isReg() && !HasVEX_4V &&
562 X86II::isX86_64ExtendedReg(MO.getReg()))
568 // Emit segment override opcode prefix as needed.
569 EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
571 // VEX opcode prefix can have 2 or 3 bytes
574 // +-----+ +--------------+ +-------------------+
575 // | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
576 // +-----+ +--------------+ +-------------------+
578 // +-----+ +-------------------+
579 // | C5h | | R | vvvv | L | pp |
580 // +-----+ +-------------------+
582 unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
584 if (VEX_B && VEX_X && !VEX_W && (VEX_5M == 1)) { // 2 byte VEX prefix
585 EmitByte(0xC5, CurByte, OS);
586 EmitByte(LastByte | (VEX_R << 7), CurByte, OS);
591 EmitByte(0xC4, CurByte, OS);
592 EmitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, CurByte, OS);
593 EmitByte(LastByte | (VEX_W << 7), CurByte, OS);
596 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
597 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
598 /// size, and 3) use of X86-64 extended registers.
599 static unsigned DetermineREXPrefix(const MCInst &MI, uint64_t TSFlags,
600 const MCInstrDesc &Desc) {
602 if (TSFlags & X86II::REX_W)
603 REX |= 1 << 3; // set REX.W
605 if (MI.getNumOperands() == 0) return REX;
607 unsigned NumOps = MI.getNumOperands();
608 // FIXME: MCInst should explicitize the two-addrness.
609 bool isTwoAddr = NumOps > 1 &&
610 Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1;
612 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
613 unsigned i = isTwoAddr ? 1 : 0;
614 for (; i != NumOps; ++i) {
615 const MCOperand &MO = MI.getOperand(i);
616 if (!MO.isReg()) continue;
617 unsigned Reg = MO.getReg();
618 if (!X86II::isX86_64NonExtLowByteReg(Reg)) continue;
619 // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
620 // that returns non-zero.
621 REX |= 0x40; // REX fixed encoding prefix
625 switch (TSFlags & X86II::FormMask) {
626 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
627 case X86II::MRMSrcReg:
628 if (MI.getOperand(0).isReg() &&
629 X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
630 REX |= 1 << 2; // set REX.R
631 i = isTwoAddr ? 2 : 1;
632 for (; i != NumOps; ++i) {
633 const MCOperand &MO = MI.getOperand(i);
634 if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
635 REX |= 1 << 0; // set REX.B
638 case X86II::MRMSrcMem: {
639 if (MI.getOperand(0).isReg() &&
640 X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
641 REX |= 1 << 2; // set REX.R
643 i = isTwoAddr ? 2 : 1;
644 for (; i != NumOps; ++i) {
645 const MCOperand &MO = MI.getOperand(i);
647 if (X86II::isX86_64ExtendedReg(MO.getReg()))
648 REX |= 1 << Bit; // set REX.B (Bit=0) and REX.X (Bit=1)
654 case X86II::MRM0m: case X86II::MRM1m:
655 case X86II::MRM2m: case X86II::MRM3m:
656 case X86II::MRM4m: case X86II::MRM5m:
657 case X86II::MRM6m: case X86II::MRM7m:
658 case X86II::MRMDestMem: {
659 unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
660 i = isTwoAddr ? 1 : 0;
661 if (NumOps > e && MI.getOperand(e).isReg() &&
662 X86II::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
663 REX |= 1 << 2; // set REX.R
665 for (; i != e; ++i) {
666 const MCOperand &MO = MI.getOperand(i);
668 if (X86II::isX86_64ExtendedReg(MO.getReg()))
669 REX |= 1 << Bit; // REX.B (Bit=0) and REX.X (Bit=1)
676 if (MI.getOperand(0).isReg() &&
677 X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
678 REX |= 1 << 0; // set REX.B
679 i = isTwoAddr ? 2 : 1;
680 for (unsigned e = NumOps; i != e; ++i) {
681 const MCOperand &MO = MI.getOperand(i);
682 if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
683 REX |= 1 << 2; // set REX.R
690 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
691 void X86MCCodeEmitter::EmitSegmentOverridePrefix(uint64_t TSFlags,
692 unsigned &CurByte, int MemOperand,
694 raw_ostream &OS) const {
695 switch (TSFlags & X86II::SegOvrMask) {
696 default: assert(0 && "Invalid segment!");
698 // No segment override, check for explicit one on memory operand.
699 if (MemOperand != -1) { // If the instruction has a memory operand.
700 switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
701 default: assert(0 && "Unknown segment register!");
703 case X86::CS: EmitByte(0x2E, CurByte, OS); break;
704 case X86::SS: EmitByte(0x36, CurByte, OS); break;
705 case X86::DS: EmitByte(0x3E, CurByte, OS); break;
706 case X86::ES: EmitByte(0x26, CurByte, OS); break;
707 case X86::FS: EmitByte(0x64, CurByte, OS); break;
708 case X86::GS: EmitByte(0x65, CurByte, OS); break;
713 EmitByte(0x64, CurByte, OS);
716 EmitByte(0x65, CurByte, OS);
721 /// EmitOpcodePrefix - Emit all instruction prefixes prior to the opcode.
723 /// MemOperand is the operand # of the start of a memory operand if present. If
724 /// Not present, it is -1.
725 void X86MCCodeEmitter::EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
726 int MemOperand, const MCInst &MI,
727 const MCInstrDesc &Desc,
728 raw_ostream &OS) const {
730 // Emit the lock opcode prefix as needed.
731 if (TSFlags & X86II::LOCK)
732 EmitByte(0xF0, CurByte, OS);
734 // Emit segment override opcode prefix as needed.
735 EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
737 // Emit the repeat opcode prefix as needed.
738 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
739 EmitByte(0xF3, CurByte, OS);
741 // Emit the address size opcode prefix as needed.
742 if ((TSFlags & X86II::AdSize) ||
743 (MemOperand != -1 && is64BitMode() && Is32BitMemOperand(MI, MemOperand)))
744 EmitByte(0x67, CurByte, OS);
746 // Emit the operand size opcode prefix as needed.
747 if (TSFlags & X86II::OpSize)
748 EmitByte(0x66, CurByte, OS);
750 bool Need0FPrefix = false;
751 switch (TSFlags & X86II::Op0Mask) {
752 default: assert(0 && "Invalid prefix!");
753 case 0: break; // No prefix!
754 case X86II::REP: break; // already handled.
755 case X86II::TB: // Two-byte opcode prefix
756 case X86II::T8: // 0F 38
757 case X86II::TA: // 0F 3A
758 case X86II::A6: // 0F A6
759 case X86II::A7: // 0F A7
762 case X86II::TF: // F2 0F 38
763 EmitByte(0xF2, CurByte, OS);
766 case X86II::XS: // F3 0F
767 EmitByte(0xF3, CurByte, OS);
770 case X86II::XD: // F2 0F
771 EmitByte(0xF2, CurByte, OS);
774 case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
775 case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
776 case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
777 case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
778 case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
779 case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
780 case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
781 case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
784 // Handle REX prefix.
785 // FIXME: Can this come before F2 etc to simplify emission?
787 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
788 EmitByte(0x40 | REX, CurByte, OS);
791 // 0x0F escape code must be emitted just before the opcode.
793 EmitByte(0x0F, CurByte, OS);
795 // FIXME: Pull this up into previous switch if REX can be moved earlier.
796 switch (TSFlags & X86II::Op0Mask) {
797 case X86II::TF: // F2 0F 38
798 case X86II::T8: // 0F 38
799 EmitByte(0x38, CurByte, OS);
801 case X86II::TA: // 0F 3A
802 EmitByte(0x3A, CurByte, OS);
804 case X86II::A6: // 0F A6
805 EmitByte(0xA6, CurByte, OS);
807 case X86II::A7: // 0F A7
808 EmitByte(0xA7, CurByte, OS);
813 void X86MCCodeEmitter::
814 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
815 SmallVectorImpl<MCFixup> &Fixups) const {
816 unsigned Opcode = MI.getOpcode();
817 const MCInstrDesc &Desc = MCII.get(Opcode);
818 uint64_t TSFlags = Desc.TSFlags;
820 // Pseudo instructions don't get encoded.
821 if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
824 // If this is a two-address instruction, skip one of the register operands.
825 // FIXME: This should be handled during MCInst lowering.
826 unsigned NumOps = Desc.getNumOperands();
828 if (NumOps > 1 && Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1)
830 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, MCOI::TIED_TO)== 0)
831 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
834 // Keep track of the current byte being emitted.
835 unsigned CurByte = 0;
837 // Is this instruction encoded using the AVX VEX prefix?
838 bool HasVEXPrefix = false;
840 // It uses the VEX.VVVV field?
841 bool HasVEX_4V = false;
843 if ((TSFlags >> X86II::VEXShift) & X86II::VEX)
845 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_4V)
849 // Determine where the memory operand starts, if present.
850 int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
851 if (MemoryOperand != -1) MemoryOperand += CurOp;
854 EmitOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
856 EmitVEXOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
859 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
861 if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
862 BaseOpcode = 0x0F; // Weird 3DNow! encoding.
864 unsigned SrcRegNum = 0;
865 switch (TSFlags & X86II::FormMask) {
866 case X86II::MRMInitReg:
867 assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
868 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
869 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
871 assert(0 && "Pseudo instruction shouldn't be emitted");
873 EmitByte(BaseOpcode, CurByte, OS);
876 case X86II::RawFrmImm8:
877 EmitByte(BaseOpcode, CurByte, OS);
878 EmitImmediate(MI.getOperand(CurOp++),
879 X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
880 CurByte, OS, Fixups);
881 EmitImmediate(MI.getOperand(CurOp++), 1, FK_Data_1, CurByte, OS, Fixups);
883 case X86II::RawFrmImm16:
884 EmitByte(BaseOpcode, CurByte, OS);
885 EmitImmediate(MI.getOperand(CurOp++),
886 X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
887 CurByte, OS, Fixups);
888 EmitImmediate(MI.getOperand(CurOp++), 2, FK_Data_2, CurByte, OS, Fixups);
891 case X86II::AddRegFrm:
892 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
895 case X86II::MRMDestReg:
896 EmitByte(BaseOpcode, CurByte, OS);
897 EmitRegModRMByte(MI.getOperand(CurOp),
898 GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
902 case X86II::MRMDestMem:
903 EmitByte(BaseOpcode, CurByte, OS);
904 SrcRegNum = CurOp + X86::AddrNumOperands;
906 if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
909 EmitMemModRMByte(MI, CurOp,
910 GetX86RegNum(MI.getOperand(SrcRegNum)),
911 TSFlags, CurByte, OS, Fixups);
912 CurOp = SrcRegNum + 1;
915 case X86II::MRMSrcReg:
916 EmitByte(BaseOpcode, CurByte, OS);
917 SrcRegNum = CurOp + 1;
919 if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
922 EmitRegModRMByte(MI.getOperand(SrcRegNum),
923 GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
924 CurOp = SrcRegNum + 1;
927 case X86II::MRMSrcMem: {
928 int AddrOperands = X86::AddrNumOperands;
929 unsigned FirstMemOp = CurOp+1;
932 ++FirstMemOp; // Skip the register source (which is encoded in VEX_VVVV).
935 EmitByte(BaseOpcode, CurByte, OS);
937 EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
938 TSFlags, CurByte, OS, Fixups);
939 CurOp += AddrOperands + 1;
943 case X86II::MRM0r: case X86II::MRM1r:
944 case X86II::MRM2r: case X86II::MRM3r:
945 case X86II::MRM4r: case X86II::MRM5r:
946 case X86II::MRM6r: case X86II::MRM7r:
947 if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
949 EmitByte(BaseOpcode, CurByte, OS);
950 EmitRegModRMByte(MI.getOperand(CurOp++),
951 (TSFlags & X86II::FormMask)-X86II::MRM0r,
954 case X86II::MRM0m: case X86II::MRM1m:
955 case X86II::MRM2m: case X86II::MRM3m:
956 case X86II::MRM4m: case X86II::MRM5m:
957 case X86II::MRM6m: case X86II::MRM7m:
958 EmitByte(BaseOpcode, CurByte, OS);
959 EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
960 TSFlags, CurByte, OS, Fixups);
961 CurOp += X86::AddrNumOperands;
964 EmitByte(BaseOpcode, CurByte, OS);
965 EmitByte(0xC1, CurByte, OS);
968 EmitByte(BaseOpcode, CurByte, OS);
969 EmitByte(0xC2, CurByte, OS);
972 EmitByte(BaseOpcode, CurByte, OS);
973 EmitByte(0xC3, CurByte, OS);
976 EmitByte(BaseOpcode, CurByte, OS);
977 EmitByte(0xC4, CurByte, OS);
980 EmitByte(BaseOpcode, CurByte, OS);
981 EmitByte(0xC8, CurByte, OS);
984 EmitByte(BaseOpcode, CurByte, OS);
985 EmitByte(0xC9, CurByte, OS);
988 EmitByte(BaseOpcode, CurByte, OS);
989 EmitByte(0xE8, CurByte, OS);
992 EmitByte(BaseOpcode, CurByte, OS);
993 EmitByte(0xF0, CurByte, OS);
996 EmitByte(BaseOpcode, CurByte, OS);
997 EmitByte(0xF8, CurByte, OS);
1000 EmitByte(BaseOpcode, CurByte, OS);
1001 EmitByte(0xF9, CurByte, OS);
1004 EmitByte(BaseOpcode, CurByte, OS);
1005 EmitByte(0xD0, CurByte, OS);
1008 EmitByte(BaseOpcode, CurByte, OS);
1009 EmitByte(0xD1, CurByte, OS);
1013 // If there is a remaining operand, it must be a trailing immediate. Emit it
1014 // according to the right size for the instruction.
1015 if (CurOp != NumOps) {
1016 // The last source register of a 4 operand instruction in AVX is encoded
1017 // in bits[7:4] of a immediate byte, and bits[3:0] are ignored.
1018 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM) {
1019 const MCOperand &MO = MI.getOperand(CurOp++);
1021 X86II::isX86_64ExtendedReg(MO.getReg());
1022 unsigned RegNum = (IsExtReg ? (1 << 7) : 0);
1023 RegNum |= GetX86RegNum(MO) << 4;
1024 EmitImmediate(MCOperand::CreateImm(RegNum), 1, FK_Data_1, CurByte, OS,
1028 // FIXME: Is there a better way to know that we need a signed relocation?
1029 if (MI.getOpcode() == X86::ADD64ri32 ||
1030 MI.getOpcode() == X86::MOV64ri32 ||
1031 MI.getOpcode() == X86::MOV64mi32 ||
1032 MI.getOpcode() == X86::PUSH64i32)
1033 FixupKind = X86::reloc_signed_4byte;
1035 FixupKind = getImmFixupKind(TSFlags);
1036 EmitImmediate(MI.getOperand(CurOp++),
1037 X86II::getSizeOfImm(TSFlags), MCFixupKind(FixupKind),
1038 CurByte, OS, Fixups);
1042 if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
1043 EmitByte(X86II::getBaseOpcodeFor(TSFlags), CurByte, OS);
1048 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
1049 errs() << "Cannot encode all operands of: ";