blob: 108b6b85833997e231456a8736c264d1ceda7c74 [file] [log] [blame]
Chris Lattner166f2262004-11-22 22:00:25 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
Chris Lattner5be478f2004-11-20 03:46:14 +000010// This file defines a MachineCodeEmitter object that is used by the JIT to
11// write machine code to memory and remember where relocatable values are.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Chris Lattner4d326fa2003-12-20 01:46:27 +000016#include "JIT.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000017#include "llvm/Constant.h"
18#include "llvm/Module.h"
Chris Lattner5b3a4552005-03-17 15:38:16 +000019#include "llvm/Type.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/CodeGen/MachineCodeEmitter.h"
21#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000022#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000024#include "llvm/CodeGen/MachineRelocation.h"
Nate Begeman37efe672006-04-22 18:53:45 +000025#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000026#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000027#include "llvm/Target/TargetJITInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
29#include "llvm/ADT/Statistic.h"
Reid Spencer52b0ba62004-09-11 04:31:03 +000030#include "llvm/System/Memory.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000031#include <algorithm>
Chris Lattnerca261802006-01-22 23:41:42 +000032#include <iostream>
33#include <list>
Chris Lattnerc19aade2003-12-08 08:06:28 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chris Lattnerbd199fb2002-12-24 00:01:05 +000036namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000037 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Chris Lattnere884dc22005-07-20 16:29:20 +000038 Statistic<> NumRelos("jit", "Number of relocations applied");
Chris Lattner4d326fa2003-12-20 01:46:27 +000039 JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000040}
Chris Lattnerbd199fb2002-12-24 00:01:05 +000041
Chris Lattner54266522004-11-20 23:57:07 +000042
43//===----------------------------------------------------------------------===//
44// JITMemoryManager code.
45//
46namespace {
Chris Lattner688506d2003-08-14 18:35:27 +000047 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
48 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
49 /// sections, one for function stubs, one for the functions themselves. We
50 /// have to do this because we may need to emit a function stub while in the
51 /// middle of emitting a function, and we don't know how large the function we
52 /// are emitting is. This never bothers to release the memory, because when
53 /// we are ready to destroy the JIT, the program exits.
54 class JITMemoryManager {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000055 std::list<sys::MemoryBlock> Blocks; // List of blocks allocated by the JIT
Chris Lattner688506d2003-08-14 18:35:27 +000056 unsigned char *FunctionBase; // Start of the function body area
Andrew Lenhartha00269b2005-07-29 23:40:16 +000057 unsigned char *GlobalBase; // Start of the Global area
58 unsigned char *ConstantBase; // Memory allocated for constant pools
59 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr, *CurGlobalPtr;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000060 unsigned char *GOTBase; //Target Specific reserved memory
Andrew Lenhartha00269b2005-07-29 23:40:16 +000061
62 // centralize memory block allocation
63 sys::MemoryBlock getNewMemoryBlock(unsigned size);
Chris Lattner688506d2003-08-14 18:35:27 +000064 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000065 JITMemoryManager(bool useGOT);
Reid Spencer4af3da62004-12-13 16:04:04 +000066 ~JITMemoryManager();
Misha Brukmanf976c852005-04-21 22:55:34 +000067
Chris Lattner688506d2003-08-14 18:35:27 +000068 inline unsigned char *allocateStub(unsigned StubSize);
Chris Lattner281a6012005-01-10 18:23:22 +000069 inline unsigned char *allocateConstant(unsigned ConstantSize,
70 unsigned Alignment);
Jeff Cohend29b6aa2005-07-30 18:33:25 +000071 inline unsigned char* allocateGlobal(unsigned Size,
Andrew Lenharth6a974612005-07-28 12:44:13 +000072 unsigned Alignment);
Chris Lattner688506d2003-08-14 18:35:27 +000073 inline unsigned char *startFunctionBody();
Chris Lattner281a6012005-01-10 18:23:22 +000074 inline void endFunctionBody(unsigned char *FunctionEnd);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000075 inline unsigned char* getGOTBase() const;
76
77 inline bool isManagingGOT() const;
Chris Lattner688506d2003-08-14 18:35:27 +000078 };
79}
80
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000081JITMemoryManager::JITMemoryManager(bool useGOT) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000082 // Allocate a 16M block of memory for functions
83 sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
84 // Allocate a 1M block of memory for Constants
85 sys::MemoryBlock ConstBlock = getNewMemoryBlock(1 << 20);
86 // Allocate a 1M Block of memory for Globals
87 sys::MemoryBlock GVBlock = getNewMemoryBlock(1 << 20);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000088
Andrew Lenhartha00269b2005-07-29 23:40:16 +000089 Blocks.push_front(FunBlock);
90 Blocks.push_front(ConstBlock);
91 Blocks.push_front(GVBlock);
Chris Lattner688506d2003-08-14 18:35:27 +000092
Andrew Lenhartha00269b2005-07-29 23:40:16 +000093 FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
94 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
95 GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
Chris Lattner281a6012005-01-10 18:23:22 +000096
Andrew Lenhartha00269b2005-07-29 23:40:16 +000097 // Allocate stubs backwards from the base, allocate functions forward
98 // from the base.
99 CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
100
101 CurConstantPtr = ConstantBase + ConstBlock.size();
102 CurGlobalPtr = GlobalBase + GVBlock.size();
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +0000103
104 //Allocate the GOT just like a global array
105 GOTBase = NULL;
106 if (useGOT)
107 GOTBase = allocateGlobal(sizeof(void*) * 8192, 8);
Chris Lattner688506d2003-08-14 18:35:27 +0000108}
109
Reid Spencer4af3da62004-12-13 16:04:04 +0000110JITMemoryManager::~JITMemoryManager() {
Chris Lattner21998772006-01-07 06:20:51 +0000111 for (std::list<sys::MemoryBlock>::iterator ib = Blocks.begin(),
112 ie = Blocks.end(); ib != ie; ++ib)
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000113 sys::Memory::ReleaseRWX(*ib);
114 Blocks.clear();
Reid Spencer4af3da62004-12-13 16:04:04 +0000115}
116
Chris Lattner688506d2003-08-14 18:35:27 +0000117unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
118 CurStubPtr -= StubSize;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000119 if (CurStubPtr < FunctionBase) {
120 //FIXME: allocate a new block
Chris Lattner688506d2003-08-14 18:35:27 +0000121 std::cerr << "JIT ran out of memory for function stubs!\n";
122 abort();
123 }
124 return CurStubPtr;
125}
126
Chris Lattner281a6012005-01-10 18:23:22 +0000127unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
128 unsigned Alignment) {
129 // Reserve space and align pointer.
130 CurConstantPtr -= ConstantSize;
131 CurConstantPtr =
132 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
133
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000134 if (CurConstantPtr < ConstantBase) {
135 //Either allocate another MB or 2xConstantSize
136 sys::MemoryBlock ConstBlock = getNewMemoryBlock(2 * ConstantSize);
137 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
138 CurConstantPtr = ConstantBase + ConstBlock.size();
139 return allocateConstant(ConstantSize, Alignment);
Chris Lattner281a6012005-01-10 18:23:22 +0000140 }
141 return CurConstantPtr;
142}
143
Andrew Lenharth6a974612005-07-28 12:44:13 +0000144unsigned char *JITMemoryManager::allocateGlobal(unsigned Size,
145 unsigned Alignment) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000146 // Reserve space and align pointer.
147 CurGlobalPtr -= Size;
148 CurGlobalPtr =
149 (unsigned char *)((intptr_t)CurGlobalPtr & ~((intptr_t)Alignment - 1));
Andrew Lenharth6a974612005-07-28 12:44:13 +0000150
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000151 if (CurGlobalPtr < GlobalBase) {
152 //Either allocate another MB or 2xSize
153 sys::MemoryBlock GVBlock = getNewMemoryBlock(2 * Size);
154 GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
155 CurGlobalPtr = GlobalBase + GVBlock.size();
156 return allocateGlobal(Size, Alignment);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000157 }
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000158 return CurGlobalPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000159}
160
Chris Lattner688506d2003-08-14 18:35:27 +0000161unsigned char *JITMemoryManager::startFunctionBody() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000162 // Round up to an even multiple of 8 bytes, this should eventually be target
Chris Lattner688506d2003-08-14 18:35:27 +0000163 // specific.
Chris Lattner5be478f2004-11-20 03:46:14 +0000164 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
Chris Lattner688506d2003-08-14 18:35:27 +0000165}
166
167void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
168 assert(FunctionEnd > CurFunctionPtr);
169 CurFunctionPtr = FunctionEnd;
170}
171
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000172unsigned char* JITMemoryManager::getGOTBase() const {
173 return GOTBase;
174}
175
176bool JITMemoryManager::isManagingGOT() const {
177 return GOTBase != NULL;
178}
179
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000180sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
181 const sys::MemoryBlock* BOld = 0;
182 if (Blocks.size())
183 BOld = &Blocks.front();
184 //never allocate less than 1 MB
185 sys::MemoryBlock B;
186 try {
187 B = sys::Memory::AllocateRWX(std::max(((unsigned)1 << 20), size), BOld);
188 } catch (std::string& err) {
189 std::cerr << "Allocation failed when allocating new memory in the JIT\n";
190 std::cerr << err << "\n";
191 abort();
192 }
193 Blocks.push_front(B);
194 return B;
195}
196
Chris Lattner54266522004-11-20 23:57:07 +0000197//===----------------------------------------------------------------------===//
198// JIT lazy compilation code.
199//
200namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000201 class JITResolverState {
202 private:
203 /// FunctionToStubMap - Keep track of the stub created for a particular
204 /// function so that we can reuse them if necessary.
205 std::map<Function*, void*> FunctionToStubMap;
206
207 /// StubToFunctionMap - Keep track of the function that each stub
208 /// corresponds to.
209 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000210
Reid Spenceree448632005-07-12 15:51:55 +0000211 public:
212 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
213 assert(locked.holds(TheJIT->lock));
214 return FunctionToStubMap;
215 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000216
Reid Spenceree448632005-07-12 15:51:55 +0000217 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
218 assert(locked.holds(TheJIT->lock));
219 return StubToFunctionMap;
220 }
221 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000222
Chris Lattner54266522004-11-20 23:57:07 +0000223 /// JITResolver - Keep track of, and resolve, call sites for functions that
224 /// have not yet been compiled.
225 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000226 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000227 MachineCodeEmitter &MCE;
228
Chris Lattner5e225582004-11-21 03:37:42 +0000229 /// LazyResolverFn - The target lazy resolver function that we actually
230 /// rewrite instructions to use.
231 TargetJITInfo::LazyResolverFn LazyResolverFn;
232
Reid Spenceree448632005-07-12 15:51:55 +0000233 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000234
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000235 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
236 /// external functions.
237 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000238
239 //map addresses to indexes in the GOT
240 std::map<void*, unsigned> revGOTMap;
241 unsigned nextGOTIndex;
242
Chris Lattner54266522004-11-20 23:57:07 +0000243 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000244 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000245 LazyResolverFn =
246 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
247 }
Chris Lattner54266522004-11-20 23:57:07 +0000248
249 /// getFunctionStub - This returns a pointer to a function stub, creating
250 /// one on demand as needed.
251 void *getFunctionStub(Function *F);
252
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000253 /// getExternalFunctionStub - Return a stub for the function at the
254 /// specified address, created lazily on demand.
255 void *getExternalFunctionStub(void *FnAddr);
256
Chris Lattner5e225582004-11-21 03:37:42 +0000257 /// AddCallbackAtLocation - If the target is capable of rewriting an
258 /// instruction without the use of a stub, record the location of the use so
259 /// we know which function is being used at the location.
260 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000261 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000262 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000263 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner5e225582004-11-21 03:37:42 +0000264 return (void*)LazyResolverFn;
265 }
266
Andrew Lenharth6a974612005-07-28 12:44:13 +0000267 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
268 /// and address. This function only manages slots, it does not manage the
269 /// contents of the slots or the memory associated with the GOT.
270 unsigned getGOTIndexForAddr(void* addr);
271
Chris Lattner54266522004-11-20 23:57:07 +0000272 /// JITCompilerFn - This function is called to resolve a stub to a compiled
273 /// address. If the LLVM Function corresponding to the stub has not yet
274 /// been compiled, this function compiles it first.
275 static void *JITCompilerFn(void *Stub);
276 };
277}
278
279/// getJITResolver - This function returns the one instance of the JIT resolver.
280///
281static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
282 static JITResolver TheJITResolver(*MCE);
283 return TheJITResolver;
284}
285
286/// getFunctionStub - This returns a pointer to a function stub, creating
287/// one on demand as needed.
288void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000289 MutexGuard locked(TheJIT->lock);
290
Chris Lattner54266522004-11-20 23:57:07 +0000291 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000292 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000293 if (Stub) return Stub;
294
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000295 // Call the lazy resolver function unless we already KNOW it is an external
296 // function, in which case we just skip the lazy resolution step.
297 void *Actual = (void*)LazyResolverFn;
Chris Lattner69435702005-02-20 18:43:35 +0000298 if (F->isExternal() && F->hasExternalLinkage())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000299 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000300
Chris Lattner54266522004-11-20 23:57:07 +0000301 // Otherwise, codegen a new stub. For now, the stub will call the lazy
302 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000303 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
304
Chris Lattner69435702005-02-20 18:43:35 +0000305 if (Actual != (void*)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000306 // If we are getting the stub for an external function, we really want the
307 // address of the stub in the GlobalAddressMap for the JIT, not the address
308 // of the external function.
309 TheJIT->updateGlobalMapping(F, Stub);
310 }
Chris Lattner54266522004-11-20 23:57:07 +0000311
Chris Lattnercb479412004-11-21 03:44:32 +0000312 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Chris Lattner6f717202004-11-22 21:48:33 +0000313 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000314
Chris Lattner54266522004-11-20 23:57:07 +0000315 // Finally, keep track of the stub-to-Function mapping so that the
316 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000317 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000318 return Stub;
319}
320
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000321/// getExternalFunctionStub - Return a stub for the function at the
322/// specified address, created lazily on demand.
323void *JITResolver::getExternalFunctionStub(void *FnAddr) {
324 // If we already have a stub for this function, recycle it.
325 void *&Stub = ExternalFnToStubMap[FnAddr];
326 if (Stub) return Stub;
327
328 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
329 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
330 << "] for external function at '" << FnAddr << "'\n");
331 return Stub;
332}
333
Andrew Lenharth6a974612005-07-28 12:44:13 +0000334unsigned JITResolver::getGOTIndexForAddr(void* addr) {
335 unsigned idx = revGOTMap[addr];
336 if (!idx) {
337 idx = ++nextGOTIndex;
338 revGOTMap[addr] = idx;
339 DEBUG(std::cerr << "Adding GOT entry " << idx
340 << " for addr " << addr << "\n");
341 // ((void**)MemMgr.getGOTBase())[idx] = addr;
342 }
343 return idx;
344}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000345
Chris Lattner54266522004-11-20 23:57:07 +0000346/// JITCompilerFn - This function is called when a lazy compilation stub has
347/// been entered. It looks up which function this stub corresponds to, compiles
348/// it if necessary, then returns the resultant function pointer.
349void *JITResolver::JITCompilerFn(void *Stub) {
350 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000351
Reid Spenceree448632005-07-12 15:51:55 +0000352 MutexGuard locked(TheJIT->lock);
353
Chris Lattner54266522004-11-20 23:57:07 +0000354 // The address given to us for the stub may not be exactly right, it might be
355 // a little bit after the stub. As such, use upper_bound to find it.
356 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000357 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000358 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
359 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000360 Function *F = (--I)->second;
361
Reid Spenceree448632005-07-12 15:51:55 +0000362 // We might like to remove the stub from the StubToFunction map.
363 // We can't do that! Multiple threads could be stuck, waiting to acquire the
364 // lock above. As soon as the 1st function finishes compiling the function,
Chris Lattner21998772006-01-07 06:20:51 +0000365 // the next one will be released, and needs to be able to find the function it
366 // needs to call.
Reid Spenceree448632005-07-12 15:51:55 +0000367 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000368
Chris Lattnercb479412004-11-21 03:44:32 +0000369 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
Chris Lattner54266522004-11-20 23:57:07 +0000370 << "' In stub ptr = " << Stub << " actual ptr = "
371 << I->first << "\n");
372
373 void *Result = TheJIT->getPointerToFunction(F);
374
375 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000376 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000377
378 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000379
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000380 // What we will do is set the compiled function address to map to the
381 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000382 // if they see it still using the stub address.
383 // Note: this is done so the Resolver doesn't have to manage GOT memory
384 // Do this without allocating map space if the target isn't using a GOT
385 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
386 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
387
Chris Lattner54266522004-11-20 23:57:07 +0000388 return Result;
389}
Chris Lattner688506d2003-08-14 18:35:27 +0000390
391
Chris Lattnere518b712004-12-05 07:19:16 +0000392// getPointerToFunctionOrStub - If the specified function has been
393// code-gen'd, return a pointer to the function. If not, compile it, or use
394// a stub to implement lazy compilation if available.
395//
396void *JIT::getPointerToFunctionOrStub(Function *F) {
397 // If we have already code generated the function, just return the address.
398 if (void *Addr = getPointerToGlobalIfAvailable(F))
399 return Addr;
400
401 // Get a stub if the target supports it
402 return getJITResolver(MCE).getFunctionStub(F);
403}
404
405
406
Chris Lattner54266522004-11-20 23:57:07 +0000407//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000408// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000409//
Chris Lattner688506d2003-08-14 18:35:27 +0000410namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000411 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
412 /// used to output functions to memory for execution.
413 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000414 JITMemoryManager MemMgr;
415
Chris Lattner6125fdd2003-05-09 03:30:07 +0000416 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000417 // save BufferBegin/BufferEnd/CurBufferPtr here.
418 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000419
Chris Lattner5be478f2004-11-20 03:46:14 +0000420 /// Relocations - These are the relocations that the function needs, as
421 /// emitted.
422 std::vector<MachineRelocation> Relocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000423
Chris Lattner239862c2006-02-09 04:49:59 +0000424 /// ConstantPool - The constant pool for the current function.
425 ///
426 MachineConstantPool *ConstantPool;
427
428 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
429 ///
430 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000431
432 /// ConstantPool - The constant pool for the current function.
433 ///
434 MachineJumpTableInfo *JumpTable;
435
436 /// JumpTableBase - A pointer to the first entry in the jump table.
437 ///
438 void *JumpTableBase;
439public:
Chris Lattner239862c2006-02-09 04:49:59 +0000440 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000441 TheJIT = &jit;
442 DEBUG(std::cerr <<
443 (MemMgr.isManagingGOT() ? "JIT is managing GOT\n"
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000444 : "JIT is not managing GOT\n"));
445 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000446
447 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000448 virtual bool finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000449 virtual void emitConstantPool(MachineConstantPool *MCP);
Nate Begeman37efe672006-04-22 18:53:45 +0000450 virtual void initJumpTableInfo(MachineJumpTableInfo *MJTI);
451 virtual void emitJumpTableInfo(MachineJumpTableInfo *MJTI,
452 std::map<MachineBasicBlock*,uint64_t> &MBBM);
Chris Lattner54266522004-11-20 23:57:07 +0000453 virtual void startFunctionStub(unsigned StubSize);
454 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000455
Chris Lattner5be478f2004-11-20 03:46:14 +0000456 virtual void addRelocation(const MachineRelocation &MR) {
457 Relocations.push_back(MR);
458 }
459
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000460 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
Nate Begeman37efe672006-04-22 18:53:45 +0000461 virtual uint64_t getJumpTableEntryAddress(unsigned Entry);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000462 virtual unsigned char* allocateGlobal(unsigned size, unsigned alignment);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000463
Chris Lattner54266522004-11-20 23:57:07 +0000464 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000465 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000466 };
467}
468
Chris Lattner4d326fa2003-12-20 01:46:27 +0000469MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
Chris Lattner166f2262004-11-22 22:00:25 +0000470 return new JITEmitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000471}
472
Chris Lattner166f2262004-11-22 22:00:25 +0000473void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
474 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000475 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
476 /// FIXME: If we straightened things out, this could actually emit the
477 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000478 return TheJIT->getOrEmitGlobalVariable(GV);
479 }
480
481 // If we have already compiled the function, return a pointer to its body.
482 Function *F = cast<Function>(V);
483 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
484 if (ResultPtr) return ResultPtr;
485
Chris Lattner532343b2004-11-30 17:41:49 +0000486 if (F->hasExternalLinkage() && F->isExternal()) {
Chris Lattner54266522004-11-20 23:57:07 +0000487 // If this is an external function pointer, we can force the JIT to
488 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000489 if (DoesntNeedStub)
490 return TheJIT->getPointerToFunction(F);
491
492 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000493 }
494
Chris Lattner5e225582004-11-21 03:37:42 +0000495 // Okay, the function has not been compiled yet, if the target callback
496 // mechanism is capable of rewriting the instruction directly, prefer to do
497 // that instead of emitting a stub.
498 if (DoesntNeedStub)
499 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
500
Chris Lattner54266522004-11-20 23:57:07 +0000501 // Otherwise, we have to emit a lazy resolving stub.
502 return getJITResolver(this).getFunctionStub(F);
503}
504
Chris Lattner166f2262004-11-22 22:00:25 +0000505void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000506 BufferBegin = CurBufferPtr = MemMgr.startFunctionBody();
507 TheJIT->updateGlobalMapping(F.getFunction(), BufferBegin);
508
509 /// FIXME: implement out of space handling correctly!
510 BufferEnd = (unsigned char*)(intptr_t)~0ULL;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000511}
512
Chris Lattner43b429b2006-05-02 18:27:26 +0000513bool JITEmitter::finishFunction(MachineFunction &F) {
514 MemMgr.endFunctionBody(CurBufferPtr);
515 NumBytes += getCurrentPCOffset();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000516
Chris Lattner5be478f2004-11-20 03:46:14 +0000517 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000518 NumRelos += Relocations.size();
519
Chris Lattner5be478f2004-11-20 03:46:14 +0000520 // Resolve the relocations to concrete pointers.
521 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
522 MachineRelocation &MR = Relocations[i];
523 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000524 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000525 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000526
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000527 // If the target REALLY wants a stub for this function, emit it now.
528 if (!MR.doesntNeedFunctionStub())
529 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Jeff Cohen00b168892005-07-27 06:12:32 +0000530 } else if (MR.isGlobalValue())
Chris Lattner5e225582004-11-21 03:37:42 +0000531 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000532 BufferBegin+MR.getMachineCodeOffset(),
Chris Lattner5e225582004-11-21 03:37:42 +0000533 MR.doesntNeedFunctionStub());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000534 else //ConstantPoolIndex
Jeff Cohen00b168892005-07-27 06:12:32 +0000535 ResultPtr =
Chris Lattnerd6bbac52005-07-25 23:42:58 +0000536 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Jeff Cohen00b168892005-07-27 06:12:32 +0000537
Chris Lattner5be478f2004-11-20 03:46:14 +0000538 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000539
Andrew Lenharth6a974612005-07-28 12:44:13 +0000540 // if we are managing the GOT and the relocation wants an index,
541 // give it one
542 if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
543 MR.isGOTRelative()) {
544 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
545 MR.setGOTIndex(idx);
546 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
547 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
Chris Lattner21998772006-01-07 06:20:51 +0000548 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
549 << "\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000550 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
551 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000552 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000553 }
554
Chris Lattner43b429b2006-05-02 18:27:26 +0000555 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000556 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000557 }
558
Andrew Lenharth6a974612005-07-28 12:44:13 +0000559 //Update the GOT entry for F to point to the new code.
560 if(MemMgr.isManagingGOT()) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000561 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
562 if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
563 DEBUG(std::cerr << "GOT was out of date for " << (void*)BufferBegin
Andrew Lenharth6a974612005-07-28 12:44:13 +0000564 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
Chris Lattner43b429b2006-05-02 18:27:26 +0000565 ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000566 }
567 }
568
Chris Lattner43b429b2006-05-02 18:27:26 +0000569 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)BufferBegin
Misha Brukman1d440852003-06-06 06:52:35 +0000570 << "] Function: " << F.getFunction()->getName()
Chris Lattner43b429b2006-05-02 18:27:26 +0000571 << ": " << getCurrentPCOffset() << " bytes of text, "
Chris Lattner5be478f2004-11-20 03:46:14 +0000572 << Relocations.size() << " relocations\n");
573 Relocations.clear();
Chris Lattner43b429b2006-05-02 18:27:26 +0000574 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000575}
576
Chris Lattner166f2262004-11-22 22:00:25 +0000577void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000578 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000579 if (Constants.empty()) return;
580
Chris Lattner3029f922006-02-09 04:46:04 +0000581 unsigned Size = Constants.back().Offset;
582 Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000583
Chris Lattner239862c2006-02-09 04:49:59 +0000584 ConstantPoolBase = MemMgr.allocateConstant(Size,
Chris Lattner3029f922006-02-09 04:46:04 +0000585 1 << MCP->getConstantPoolAlignment());
Chris Lattner239862c2006-02-09 04:49:59 +0000586 ConstantPool = MCP;
587
588 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000589 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000590 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Chris Lattner3029f922006-02-09 04:46:04 +0000591 TheJIT->InitializeMemory(Constants[i].Val, CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000592 }
593}
594
Nate Begeman37efe672006-04-22 18:53:45 +0000595void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
596 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
597 if (JT.empty()) return;
598
599 unsigned Size = 0;
600 unsigned EntrySize = MJTI->getEntrySize();
601 for (unsigned i = 0, e = JT.size(); i != e; ++i)
602 Size += JT[i].MBBs.size() * EntrySize;
603
604 // Just allocate space for all the jump tables now. We will fix up the actual
605 // MBB entries in the tables after we emit the code for each block, since then
606 // we will know the final locations of the MBBs in memory.
607 JumpTable = MJTI;
608 JumpTableBase = MemMgr.allocateConstant(Size, MJTI->getAlignment());
609}
610
611void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI,
612 std::map<MachineBasicBlock*,uint64_t> &MBBM){
613 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
614 if (JT.empty()) return;
615
616 unsigned Offset = 0;
617 unsigned EntrySize = MJTI->getEntrySize();
618
619 // For each jump table, map each target in the jump table to the address of
620 // an emitted MachineBasicBlock.
621 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
622 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
623 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
624 uint64_t addr = MBBM[MBBs[mi]];
625 GenericValue addrgv;
626 const Type *Ty;
627 if (EntrySize == 4) {
628 addrgv.UIntVal = addr;
629 Ty = Type::UIntTy;
630 } else if (EntrySize == 8) {
631 addrgv.ULongVal = addr;
632 Ty = Type::ULongTy;
633 } else {
634 assert(0 && "Unhandled jump table entry size!");
635 abort();
636 }
637 // Store the address of the basic block for this jump table slot in the
638 // memory we allocated for the jump table in 'initJumpTableInfo'
639 void *ptr = (void *)((char *)JumpTableBase + Offset);
640 TheJIT->StoreValueToMemory(addrgv, (GenericValue *)ptr, Ty);
641 Offset += EntrySize;
642 }
643 }
644}
645
Chris Lattner166f2262004-11-22 22:00:25 +0000646void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000647 SavedBufferBegin = BufferBegin;
648 SavedBufferEnd = BufferEnd;
649 SavedCurBufferPtr = CurBufferPtr;
650
651 BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize);
652 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000653}
654
Chris Lattner166f2262004-11-22 22:00:25 +0000655void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000656 NumBytes += getCurrentPCOffset();
657 std::swap(SavedBufferBegin, BufferBegin);
658 BufferEnd = SavedBufferEnd;
659 CurBufferPtr = SavedCurBufferPtr;
660 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000661}
662
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000663// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
664// in the constant pool that was last emitted with the 'emitConstantPool'
665// method.
666//
Chris Lattner166f2262004-11-22 22:00:25 +0000667uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
Chris Lattner239862c2006-02-09 04:49:59 +0000668 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000669 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000670 return (intptr_t)ConstantPoolBase +
671 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000672}
673
Nate Begeman37efe672006-04-22 18:53:45 +0000674// getJumpTableEntryAddress - Return the address of the JumpTable with index
675// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
676//
677uint64_t JITEmitter::getJumpTableEntryAddress(unsigned Index) {
678 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
679 assert(Index < JT.size() && "Invalid jump table index!");
680
681 unsigned Offset = 0;
682 unsigned EntrySize = JumpTable->getEntrySize();
683
684 for (unsigned i = 0; i < Index; ++i)
685 Offset += JT[i].MBBs.size() * EntrySize;
686
Nate Begemanc34b2272006-04-25 17:46:32 +0000687 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000688}
689
Andrew Lenharth6a974612005-07-28 12:44:13 +0000690unsigned char* JITEmitter::allocateGlobal(unsigned size, unsigned alignment)
691{
692 return MemMgr.allocateGlobal(size, alignment);
693}
694
Misha Brukmand69c1e62003-07-28 19:09:06 +0000695// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000696// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000697// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
698// need to resolve function(s) that are being mis-codegenerated, so we need to
699// resolve their addresses at runtime, and this is the way to do it.
700extern "C" {
701 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000702 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000703 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000704 return TheJIT->getPointerToFunction(F);
705 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000706 }
707}