blob: e24e2904b51e957b57ed18e23577208e8663a299 [file] [log] [blame]
Misha Brukmancd603132003-06-02 03:28:00 +00001//===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner40ead952002-12-02 21:24:12 +00009//
10// This file contains the pass that transforms the X86 machine instructions into
11// actual executable machine code.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnercb533582003-08-03 21:14:38 +000015#define DEBUG_TYPE "jit"
Chris Lattner40ead952002-12-02 21:24:12 +000016#include "X86TargetMachine.h"
Chris Lattnerea1ddab2002-12-03 06:34:06 +000017#include "X86.h"
Chris Lattner40ead952002-12-02 21:24:12 +000018#include "llvm/PassManager.h"
19#include "llvm/CodeGen/MachineCodeEmitter.h"
Chris Lattner5ae99fe2002-12-28 20:24:48 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattner76041ce2002-12-02 21:44:34 +000021#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerc01d1232003-10-20 03:42:58 +000022#include "llvm/Function.h"
Chris Lattnera11136b2003-08-01 22:21:34 +000023#include "Support/Debug.h"
Chris Lattner302de592003-06-06 04:00:05 +000024#include "Support/Statistic.h"
John Criswell7a73b802003-06-30 21:59:07 +000025#include "Config/alloca.h"
Chris Lattner40ead952002-12-02 21:24:12 +000026
Brian Gaeked0fde302003-11-11 22:41:34 +000027namespace llvm {
28
Chris Lattner40ead952002-12-02 21:24:12 +000029namespace {
Chris Lattner302de592003-06-06 04:00:05 +000030 Statistic<>
31 NumEmitted("x86-emitter", "Number of machine instructions emitted");
32
Chris Lattner04b0b302003-06-01 23:23:50 +000033 class JITResolver {
34 MachineCodeEmitter &MCE;
35
36 // LazyCodeGenMap - Keep track of call sites for functions that are to be
37 // lazily resolved.
38 std::map<unsigned, Function*> LazyCodeGenMap;
39
40 // LazyResolverMap - Keep track of the lazy resolver created for a
41 // particular function so that we can reuse them if necessary.
42 std::map<Function*, unsigned> LazyResolverMap;
43 public:
44 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
45 unsigned getLazyResolver(Function *F);
46 unsigned addFunctionReference(unsigned Address, Function *F);
47
48 private:
49 unsigned emitStubForFunction(Function *F);
50 static void CompilationCallback();
51 unsigned resolveFunctionReference(unsigned RetAddr);
52 };
53
54 JITResolver *TheJITResolver;
55}
56
57
58/// addFunctionReference - This method is called when we need to emit the
59/// address of a function that has not yet been emitted, so we don't know the
60/// address. Instead, we emit a call to the CompilationCallback method, and
61/// keep track of where we are.
62///
63unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
64 LazyCodeGenMap[Address] = F;
65 return (intptr_t)&JITResolver::CompilationCallback;
66}
67
68unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
69 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
70 assert(I != LazyCodeGenMap.end() && "Not in map!");
71 Function *F = I->second;
72 LazyCodeGenMap.erase(I);
73 return MCE.forceCompilationOf(F);
74}
75
76unsigned JITResolver::getLazyResolver(Function *F) {
77 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
78 if (I != LazyResolverMap.end() && I->first == F) return I->second;
79
80//std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
81
82 unsigned Stub = emitStubForFunction(F);
83 LazyResolverMap.insert(I, std::make_pair(F, Stub));
84 return Stub;
85}
86
87void JITResolver::CompilationCallback() {
88 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
Misha Brukmanbc80b222003-06-02 04:13:58 +000089 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
Chris Lattner04b0b302003-06-01 23:23:50 +000090 assert(StackPtr[1] == RetAddr &&
91 "Could not find return address on the stack!");
Chris Lattner30d002b2003-06-06 18:25:33 +000092
93 // It's a stub if there is an interrupt marker after the call...
94 bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
Chris Lattner04b0b302003-06-01 23:23:50 +000095
Chris Lattner302de592003-06-06 04:00:05 +000096 // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
97 // pointer elimination has been performed. Having a variable sized alloca
98 // disables frame pointer elimination currently, even if it's dead. This is a
99 // gross hack.
100 alloca(10+isStub);
101 // FIXME FIXME FIXME FIXME
102
Chris Lattner04b0b302003-06-01 23:23:50 +0000103 // The call instruction should have pushed the return value onto the stack...
104 RetAddr -= 4; // Backtrack to the reference itself...
105
106#if 0
107 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
108 << " ESP=0x" << (unsigned)StackPtr << std::dec
109 << ": Resolving call to function: "
110 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
111#endif
112
113 // Sanity check to make sure this really is a call instruction...
Chris Lattner30d002b2003-06-06 18:25:33 +0000114 assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000115
116 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
117
118 // Rewrite the call target... so that we don't fault every time we execute
119 // the call.
Chris Lattner30d002b2003-06-06 18:25:33 +0000120 *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
Chris Lattner04b0b302003-06-01 23:23:50 +0000121
122 if (isStub) {
123 // If this is a stub, rewrite the call into an unconditional branch
124 // instruction so that two return addresses are not pushed onto the stack
125 // when the requested function finally gets called. This also makes the
126 // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
Chris Lattner30d002b2003-06-06 18:25:33 +0000127 ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
Chris Lattner04b0b302003-06-01 23:23:50 +0000128 }
129
130 // Change the return address to reexecute the call instruction...
131 StackPtr[1] -= 5;
132}
133
134/// emitStubForFunction - This method is used by the JIT when it needs to emit
135/// the address of a function for a function whose code has not yet been
136/// generated. In order to do this, it generates a stub which jumps to the lazy
137/// function compiler, which will eventually get fixed to call the function
138/// directly.
139///
140unsigned JITResolver::emitStubForFunction(Function *F) {
141 MCE.startFunctionStub(*F, 6);
142 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
143
144 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
145 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
146
147 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
148 return (intptr_t)MCE.finishFunctionStub(*F);
149}
150
151
152
153namespace {
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000154 class Emitter : public MachineFunctionPass {
155 const X86InstrInfo *II;
Chris Lattner8f04b092002-12-02 21:56:18 +0000156 MachineCodeEmitter &MCE;
Chris Lattnerdee12632003-07-26 23:06:00 +0000157 std::map<const BasicBlock*, unsigned> BasicBlockAddrs;
158 std::vector<std::pair<const BasicBlock*, unsigned> > BBRefs;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000159 public:
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000160 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
Chris Lattner40ead952002-12-02 21:24:12 +0000161
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000162 bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner76041ce2002-12-02 21:44:34 +0000163
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000164 virtual const char *getPassName() const {
165 return "X86 Machine Code Emitter";
166 }
167
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000168 private:
Chris Lattner76041ce2002-12-02 21:44:34 +0000169 void emitBasicBlock(MachineBasicBlock &MBB);
170 void emitInstruction(MachineInstr &MI);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000171
Chris Lattner04b0b302003-06-01 23:23:50 +0000172 void emitPCRelativeBlockAddress(BasicBlock *BB);
173 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
174 void emitGlobalAddressForCall(GlobalValue *GV);
175 void emitGlobalAddressForPtr(GlobalValue *GV);
176
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000177 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
178 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
179 void emitConstant(unsigned Val, unsigned Size);
180
181 void emitMemModRMByte(const MachineInstr &MI,
182 unsigned Op, unsigned RegOpcodeField);
183
Chris Lattner40ead952002-12-02 21:24:12 +0000184 };
185}
186
Chris Lattner40ead952002-12-02 21:24:12 +0000187/// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
Brian Gaeke45f0b6d2003-10-16 23:45:05 +0000188/// machine code emitted. This uses a MachineCodeEmitter object to handle
Chris Lattner40ead952002-12-02 21:24:12 +0000189/// actually outputting the machine code and resolving things like the address
190/// of functions. This method should returns true if machine code emission is
191/// not supported.
192///
Brian Gaeke8844a0b2003-08-13 18:17:27 +0000193bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
Chris Lattner40ead952002-12-02 21:24:12 +0000194 MachineCodeEmitter &MCE) {
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000195 PM.add(new Emitter(MCE));
Chris Lattner40ead952002-12-02 21:24:12 +0000196 return false;
197}
Chris Lattner76041ce2002-12-02 21:44:34 +0000198
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000199bool Emitter::runOnMachineFunction(MachineFunction &MF) {
200 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
Chris Lattner76041ce2002-12-02 21:44:34 +0000201
202 MCE.startFunction(MF);
Chris Lattnere831b6b2003-01-13 00:33:59 +0000203 MCE.emitConstantPool(MF.getConstantPool());
Chris Lattner76041ce2002-12-02 21:44:34 +0000204 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
205 emitBasicBlock(*I);
206 MCE.finishFunction(MF);
Chris Lattner04b0b302003-06-01 23:23:50 +0000207
208 // Resolve all forward branches now...
209 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
210 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
211 unsigned Ref = BBRefs[i].second;
Chris Lattner30d002b2003-06-06 18:25:33 +0000212 *(unsigned*)(intptr_t)Ref = Location-Ref-4;
Chris Lattner04b0b302003-06-01 23:23:50 +0000213 }
214 BBRefs.clear();
215 BasicBlockAddrs.clear();
Chris Lattner76041ce2002-12-02 21:44:34 +0000216 return false;
217}
218
219void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000220 if (uint64_t Addr = MCE.getCurrentPCValue())
221 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
222
Chris Lattner76041ce2002-12-02 21:44:34 +0000223 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
224 emitInstruction(**I);
225}
226
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000227
Chris Lattner04b0b302003-06-01 23:23:50 +0000228/// emitPCRelativeBlockAddress - This method emits the PC relative address of
229/// the specified basic block, or if the basic block hasn't been emitted yet
230/// (because this is a forward branch), it keeps track of the information
231/// necessary to resolve this address later (and emits a dummy value).
232///
233void Emitter::emitPCRelativeBlockAddress(BasicBlock *BB) {
234 // FIXME: Emit backward branches directly
235 BBRefs.push_back(std::make_pair(BB, MCE.getCurrentPCValue()));
236 MCE.emitWord(0); // Emit a dummy value
237}
238
239/// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
240///
241void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
242 if (isPCRelative)
243 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
244 else
245 MCE.emitWord(Address);
246}
247
248/// emitGlobalAddressForCall - Emit the specified address to the code stream
249/// assuming this is part of a function call, which is PC relative.
250///
251void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
252 // Get the address from the backend...
253 unsigned Address = MCE.getGlobalValueAddress(GV);
254
Chris Lattner04b0b302003-06-01 23:23:50 +0000255 if (Address == 0) {
256 // FIXME: this is JIT specific!
257 if (TheJITResolver == 0)
258 TheJITResolver = new JITResolver(MCE);
259 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
Chris Lattnerc01d1232003-10-20 03:42:58 +0000260 cast<Function>(GV));
Chris Lattner04b0b302003-06-01 23:23:50 +0000261 }
262 emitMaybePCRelativeValue(Address, true);
263}
264
265/// emitGlobalAddress - Emit the specified address to the code stream assuming
266/// this is part of a "take the address of a global" instruction, which is not
267/// PC relative.
268///
269void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
270 // Get the address from the backend...
271 unsigned Address = MCE.getGlobalValueAddress(GV);
272
273 // If the machine code emitter doesn't know what the address IS yet, we have
274 // to take special measures.
275 //
276 if (Address == 0) {
277 // FIXME: this is JIT specific!
278 if (TheJITResolver == 0)
279 TheJITResolver = new JITResolver(MCE);
280 Address = TheJITResolver->getLazyResolver((Function*)GV);
281 }
282
283 emitMaybePCRelativeValue(Address, false);
284}
285
286
287
Chris Lattnerff3261a2003-06-03 15:31:23 +0000288/// N86 namespace - Native X86 Register numbers... used by X86 backend.
289///
290namespace N86 {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000291 enum {
292 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
293 };
294}
295
296
297// getX86RegNum - This function maps LLVM register identifiers to their X86
298// specific numbering, which is used in various places encoding instructions.
299//
300static unsigned getX86RegNum(unsigned RegNo) {
301 switch(RegNo) {
302 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
303 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
304 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
305 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
306 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
307 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
308 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
309 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000310
311 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
312 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
313 return RegNo-X86::ST0;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000314 default:
315 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
316 "Unknown physical register!");
317 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
318 return 0;
319 }
320}
321
322inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
323 unsigned RM) {
324 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
325 return RM | (RegOpcode << 3) | (Mod << 6);
326}
327
328void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
329 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
330}
331
332void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
333 // SIB byte is in the same format as the ModRMByte...
334 MCE.emitByte(ModRMByte(SS, Index, Base));
335}
336
337void Emitter::emitConstant(unsigned Val, unsigned Size) {
338 // Output the constant in little endian byte order...
339 for (unsigned i = 0; i != Size; ++i) {
340 MCE.emitByte(Val & 255);
341 Val >>= 8;
342 }
343}
344
345static bool isDisp8(int Value) {
346 return Value == (signed char)Value;
347}
348
349void Emitter::emitMemModRMByte(const MachineInstr &MI,
350 unsigned Op, unsigned RegOpcodeField) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000351 const MachineOperand &Disp = MI.getOperand(Op+3);
352 if (MI.getOperand(Op).isConstantPoolIndex()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000353 // Emit a direct address reference [disp32] where the displacement of the
354 // constant pool entry is controlled by the MCE.
Chris Lattnere831b6b2003-01-13 00:33:59 +0000355 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
356 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
Chris Lattner04b0b302003-06-01 23:23:50 +0000357 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
358 MCE.emitWord(Address+Disp.getImmedValue());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000359 return;
360 }
361
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000362 const MachineOperand &BaseReg = MI.getOperand(Op);
363 const MachineOperand &Scale = MI.getOperand(Op+1);
364 const MachineOperand &IndexReg = MI.getOperand(Op+2);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000365
366 // Is a SIB byte needed?
367 if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
368 if (BaseReg.getReg() == 0) { // Just a displacement?
369 // Emit special case [disp32] encoding
370 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
371 emitConstant(Disp.getImmedValue(), 4);
372 } else {
373 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
374 if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
375 // Emit simple indirect register encoding... [EAX] f.e.
376 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
377 } else if (isDisp8(Disp.getImmedValue())) {
378 // Emit the disp8 encoding... [REG+disp8]
379 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
380 emitConstant(Disp.getImmedValue(), 1);
381 } else {
382 // Emit the most general non-SIB encoding: [REG+disp32]
Chris Lattner20671842002-12-13 05:05:05 +0000383 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000384 emitConstant(Disp.getImmedValue(), 4);
385 }
386 }
387
388 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
389 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
390
391 bool ForceDisp32 = false;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000392 bool ForceDisp8 = false;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000393 if (BaseReg.getReg() == 0) {
394 // If there is no base register, we emit the special case SIB byte with
395 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
396 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
397 ForceDisp32 = true;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000398 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000399 // Emit no displacement ModR/M byte
400 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
401 } else if (isDisp8(Disp.getImmedValue())) {
402 // Emit the disp8 encoding...
403 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
Brian Gaeke95780cc2002-12-13 07:56:18 +0000404 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000405 } else {
406 // Emit the normal disp32 encoding...
407 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
408 }
409
410 // Calculate what the SS field value should be...
411 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
412 unsigned SS = SSTable[Scale.getImmedValue()];
413
414 if (BaseReg.getReg() == 0) {
415 // Handle the SIB byte for the case where there is no base. The
416 // displacement has already been output.
417 assert(IndexReg.getReg() && "Index register must be specified!");
418 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
419 } else {
420 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000421 unsigned IndexRegNo;
422 if (IndexReg.getReg())
423 IndexRegNo = getX86RegNum(IndexReg.getReg());
424 else
425 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000426 emitSIBByte(SS, IndexRegNo, BaseRegNo);
427 }
428
429 // Do we need to output a displacement?
Brian Gaeke95780cc2002-12-13 07:56:18 +0000430 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000431 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
432 emitConstant(Disp.getImmedValue(), 1);
433 else
434 emitConstant(Disp.getImmedValue(), 4);
435 }
436 }
437}
438
Chris Lattner04b0b302003-06-01 23:23:50 +0000439static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
Chris Lattnera0f38c82002-12-13 03:51:55 +0000440 switch (Desc.TSFlags & X86II::ArgMask) {
441 case X86II::Arg8: return 1;
442 case X86II::Arg16: return 2;
443 case X86II::Arg32: return 4;
Chris Lattner5ada8df2002-12-25 05:09:21 +0000444 case X86II::ArgF32: return 4;
445 case X86II::ArgF64: return 8;
446 case X86II::ArgF80: return 10;
Chris Lattnera6a382c2002-12-13 03:50:13 +0000447 default: assert(0 && "Memory size not set!");
Chris Lattnerdf642e12002-12-20 04:12:48 +0000448 return 0;
Misha Brukman5000e432002-12-13 02:13:15 +0000449 }
450}
451
Chris Lattner76041ce2002-12-02 21:44:34 +0000452void Emitter::emitInstruction(MachineInstr &MI) {
Chris Lattner302de592003-06-06 04:00:05 +0000453 NumEmitted++; // Keep track of the # of mi's emitted
454
Chris Lattner76041ce2002-12-02 21:44:34 +0000455 unsigned Opcode = MI.getOpcode();
Chris Lattner3501fea2003-01-14 22:00:31 +0000456 const TargetInstrDescriptor &Desc = II->get(Opcode);
Chris Lattner76041ce2002-12-02 21:44:34 +0000457
Misha Brukman5560c9d2003-08-18 14:43:39 +0000458 // Emit instruction prefixes if necessary
Chris Lattner76041ce2002-12-02 21:44:34 +0000459 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
Chris Lattner5ada8df2002-12-25 05:09:21 +0000460
461 switch (Desc.TSFlags & X86II::Op0Mask) {
462 case X86II::TB:
463 MCE.emitByte(0x0F); // Two-byte opcode prefix
464 break;
465 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
466 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
Chris Lattnere831b6b2003-01-13 00:33:59 +0000467 MCE.emitByte(0xD8+
468 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
469 >> X86II::Op0Shift));
Chris Lattner5ada8df2002-12-25 05:09:21 +0000470 break; // Two-byte opcode prefix
Chris Lattnere831b6b2003-01-13 00:33:59 +0000471 default: assert(0 && "Invalid prefix!");
472 case 0: break; // No prefix!
Chris Lattner5ada8df2002-12-25 05:09:21 +0000473 }
Chris Lattner76041ce2002-12-02 21:44:34 +0000474
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000475 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
Chris Lattner76041ce2002-12-02 21:44:34 +0000476 switch (Desc.TSFlags & X86II::FormMask) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000477 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
Chris Lattner5ada8df2002-12-25 05:09:21 +0000478 case X86II::Pseudo:
Chris Lattner02beda12003-08-05 00:48:47 +0000479 if (Opcode != X86::IMPLICIT_USE && Opcode != X86::IMPLICIT_DEF)
Chris Lattner9dedbcc2003-05-06 21:31:47 +0000480 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
Chris Lattner5ada8df2002-12-25 05:09:21 +0000481 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000482
Chris Lattner76041ce2002-12-02 21:44:34 +0000483 case X86II::RawFrm:
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000484 MCE.emitByte(BaseOpcode);
Chris Lattner8f04b092002-12-02 21:56:18 +0000485 if (MI.getNumOperands() == 1) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000486 MachineOperand &MO = MI.getOperand(0);
487 if (MO.isPCRelativeDisp()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000488 // Conditional branch... FIXME: this should use an MBB destination!
489 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
Chris Lattnere831b6b2003-01-13 00:33:59 +0000490 } else if (MO.isGlobalAddress()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000491 assert(MO.isPCRelative() && "Call target is not PC Relative?");
492 emitGlobalAddressForCall(MO.getGlobal());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000493 } else if (MO.isExternalSymbol()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000494 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
495 assert(Address && "Unknown external symbol!");
496 emitMaybePCRelativeValue(Address, MO.isPCRelative());
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000497 } else {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000498 assert(0 && "Unknown RawFrm operand!");
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000499 }
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000500 }
501 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000502
503 case X86II::AddRegFrm:
504 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
505 if (MI.getNumOperands() == 2) {
506 MachineOperand &MO1 = MI.getOperand(1);
507 if (MO1.isImmediate() || MO1.getVRegValueOrNull() ||
508 MO1.isGlobalAddress() || MO1.isExternalSymbol()) {
509 unsigned Size = sizeOfPtr(Desc);
510 if (Value *V = MO1.getVRegValueOrNull()) {
511 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000512 emitGlobalAddressForPtr(cast<GlobalValue>(V));
Chris Lattnere831b6b2003-01-13 00:33:59 +0000513 } else if (MO1.isGlobalAddress()) {
514 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000515 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
516 emitGlobalAddressForPtr(MO1.getGlobal());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000517 } else if (MO1.isExternalSymbol()) {
518 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000519
520 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
521 assert(Address && "Unknown external symbol!");
522 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000523 } else {
524 emitConstant(MO1.getImmedValue(), Size);
525 }
526 }
527 }
528 break;
529
530 case X86II::MRMDestReg: {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000531 MCE.emitByte(BaseOpcode);
Chris Lattnere831b6b2003-01-13 00:33:59 +0000532 MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
533 emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
534 if (MI.getNumOperands() == 4)
535 emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
Chris Lattner9dedbcc2003-05-06 21:31:47 +0000536 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000537 }
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000538 case X86II::MRMDestMem:
539 MCE.emitByte(BaseOpcode);
540 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
541 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000542
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000543 case X86II::MRMSrcReg:
544 MCE.emitByte(BaseOpcode);
Chris Lattnerc01d1232003-10-20 03:42:58 +0000545
546 if (MI.getNumOperands() == 2) {
547 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
548 getX86RegNum(MI.getOperand(0).getReg()));
549 } else if (MI.getOperand(2).isImmediate()) {
550 emitRegModRMByte(MI.getOperand(1).getReg(),
551 getX86RegNum(MI.getOperand(0).getReg()));
552
553 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfPtr(Desc));
554 } else {
555 emitRegModRMByte(MI.getOperand(2).getReg(),
556 getX86RegNum(MI.getOperand(0).getReg()));
557 }
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000558 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000559
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000560 case X86II::MRMSrcMem:
561 MCE.emitByte(BaseOpcode);
562 emitMemModRMByte(MI, MI.getNumOperands()-4,
563 getX86RegNum(MI.getOperand(0).getReg()));
564 break;
565
566 case X86II::MRMS0r: case X86II::MRMS1r:
567 case X86II::MRMS2r: case X86II::MRMS3r:
568 case X86II::MRMS4r: case X86II::MRMS5r:
569 case X86II::MRMS6r: case X86II::MRMS7r:
570 MCE.emitByte(BaseOpcode);
571 emitRegModRMByte(MI.getOperand(0).getReg(),
572 (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r);
573
Chris Lattnerd9096832002-12-15 08:01:39 +0000574 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
Misha Brukman5000e432002-12-13 02:13:15 +0000575 unsigned Size = sizeOfPtr(Desc);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000576 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
577 }
578 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000579
580 case X86II::MRMS0m: case X86II::MRMS1m:
581 case X86II::MRMS2m: case X86II::MRMS3m:
582 case X86II::MRMS4m: case X86II::MRMS5m:
583 case X86II::MRMS6m: case X86II::MRMS7m:
584 MCE.emitByte(BaseOpcode);
585 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0m);
586
587 if (MI.getNumOperands() == 5) {
588 unsigned Size = sizeOfPtr(Desc);
589 emitConstant(MI.getOperand(4).getImmedValue(), Size);
590 }
591 break;
Chris Lattner76041ce2002-12-02 21:44:34 +0000592 }
593}
Brian Gaeked0fde302003-11-11 22:41:34 +0000594
595} // End llvm namespace