1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
13 //===----------------------------------------------------------------------===//
15 #include "X86TargetMachine.h"
16 #include "X86Relocations.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Function.h"
24 #include "llvm/ADT/Statistic.h"
29 NumEmitted("x86-emitter", "Number of machine instructions emitted");
33 class Emitter : public MachineFunctionPass {
34 const X86InstrInfo *II;
35 MachineCodeEmitter &MCE;
36 std::map<const MachineBasicBlock*, unsigned> BasicBlockAddrs;
37 std::vector<std::pair<const MachineBasicBlock *, unsigned> > BBRefs;
39 explicit Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
40 Emitter(MachineCodeEmitter &mce, const X86InstrInfo& ii)
41 : II(&ii), MCE(mce) {}
43 bool runOnMachineFunction(MachineFunction &MF);
45 virtual const char *getPassName() const {
46 return "X86 Machine Code Emitter";
49 void emitInstruction(const MachineInstr &MI);
52 void emitBasicBlock(const MachineBasicBlock &MBB);
54 void emitPCRelativeBlockAddress(const MachineBasicBlock *BB);
55 void emitPCRelativeValue(unsigned Address);
56 void emitGlobalAddressForCall(GlobalValue *GV);
57 void emitGlobalAddressForPtr(GlobalValue *GV, int Disp = 0);
58 void emitExternalSymbolAddress(const char *ES, bool isPCRelative);
60 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
61 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
62 void emitConstant(unsigned Val, unsigned Size);
64 void emitMemModRMByte(const MachineInstr &MI,
65 unsigned Op, unsigned RegOpcodeField);
70 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
71 /// machine code emitted. This uses a MachineCodeEmitter object to handle
72 /// actually outputting the machine code and resolving things like the address
73 /// of functions. This method should returns true if machine code emission is
76 bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
77 MachineCodeEmitter &MCE) {
78 PM.add(new Emitter(MCE));
79 // Delete machine code for this function
80 PM.add(createMachineCodeDeleter());
84 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
85 II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
87 MCE.startFunction(MF);
88 MCE.emitConstantPool(MF.getConstantPool());
89 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
91 MCE.finishFunction(MF);
93 // Resolve all forward branches now...
94 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
95 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
96 unsigned Ref = BBRefs[i].second;
97 MCE.emitWordAt(Location-Ref-4, (unsigned*)(intptr_t)Ref);
100 BasicBlockAddrs.clear();
104 void Emitter::emitBasicBlock(const MachineBasicBlock &MBB) {
105 if (uint64_t Addr = MCE.getCurrentPCValue())
106 BasicBlockAddrs[&MBB] = Addr;
108 for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end();
113 /// emitPCRelativeValue - Emit a 32-bit PC relative address.
115 void Emitter::emitPCRelativeValue(unsigned Address) {
116 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
119 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
120 /// the specified basic block, or if the basic block hasn't been emitted yet
121 /// (because this is a forward branch), it keeps track of the information
122 /// necessary to resolve this address later (and emits a dummy value).
124 void Emitter::emitPCRelativeBlockAddress(const MachineBasicBlock *MBB) {
125 // If this is a backwards branch, we already know the address of the target,
126 // so just emit the value.
127 std::map<const MachineBasicBlock*, unsigned>::iterator I =
128 BasicBlockAddrs.find(MBB);
129 if (I != BasicBlockAddrs.end()) {
130 emitPCRelativeValue(I->second);
132 // Otherwise, remember where this reference was and where it is to so we can
133 // deal with it later.
134 BBRefs.push_back(std::make_pair(MBB, MCE.getCurrentPCValue()));
139 /// emitGlobalAddressForCall - Emit the specified address to the code stream
140 /// assuming this is part of a function call, which is PC relative.
142 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
143 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
144 X86::reloc_pcrel_word, GV, 0, true));
148 /// emitGlobalAddress - Emit the specified address to the code stream assuming
149 /// this is part of a "take the address of a global" instruction, which is not
152 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV, int Disp /* = 0 */) {
153 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
154 X86::reloc_absolute_word, GV));
155 MCE.emitWord(Disp); // The relocated value will be added to the displacement
158 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
159 /// be emitted to the current location in the function, and allow it to be PC
161 void Emitter::emitExternalSymbolAddress(const char *ES, bool isPCRelative) {
162 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
163 isPCRelative ? X86::reloc_pcrel_word : X86::reloc_absolute_word, ES));
167 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
171 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
176 // getX86RegNum - This function maps LLVM register identifiers to their X86
177 // specific numbering, which is used in various places encoding instructions.
179 static unsigned getX86RegNum(unsigned RegNo) {
181 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
182 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
183 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
184 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
185 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
186 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
187 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
188 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
190 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
191 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
192 return RegNo-X86::ST0;
194 assert(MRegisterInfo::isVirtualRegister(RegNo) &&
195 "Unknown physical register!");
196 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
201 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
203 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
204 return RM | (RegOpcode << 3) | (Mod << 6);
207 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
208 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
211 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
212 // SIB byte is in the same format as the ModRMByte...
213 MCE.emitByte(ModRMByte(SS, Index, Base));
216 void Emitter::emitConstant(unsigned Val, unsigned Size) {
217 // Output the constant in little endian byte order...
218 for (unsigned i = 0; i != Size; ++i) {
219 MCE.emitByte(Val & 255);
224 static bool isDisp8(int Value) {
225 return Value == (signed char)Value;
228 void Emitter::emitMemModRMByte(const MachineInstr &MI,
229 unsigned Op, unsigned RegOpcodeField) {
230 const MachineOperand &Op3 = MI.getOperand(Op+3);
234 if (Op3.isGlobalAddress()) {
235 GV = Op3.getGlobal();
236 DispVal = Op3.getOffset();
238 DispVal = Op3.getImmedValue();
241 const MachineOperand &Base = MI.getOperand(Op);
242 const MachineOperand &Scale = MI.getOperand(Op+1);
243 const MachineOperand &IndexReg = MI.getOperand(Op+2);
245 unsigned BaseReg = 0;
247 if (Base.isConstantPoolIndex()) {
248 // Emit a direct address reference [disp32] where the displacement of the
249 // constant pool entry is controlled by the MCE.
250 assert(!GV && "Constant Pool reference cannot be relative to global!");
251 DispVal += MCE.getConstantPoolEntryAddress(Base.getConstantPoolIndex());
253 BaseReg = Base.getReg();
256 // Is a SIB byte needed?
257 if (IndexReg.getReg() == 0 && BaseReg != X86::ESP) {
258 if (BaseReg == 0) { // Just a displacement?
259 // Emit special case [disp32] encoding
260 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
262 emitGlobalAddressForPtr(GV, DispVal);
264 emitConstant(DispVal, 4);
266 unsigned BaseRegNo = getX86RegNum(BaseReg);
268 // Emit the most general non-SIB encoding: [REG+disp32]
269 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
270 emitGlobalAddressForPtr(GV, DispVal);
271 } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
272 // Emit simple indirect register encoding... [EAX] f.e.
273 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
274 } else if (isDisp8(DispVal)) {
275 // Emit the disp8 encoding... [REG+disp8]
276 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
277 emitConstant(DispVal, 1);
279 // Emit the most general non-SIB encoding: [REG+disp32]
280 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
281 emitConstant(DispVal, 4);
285 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
286 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
288 bool ForceDisp32 = false;
289 bool ForceDisp8 = false;
291 // If there is no base register, we emit the special case SIB byte with
292 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
293 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
296 // Emit the normal disp32 encoding...
297 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
299 } else if (DispVal == 0 && BaseReg != X86::EBP) {
300 // Emit no displacement ModR/M byte
301 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
302 } else if (isDisp8(DispVal)) {
303 // Emit the disp8 encoding...
304 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
305 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
307 // Emit the normal disp32 encoding...
308 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
311 // Calculate what the SS field value should be...
312 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
313 unsigned SS = SSTable[Scale.getImmedValue()];
316 // Handle the SIB byte for the case where there is no base. The
317 // displacement has already been output.
318 assert(IndexReg.getReg() && "Index register must be specified!");
319 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
321 unsigned BaseRegNo = getX86RegNum(BaseReg);
323 if (IndexReg.getReg())
324 IndexRegNo = getX86RegNum(IndexReg.getReg());
326 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
327 emitSIBByte(SS, IndexRegNo, BaseRegNo);
330 // Do we need to output a displacement?
331 if (DispVal != 0 || ForceDisp32 || ForceDisp8) {
332 if (!ForceDisp32 && isDisp8(DispVal))
333 emitConstant(DispVal, 1);
335 emitGlobalAddressForPtr(GV, DispVal);
337 emitConstant(DispVal, 4);
342 static unsigned sizeOfImm(const TargetInstrDescriptor &Desc) {
343 switch (Desc.TSFlags & X86II::ImmMask) {
344 case X86II::Imm8: return 1;
345 case X86II::Imm16: return 2;
346 case X86II::Imm32: return 4;
347 default: assert(0 && "Immediate size not set!");
352 void Emitter::emitInstruction(const MachineInstr &MI) {
353 NumEmitted++; // Keep track of the # of mi's emitted
355 unsigned Opcode = MI.getOpcode();
356 const TargetInstrDescriptor &Desc = II->get(Opcode);
358 // Emit the repeat opcode prefix as needed.
359 if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
361 // Emit instruction prefixes if necessary
362 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
364 switch (Desc.TSFlags & X86II::Op0Mask) {
366 MCE.emitByte(0x0F); // Two-byte opcode prefix
368 case X86II::REP: break; // already handled.
369 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
370 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
372 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
373 >> X86II::Op0Shift));
374 break; // Two-byte opcode prefix
375 default: assert(0 && "Invalid prefix!");
376 case 0: break; // No prefix!
379 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
380 switch (Desc.TSFlags & X86II::FormMask) {
381 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
383 if (Opcode != X86::IMPLICIT_USE &&
384 Opcode != X86::IMPLICIT_DEF &&
385 Opcode != X86::FP_REG_KILL)
386 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
390 MCE.emitByte(BaseOpcode);
391 if (MI.getNumOperands() == 1) {
392 const MachineOperand &MO = MI.getOperand(0);
393 if (MO.isMachineBasicBlock()) {
394 emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
395 } else if (MO.isGlobalAddress()) {
396 assert(MO.isPCRelative() && "Call target is not PC Relative?");
397 emitGlobalAddressForCall(MO.getGlobal());
398 } else if (MO.isExternalSymbol()) {
399 emitExternalSymbolAddress(MO.getSymbolName(), true);
400 } else if (MO.isImmediate()) {
401 emitConstant(MO.getImmedValue(), sizeOfImm(Desc));
403 assert(0 && "Unknown RawFrm operand!");
408 case X86II::AddRegFrm:
409 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
410 if (MI.getNumOperands() == 2) {
411 const MachineOperand &MO1 = MI.getOperand(1);
412 if (Value *V = MO1.getVRegValueOrNull()) {
413 assert(sizeOfImm(Desc) == 4 &&
414 "Don't know how to emit non-pointer values!");
415 emitGlobalAddressForPtr(cast<GlobalValue>(V));
416 } else if (MO1.isGlobalAddress()) {
417 assert(sizeOfImm(Desc) == 4 &&
418 "Don't know how to emit non-pointer values!");
419 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
420 emitGlobalAddressForPtr(MO1.getGlobal(), MO1.getOffset());
421 } else if (MO1.isExternalSymbol()) {
422 assert(sizeOfImm(Desc) == 4 &&
423 "Don't know how to emit non-pointer values!");
424 emitExternalSymbolAddress(MO1.getSymbolName(), false);
426 emitConstant(MO1.getImmedValue(), sizeOfImm(Desc));
431 case X86II::MRMDestReg: {
432 MCE.emitByte(BaseOpcode);
433 emitRegModRMByte(MI.getOperand(0).getReg(),
434 getX86RegNum(MI.getOperand(1).getReg()));
435 if (MI.getNumOperands() == 3)
436 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
439 case X86II::MRMDestMem:
440 MCE.emitByte(BaseOpcode);
441 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
442 if (MI.getNumOperands() == 6)
443 emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
446 case X86II::MRMSrcReg:
447 MCE.emitByte(BaseOpcode);
449 emitRegModRMByte(MI.getOperand(1).getReg(),
450 getX86RegNum(MI.getOperand(0).getReg()));
451 if (MI.getNumOperands() == 3)
452 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
455 case X86II::MRMSrcMem:
456 MCE.emitByte(BaseOpcode);
457 emitMemModRMByte(MI, 1, getX86RegNum(MI.getOperand(0).getReg()));
458 if (MI.getNumOperands() == 2+4)
459 emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
462 case X86II::MRM0r: case X86II::MRM1r:
463 case X86II::MRM2r: case X86II::MRM3r:
464 case X86II::MRM4r: case X86II::MRM5r:
465 case X86II::MRM6r: case X86II::MRM7r:
466 MCE.emitByte(BaseOpcode);
467 emitRegModRMByte(MI.getOperand(0).getReg(),
468 (Desc.TSFlags & X86II::FormMask)-X86II::MRM0r);
470 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
471 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(),
476 case X86II::MRM0m: case X86II::MRM1m:
477 case X86II::MRM2m: case X86II::MRM3m:
478 case X86II::MRM4m: case X86II::MRM5m:
479 case X86II::MRM6m: case X86II::MRM7m:
480 MCE.emitByte(BaseOpcode);
481 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRM0m);
483 if (MI.getNumOperands() == 5) {
484 if (MI.getOperand(4).isImmediate())
485 emitConstant(MI.getOperand(4).getImmedValue(), sizeOfImm(Desc));
486 else if (MI.getOperand(4).isGlobalAddress())
487 emitGlobalAddressForPtr(MI.getOperand(4).getGlobal(),
488 MI.getOperand(4).getOffset());
490 assert(0 && "Unknown operand!");