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)
31 : TM(tm), TII(*TM.getInstrInfo()) {
32 // FIXME: Get this from the right place.
36 ~X86MCCodeEmitter() {}
38 static unsigned GetX86RegNum(const MCOperand &MO) {
39 return X86RegisterInfo::getX86RegNum(MO.getReg());
42 void EmitByte(unsigned char C, raw_ostream &OS) const {
46 void EmitConstant(uint64_t Val, unsigned Size, raw_ostream &OS) const {
47 // Output the constant in little endian byte order.
48 for (unsigned i = 0; i != Size; ++i) {
49 EmitByte(Val & 255, OS);
54 void EmitDisplacementField(const MCOperand *RelocOp, int DispVal,
55 int64_t Adj, bool IsPCRel, raw_ostream &OS) const;
57 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
59 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
60 return RM | (RegOpcode << 3) | (Mod << 6);
63 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
64 raw_ostream &OS) const {
65 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), OS);
68 void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
69 raw_ostream &OS) const {
70 // SIB byte is in the same format as the ModRMByte...
71 EmitByte(ModRMByte(SS, Index, Base), OS);
75 void EmitMemModRMByte(const MCInst &MI, unsigned Op,
76 unsigned RegOpcodeField, intptr_t PCAdj,
77 raw_ostream &OS) const;
79 void EncodeInstruction(const MCInst &MI, raw_ostream &OS) const;
83 } // end anonymous namespace
86 MCCodeEmitter *llvm::createX86MCCodeEmitter(const Target &,
88 return new X86MCCodeEmitter(TM);
92 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
93 /// sign-extended field.
94 static bool isDisp8(int Value) {
95 return Value == (signed char)Value;
98 void X86MCCodeEmitter::
99 EmitDisplacementField(const MCOperand *RelocOp, int DispVal,
100 int64_t Adj, bool IsPCRel, raw_ostream &OS) const {
101 // If this is a simple integer displacement that doesn't require a relocation,
104 EmitConstant(DispVal, 4, OS);
108 assert(0 && "Reloc not handled yet");
110 // Otherwise, this is something that requires a relocation. Emit it as such
112 unsigned RelocType = Is64BitMode ?
113 (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
114 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
115 if (RelocOp->isGlobal()) {
116 // In 64-bit static small code model, we could potentially emit absolute.
117 // But it's probably not beneficial. If the MCE supports using RIP directly
118 // do it, otherwise fallback to absolute (this is determined by IsPCRel).
119 // 89 05 00 00 00 00 mov %eax,0(%rip) # PC-relative
120 // 89 04 25 00 00 00 00 mov %eax,0x0 # Absolute
121 bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
122 emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
124 } else if (RelocOp->isSymbol()) {
125 emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
126 } else if (RelocOp->isCPI()) {
127 emitConstPoolAddress(RelocOp->getIndex(), RelocType,
128 RelocOp->getOffset(), Adj);
130 assert(RelocOp->isJTI() && "Unexpected machine operand!");
131 emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
137 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
138 unsigned RegOpcodeField,
140 raw_ostream &OS) const {
141 const MCOperand &Op3 = MI.getOperand(Op+3);
143 const MCOperand *DispForReloc = 0;
145 // Figure out what sort of displacement we have to handle here.
147 DispVal = Op3.getImm();
149 assert(0 && "Unknown operand");
151 if (Op3.isGlobal()) {
153 } else if (Op3.isSymbol()) {
155 } else if (Op3.isCPI()) {
156 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
159 DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
160 DispVal += Op3.getOffset();
164 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
167 DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
172 const MCOperand &Base = MI.getOperand(Op);
173 const MCOperand &Scale = MI.getOperand(Op+1);
174 const MCOperand &IndexReg = MI.getOperand(Op+2);
175 unsigned BaseReg = Base.getReg();
178 bool IsPCRel = false;
180 // Is a SIB byte needed?
181 // If no BaseReg, issue a RIP relative instruction only if the MCE can
182 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
183 // 2-7) and absolute references.
184 if ((!Is64BitMode || DispForReloc || BaseReg != 0) &&
185 IndexReg.getReg() == 0 &&
186 (BaseReg == X86::RIP || (BaseReg != 0 && BaseReg != X86::ESP))) {
187 if (BaseReg == 0 || BaseReg == X86::RIP) { // Just a displacement?
188 // Emit special case [disp32] encoding
189 EmitByte(ModRMByte(0, RegOpcodeField, 5), OS);
190 EmitDisplacementField(DispForReloc, DispVal, PCAdj, true, OS);
192 unsigned BaseRegNo = GetX86RegNum(Base);
193 if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
194 // Emit simple indirect register encoding... [EAX] f.e.
195 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), OS);
196 } else if (!DispForReloc && isDisp8(DispVal)) {
197 // Emit the disp8 encoding... [REG+disp8]
198 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), OS);
199 EmitConstant(DispVal, 1, OS);
201 // Emit the most general non-SIB encoding: [REG+disp32]
202 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), OS);
203 EmitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel, OS);
209 // We need a SIB byte, so start by outputting the ModR/M byte first
210 assert(IndexReg.getReg() != X86::ESP &&
211 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
213 bool ForceDisp32 = false;
214 bool ForceDisp8 = false;
216 // If there is no base register, we emit the special case SIB byte with
217 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
218 EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
220 } else if (DispForReloc) {
221 // Emit the normal disp32 encoding.
222 EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
224 } else if (DispVal == 0 && BaseReg != X86::EBP) {
225 // Emit no displacement ModR/M byte
226 EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
227 } else if (isDisp8(DispVal)) {
228 // Emit the disp8 encoding.
229 EmitByte(ModRMByte(1, RegOpcodeField, 4), OS);
230 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
232 // Emit the normal disp32 encoding.
233 EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
236 // Calculate what the SS field value should be...
237 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
238 unsigned SS = SSTable[Scale.getImm()];
241 // Handle the SIB byte for the case where there is no base, see Intel
242 // Manual 2A, table 2-7. The displacement has already been output.
244 if (IndexReg.getReg())
245 IndexRegNo = GetX86RegNum(IndexReg);
246 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
248 EmitSIBByte(SS, IndexRegNo, 5, OS);
251 if (IndexReg.getReg())
252 IndexRegNo = GetX86RegNum(IndexReg);
254 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
255 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), OS);
258 // Do we need to output a displacement?
260 EmitConstant(DispVal, 1, OS);
261 else if (DispVal != 0 || ForceDisp32)
262 EmitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel, OS);
266 void X86MCCodeEmitter::
267 EncodeInstruction(const MCInst &MI, raw_ostream &OS) const {
268 unsigned Opcode = MI.getOpcode();
269 const TargetInstrDesc &Desc = TII.get(Opcode);
270 unsigned TSFlags = Desc.TSFlags;
272 // FIXME: We should emit the prefixes in exactly the same order as GAS does,
273 // in order to provide diffability.
275 // Emit the lock opcode prefix as needed.
276 if (TSFlags & X86II::LOCK)
279 // Emit segment override opcode prefix as needed.
280 switch (TSFlags & X86II::SegOvrMask) {
281 default: assert(0 && "Invalid segment!");
282 case 0: break; // No segment override!
291 // Emit the repeat opcode prefix as needed.
292 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
295 // Emit the operand size opcode prefix as needed.
296 if (TSFlags & X86II::OpSize)
299 // Emit the address size opcode prefix as needed.
300 if (TSFlags & X86II::AdSize)
303 bool Need0FPrefix = false;
304 switch (TSFlags & X86II::Op0Mask) {
305 default: assert(0 && "Invalid prefix!");
306 case 0: break; // No prefix!
307 case X86II::REP: break; // already handled.
308 case X86II::TB: // Two-byte opcode prefix
309 case X86II::T8: // 0F 38
310 case X86II::TA: // 0F 3A
313 case X86II::TF: // F2 0F 38
317 case X86II::XS: // F3 0F
321 case X86II::XD: // F2 0F
325 case X86II::D8: EmitByte(0xD8, OS); break;
326 case X86II::D9: EmitByte(0xD9, OS); break;
327 case X86II::DA: EmitByte(0xDA, OS); break;
328 case X86II::DB: EmitByte(0xDB, OS); break;
329 case X86II::DC: EmitByte(0xDC, OS); break;
330 case X86II::DD: EmitByte(0xDD, OS); break;
331 case X86II::DE: EmitByte(0xDE, OS); break;
332 case X86II::DF: EmitByte(0xDF, OS); break;
335 // Handle REX prefix.
336 #if 0 // FIXME: Add in, also, can this come before F2 etc to simplify emission?
338 if (unsigned REX = X86InstrInfo::determineREX(MI))
339 EmitByte(0x40 | REX, OS);
343 // 0x0F escape code must be emitted just before the opcode.
347 // FIXME: Pull this up into previous switch if REX can be moved earlier.
348 switch (TSFlags & X86II::Op0Mask) {
349 case X86II::TF: // F2 0F 38
350 case X86II::T8: // 0F 38
353 case X86II::TA: // 0F 3A
358 // If this is a two-address instruction, skip one of the register operands.
359 unsigned NumOps = Desc.getNumOperands();
361 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
363 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
364 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
367 // FIXME: Can we kill off MRMInitReg??
369 unsigned char BaseOpcode = X86InstrInfo::getBaseOpcodeFor(Desc);
370 switch (TSFlags & X86II::FormMask) {
371 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
372 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
373 case X86II::RawFrm: {
374 EmitByte(BaseOpcode, OS);
379 assert(0 && "Unimpl RawFrm expr");
383 case X86II::AddRegFrm: {
384 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)),OS);
388 const MCOperand &MO1 = MI.getOperand(CurOp++);
390 unsigned Size = X86InstrInfo::sizeOfImm(&Desc);
391 EmitConstant(MO1.getImm(), Size, OS);
395 assert(0 && "Unimpl AddRegFrm expr");
399 case X86II::MRMDestReg:
400 EmitByte(BaseOpcode, OS);
401 EmitRegModRMByte(MI.getOperand(CurOp),
402 GetX86RegNum(MI.getOperand(CurOp+1)), OS);
405 EmitConstant(MI.getOperand(CurOp++).getImm(),
406 X86InstrInfo::sizeOfImm(&Desc), OS);
409 case X86II::MRMDestMem:
410 EmitByte(BaseOpcode, OS);
411 EmitMemModRMByte(MI, CurOp,
412 GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
414 CurOp += X86AddrNumOperands + 1;
416 EmitConstant(MI.getOperand(CurOp++).getImm(),
417 X86InstrInfo::sizeOfImm(&Desc), OS);
422 if (!Desc.isVariadic() && CurOp != NumOps) {
423 errs() << "Cannot encode all operands of: ";