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 "x86-emitter"
16 #include "X86InstrInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/Support/raw_ostream.h"
23 class X86MCCodeEmitter : public MCCodeEmitter {
24 X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
25 void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
26 const TargetMachine &TM;
27 const TargetInstrInfo &TII;
30 X86MCCodeEmitter(TargetMachine &tm, bool is64Bit)
31 : TM(tm), TII(*TM.getInstrInfo()) {
32 Is64BitMode = is64Bit;
35 ~X86MCCodeEmitter() {}
37 unsigned getNumFixupKinds() const {
41 MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
42 static MCFixupKindInfo Infos[] = {
43 { "reloc_pcrel_word", 0, 4 * 8 },
44 { "reloc_picrel_word", 0, 4 * 8 },
45 { "reloc_absolute_word", 0, 4 * 8 },
46 { "reloc_absolute_word_sext", 0, 4 * 8 },
47 { "reloc_absolute_dword", 0, 8 * 8 }
50 assert(Kind >= FirstTargetFixupKind && Kind < MaxTargetFixupKind &&
52 return Infos[Kind - FirstTargetFixupKind];
55 static unsigned GetX86RegNum(const MCOperand &MO) {
56 return X86RegisterInfo::getX86RegNum(MO.getReg());
59 void EmitByte(unsigned char C, raw_ostream &OS) const {
63 void EmitConstant(uint64_t Val, unsigned Size, raw_ostream &OS) const {
64 // Output the constant in little endian byte order.
65 for (unsigned i = 0; i != Size; ++i) {
66 EmitByte(Val & 255, OS);
71 void EmitDisplacementField(const MCOperand &Disp, int64_t Adj, bool IsPCRel,
72 raw_ostream &OS) const;
74 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
76 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
77 return RM | (RegOpcode << 3) | (Mod << 6);
80 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
81 raw_ostream &OS) const {
82 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), OS);
85 void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
86 raw_ostream &OS) const {
87 // SIB byte is in the same format as the ModRMByte...
88 EmitByte(ModRMByte(SS, Index, Base), OS);
92 void EmitMemModRMByte(const MCInst &MI, unsigned Op,
93 unsigned RegOpcodeField, intptr_t PCAdj,
94 raw_ostream &OS) const;
96 void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
97 SmallVectorImpl<MCFixup> &Fixups) const;
101 } // end anonymous namespace
104 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
106 return new X86MCCodeEmitter(TM, false);
109 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
111 return new X86MCCodeEmitter(TM, true);
115 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
116 /// sign-extended field.
117 static bool isDisp8(int Value) {
118 return Value == (signed char)Value;
121 void X86MCCodeEmitter::
122 EmitDisplacementField(const MCOperand &DispOp, int64_t Adj, bool IsPCRel,
123 raw_ostream &OS) const {
124 // If this is a simple integer displacement that doesn't require a relocation,
126 if (DispOp.isImm()) {
127 EmitConstant(DispOp.getImm(), 4, OS);
131 assert(0 && "Reloc not handled yet");
133 // Otherwise, this is something that requires a relocation. Emit it as such
135 unsigned RelocType = Is64BitMode ?
136 (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
137 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
138 if (RelocOp->isGlobal()) {
139 // In 64-bit static small code model, we could potentially emit absolute.
140 // But it's probably not beneficial. If the MCE supports using RIP directly
141 // do it, otherwise fallback to absolute (this is determined by IsPCRel).
142 // 89 05 00 00 00 00 mov %eax,0(%rip) # PC-relative
143 // 89 04 25 00 00 00 00 mov %eax,0x0 # Absolute
144 bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
145 emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
147 } else if (RelocOp->isSymbol()) {
148 emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
149 } else if (RelocOp->isCPI()) {
150 emitConstPoolAddress(RelocOp->getIndex(), RelocType,
151 RelocOp->getOffset(), Adj);
153 assert(RelocOp->isJTI() && "Unexpected machine operand!");
154 emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
160 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
161 unsigned RegOpcodeField,
162 intptr_t PCAdj, raw_ostream &OS) const {
163 const MCOperand &Disp = MI.getOperand(Op+3);
164 const MCOperand &Base = MI.getOperand(Op);
165 const MCOperand &Scale = MI.getOperand(Op+1);
166 const MCOperand &IndexReg = MI.getOperand(Op+2);
167 unsigned BaseReg = Base.getReg();
170 bool IsPCRel = false;
172 // Determine whether a SIB byte is needed.
173 // If no BaseReg, issue a RIP relative instruction only if the MCE can
174 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
175 // 2-7) and absolute references.
176 if (// The SIB byte must be used if there is an index register.
177 IndexReg.getReg() == 0 &&
178 // The SIB byte must be used if the base is ESP/RSP.
179 BaseReg != X86::ESP && BaseReg != X86::RSP &&
180 // If there is no base register and we're in 64-bit mode, we need a SIB
181 // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
182 (!Is64BitMode || BaseReg != 0)) {
184 if (BaseReg == 0 || // [disp32] in X86-32 mode
185 BaseReg == X86::RIP) { // [disp32+RIP] in X86-64 mode
186 EmitByte(ModRMByte(0, RegOpcodeField, 5), OS);
187 EmitDisplacementField(Disp, PCAdj, true, OS);
191 unsigned BaseRegNo = GetX86RegNum(Base);
193 // If the base is not EBP/ESP and there is no displacement, use simple
194 // indirect register encoding, this handles addresses like [EAX]. The
195 // encoding for [EBP] with no displacement means [disp32] so we handle it
196 // by emitting a displacement of 0 below.
197 if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
198 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), OS);
202 // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
203 if (Disp.isImm() && isDisp8(Disp.getImm())) {
204 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), OS);
205 EmitConstant(Disp.getImm(), 1, OS);
209 // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
210 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), OS);
211 EmitDisplacementField(Disp, PCAdj, IsPCRel, OS);
215 // We need a SIB byte, so start by outputting the ModR/M byte first
216 assert(IndexReg.getReg() != X86::ESP &&
217 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
219 bool ForceDisp32 = false;
220 bool ForceDisp8 = false;
222 // If there is no base register, we emit the special case SIB byte with
223 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
224 EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
226 } else if (!Disp.isImm()) {
227 // Emit the normal disp32 encoding.
228 EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
230 } else if (Disp.getImm() == 0 && BaseReg != X86::EBP) {
231 // Emit no displacement ModR/M byte
232 EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
233 } else if (isDisp8(Disp.getImm())) {
234 // Emit the disp8 encoding.
235 EmitByte(ModRMByte(1, RegOpcodeField, 4), OS);
236 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
238 // Emit the normal disp32 encoding.
239 EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
242 // Calculate what the SS field value should be...
243 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
244 unsigned SS = SSTable[Scale.getImm()];
247 // Handle the SIB byte for the case where there is no base, see Intel
248 // Manual 2A, table 2-7. The displacement has already been output.
250 if (IndexReg.getReg())
251 IndexRegNo = GetX86RegNum(IndexReg);
252 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
254 EmitSIBByte(SS, IndexRegNo, 5, OS);
257 if (IndexReg.getReg())
258 IndexRegNo = GetX86RegNum(IndexReg);
260 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
261 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), OS);
264 // Do we need to output a displacement?
266 EmitConstant(Disp.getImm(), 1, OS);
267 else if (ForceDisp32 || Disp.getImm() != 0)
268 EmitDisplacementField(Disp, PCAdj, IsPCRel, OS);
271 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
272 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
273 /// size, and 3) use of X86-64 extended registers.
274 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
275 const TargetInstrDesc &Desc) {
278 // Pseudo instructions do not need REX prefix byte.
279 if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
281 if (TSFlags & X86II::REX_W)
284 if (MI.getNumOperands() == 0) return REX;
286 unsigned NumOps = MI.getNumOperands();
287 // FIXME: MCInst should explicitize the two-addrness.
288 bool isTwoAddr = NumOps > 1 &&
289 Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
291 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
292 unsigned i = isTwoAddr ? 1 : 0;
293 for (; i != NumOps; ++i) {
294 const MCOperand &MO = MI.getOperand(i);
295 if (!MO.isReg()) continue;
296 unsigned Reg = MO.getReg();
297 if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
298 // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
299 // that returns non-zero.
304 switch (TSFlags & X86II::FormMask) {
305 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
306 case X86II::MRMSrcReg:
307 if (MI.getOperand(0).isReg() &&
308 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
310 i = isTwoAddr ? 2 : 1;
311 for (; i != NumOps; ++i) {
312 const MCOperand &MO = MI.getOperand(i);
313 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
317 case X86II::MRMSrcMem: {
318 if (MI.getOperand(0).isReg() &&
319 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
322 i = isTwoAddr ? 2 : 1;
323 for (; i != NumOps; ++i) {
324 const MCOperand &MO = MI.getOperand(i);
326 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
333 case X86II::MRM0m: case X86II::MRM1m:
334 case X86II::MRM2m: case X86II::MRM3m:
335 case X86II::MRM4m: case X86II::MRM5m:
336 case X86II::MRM6m: case X86II::MRM7m:
337 case X86II::MRMDestMem: {
338 unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
339 i = isTwoAddr ? 1 : 0;
340 if (NumOps > e && MI.getOperand(e).isReg() &&
341 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
344 for (; i != e; ++i) {
345 const MCOperand &MO = MI.getOperand(i);
347 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
355 if (MI.getOperand(0).isReg() &&
356 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
358 i = isTwoAddr ? 2 : 1;
359 for (unsigned e = NumOps; i != e; ++i) {
360 const MCOperand &MO = MI.getOperand(i);
361 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
369 void X86MCCodeEmitter::
370 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
371 SmallVectorImpl<MCFixup> &Fixups) const {
372 unsigned Opcode = MI.getOpcode();
373 const TargetInstrDesc &Desc = TII.get(Opcode);
374 unsigned TSFlags = Desc.TSFlags;
376 // FIXME: We should emit the prefixes in exactly the same order as GAS does,
377 // in order to provide diffability.
379 // Emit the lock opcode prefix as needed.
380 if (TSFlags & X86II::LOCK)
383 // Emit segment override opcode prefix as needed.
384 switch (TSFlags & X86II::SegOvrMask) {
385 default: assert(0 && "Invalid segment!");
386 case 0: break; // No segment override!
395 // Emit the repeat opcode prefix as needed.
396 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
399 // Emit the operand size opcode prefix as needed.
400 if (TSFlags & X86II::OpSize)
403 // Emit the address size opcode prefix as needed.
404 if (TSFlags & X86II::AdSize)
407 bool Need0FPrefix = false;
408 switch (TSFlags & X86II::Op0Mask) {
409 default: assert(0 && "Invalid prefix!");
410 case 0: break; // No prefix!
411 case X86II::REP: break; // already handled.
412 case X86II::TB: // Two-byte opcode prefix
413 case X86II::T8: // 0F 38
414 case X86II::TA: // 0F 3A
417 case X86II::TF: // F2 0F 38
421 case X86II::XS: // F3 0F
425 case X86II::XD: // F2 0F
429 case X86II::D8: EmitByte(0xD8, OS); break;
430 case X86II::D9: EmitByte(0xD9, OS); break;
431 case X86II::DA: EmitByte(0xDA, OS); break;
432 case X86II::DB: EmitByte(0xDB, OS); break;
433 case X86II::DC: EmitByte(0xDC, OS); break;
434 case X86II::DD: EmitByte(0xDD, OS); break;
435 case X86II::DE: EmitByte(0xDE, OS); break;
436 case X86II::DF: EmitByte(0xDF, OS); break;
439 // Handle REX prefix.
440 // FIXME: Can this come before F2 etc to simplify emission?
442 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
443 EmitByte(0x40 | REX, OS);
446 // 0x0F escape code must be emitted just before the opcode.
450 // FIXME: Pull this up into previous switch if REX can be moved earlier.
451 switch (TSFlags & X86II::Op0Mask) {
452 case X86II::TF: // F2 0F 38
453 case X86II::T8: // 0F 38
456 case X86II::TA: // 0F 3A
461 // If this is a two-address instruction, skip one of the register operands.
462 unsigned NumOps = Desc.getNumOperands();
464 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
466 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
467 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
470 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
471 switch (TSFlags & X86II::FormMask) {
472 case X86II::MRMInitReg:
473 assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
474 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
475 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
476 case X86II::RawFrm: {
477 EmitByte(BaseOpcode, OS);
482 assert(0 && "Unimpl RawFrm expr");
486 case X86II::AddRegFrm: {
487 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)),OS);
491 const MCOperand &MO1 = MI.getOperand(CurOp++);
493 unsigned Size = X86II::getSizeOfImm(TSFlags);
494 EmitConstant(MO1.getImm(), Size, OS);
498 assert(0 && "Unimpl AddRegFrm expr");
502 case X86II::MRMDestReg:
503 EmitByte(BaseOpcode, OS);
504 EmitRegModRMByte(MI.getOperand(CurOp),
505 GetX86RegNum(MI.getOperand(CurOp+1)), OS);
508 EmitConstant(MI.getOperand(CurOp++).getImm(),
509 X86II::getSizeOfImm(TSFlags), OS);
512 case X86II::MRMDestMem:
513 EmitByte(BaseOpcode, OS);
514 EmitMemModRMByte(MI, CurOp,
515 GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
517 CurOp += X86AddrNumOperands + 1;
519 EmitConstant(MI.getOperand(CurOp++).getImm(),
520 X86II::getSizeOfImm(TSFlags), OS);
523 case X86II::MRMSrcReg:
524 EmitByte(BaseOpcode, OS);
525 EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
529 EmitConstant(MI.getOperand(CurOp++).getImm(),
530 X86II::getSizeOfImm(TSFlags), OS);
533 case X86II::MRMSrcMem: {
534 EmitByte(BaseOpcode, OS);
536 // FIXME: Maybe lea should have its own form? This is a horrible hack.
538 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
539 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
540 AddrOperands = X86AddrNumOperands - 1; // No segment register
542 AddrOperands = X86AddrNumOperands;
544 // FIXME: What is this actually doing?
545 intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
546 X86II::getSizeOfImm(TSFlags) : 0;
548 EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
550 CurOp += AddrOperands + 1;
552 EmitConstant(MI.getOperand(CurOp++).getImm(),
553 X86II::getSizeOfImm(TSFlags), OS);
557 case X86II::MRM0r: case X86II::MRM1r:
558 case X86II::MRM2r: case X86II::MRM3r:
559 case X86II::MRM4r: case X86II::MRM5r:
560 case X86II::MRM6r: case X86II::MRM7r: {
561 EmitByte(BaseOpcode, OS);
563 // Special handling of lfence, mfence, monitor, and mwait.
564 // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
565 if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
566 Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
567 EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r, 0), OS);
571 case X86::MONITOR: EmitByte(0xC8, OS); break;
572 case X86::MWAIT: EmitByte(0xC9, OS); break;
575 EmitRegModRMByte(MI.getOperand(CurOp++),
576 (TSFlags & X86II::FormMask)-X86II::MRM0r,
583 const MCOperand &MO1 = MI.getOperand(CurOp++);
585 EmitConstant(MO1.getImm(), X86II::getSizeOfImm(TSFlags), OS);
589 assert(0 && "relo unimpl");
591 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
592 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
593 if (Opcode == X86::MOV64ri32)
594 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
595 if (MO1.isGlobal()) {
596 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
597 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
599 } else if (MO1.isSymbol())
600 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
601 else if (MO1.isCPI())
602 emitConstPoolAddress(MO1.getIndex(), rt);
603 else if (MO1.isJTI())
604 emitJumpTableAddress(MO1.getIndex(), rt);
608 case X86II::MRM0m: case X86II::MRM1m:
609 case X86II::MRM2m: case X86II::MRM3m:
610 case X86II::MRM4m: case X86II::MRM5m:
611 case X86II::MRM6m: case X86II::MRM7m: {
613 if (CurOp + X86AddrNumOperands != NumOps) {
614 if (MI.getOperand(CurOp+X86AddrNumOperands).isImm())
615 PCAdj = X86II::getSizeOfImm(TSFlags);
620 EmitByte(BaseOpcode, OS);
621 EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
623 CurOp += X86AddrNumOperands;
628 const MCOperand &MO = MI.getOperand(CurOp++);
630 EmitConstant(MO.getImm(), X86II::getSizeOfImm(TSFlags), OS);
634 assert(0 && "relo not handled");
636 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
637 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
638 if (Opcode == X86::MOV64mi32)
639 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
641 bool Indirect = gvNeedsNonLazyPtr(MO, TM);
642 emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
644 } else if (MO.isSymbol())
645 emitExternalSymbolAddress(MO.getSymbolName(), rt);
647 emitConstPoolAddress(MO.getIndex(), rt);
649 emitJumpTableAddress(MO.getIndex(), rt);
657 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
658 errs() << "Cannot encode all operands of: ";