blob: f4abd28a6c470f0450a80c025058769c16013df1 [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
Chris Lattnera726c7f2006-05-02 21:44:14 +000057 unsigned char *GlobalBase; // Start of the Global area
Andrew Lenhartha00269b2005-07-29 23:40:16 +000058 unsigned char *ConstantBase; // Memory allocated for constant pools
59 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr, *CurGlobalPtr;
Chris Lattnera726c7f2006-05-02 21:44:14 +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);
Chris Lattnera726c7f2006-05-02 21:44:14 +000075
76 unsigned char *getGOTBase() const {
77 return GOTBase;
78 }
79 bool isManagingGOT() const {
80 return GOTBase != NULL;
81 }
Chris Lattner688506d2003-08-14 18:35:27 +000082 };
83}
84
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000085JITMemoryManager::JITMemoryManager(bool useGOT) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000086 // Allocate a 16M block of memory for functions
87 sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
88 // Allocate a 1M block of memory for Constants
89 sys::MemoryBlock ConstBlock = getNewMemoryBlock(1 << 20);
90 // Allocate a 1M Block of memory for Globals
91 sys::MemoryBlock GVBlock = getNewMemoryBlock(1 << 20);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000092
Andrew Lenhartha00269b2005-07-29 23:40:16 +000093 Blocks.push_front(FunBlock);
94 Blocks.push_front(ConstBlock);
95 Blocks.push_front(GVBlock);
Chris Lattner688506d2003-08-14 18:35:27 +000096
Andrew Lenhartha00269b2005-07-29 23:40:16 +000097 FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
98 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
99 GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
Chris Lattner281a6012005-01-10 18:23:22 +0000100
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000101 // Allocate stubs backwards from the base, allocate functions forward
102 // from the base.
103 CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
104
105 CurConstantPtr = ConstantBase + ConstBlock.size();
106 CurGlobalPtr = GlobalBase + GVBlock.size();
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +0000107
108 //Allocate the GOT just like a global array
109 GOTBase = NULL;
110 if (useGOT)
111 GOTBase = allocateGlobal(sizeof(void*) * 8192, 8);
Chris Lattner688506d2003-08-14 18:35:27 +0000112}
113
Reid Spencer4af3da62004-12-13 16:04:04 +0000114JITMemoryManager::~JITMemoryManager() {
Chris Lattner21998772006-01-07 06:20:51 +0000115 for (std::list<sys::MemoryBlock>::iterator ib = Blocks.begin(),
116 ie = Blocks.end(); ib != ie; ++ib)
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000117 sys::Memory::ReleaseRWX(*ib);
118 Blocks.clear();
Reid Spencer4af3da62004-12-13 16:04:04 +0000119}
120
Chris Lattner688506d2003-08-14 18:35:27 +0000121unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
122 CurStubPtr -= StubSize;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000123 if (CurStubPtr < FunctionBase) {
Chris Lattnera726c7f2006-05-02 21:44:14 +0000124 // FIXME: allocate a new block
Chris Lattner688506d2003-08-14 18:35:27 +0000125 std::cerr << "JIT ran out of memory for function stubs!\n";
126 abort();
127 }
128 return CurStubPtr;
129}
130
Chris Lattner281a6012005-01-10 18:23:22 +0000131unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
132 unsigned Alignment) {
133 // Reserve space and align pointer.
134 CurConstantPtr -= ConstantSize;
135 CurConstantPtr =
136 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
137
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000138 if (CurConstantPtr < ConstantBase) {
139 //Either allocate another MB or 2xConstantSize
140 sys::MemoryBlock ConstBlock = getNewMemoryBlock(2 * ConstantSize);
141 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
142 CurConstantPtr = ConstantBase + ConstBlock.size();
143 return allocateConstant(ConstantSize, Alignment);
Chris Lattner281a6012005-01-10 18:23:22 +0000144 }
145 return CurConstantPtr;
146}
147
Andrew Lenharth6a974612005-07-28 12:44:13 +0000148unsigned char *JITMemoryManager::allocateGlobal(unsigned Size,
149 unsigned Alignment) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000150 // Reserve space and align pointer.
151 CurGlobalPtr -= Size;
152 CurGlobalPtr =
153 (unsigned char *)((intptr_t)CurGlobalPtr & ~((intptr_t)Alignment - 1));
Andrew Lenharth6a974612005-07-28 12:44:13 +0000154
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000155 if (CurGlobalPtr < GlobalBase) {
156 //Either allocate another MB or 2xSize
157 sys::MemoryBlock GVBlock = getNewMemoryBlock(2 * Size);
158 GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
159 CurGlobalPtr = GlobalBase + GVBlock.size();
160 return allocateGlobal(Size, Alignment);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000161 }
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000162 return CurGlobalPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000163}
164
Chris Lattner688506d2003-08-14 18:35:27 +0000165unsigned char *JITMemoryManager::startFunctionBody() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000166 // Round up to an even multiple of 8 bytes, this should eventually be target
Chris Lattner688506d2003-08-14 18:35:27 +0000167 // specific.
Chris Lattner5be478f2004-11-20 03:46:14 +0000168 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
Chris Lattner688506d2003-08-14 18:35:27 +0000169}
170
171void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
172 assert(FunctionEnd > CurFunctionPtr);
173 CurFunctionPtr = FunctionEnd;
174}
175
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000176sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
177 const sys::MemoryBlock* BOld = 0;
178 if (Blocks.size())
179 BOld = &Blocks.front();
180 //never allocate less than 1 MB
181 sys::MemoryBlock B;
182 try {
183 B = sys::Memory::AllocateRWX(std::max(((unsigned)1 << 20), size), BOld);
184 } catch (std::string& err) {
185 std::cerr << "Allocation failed when allocating new memory in the JIT\n";
186 std::cerr << err << "\n";
187 abort();
188 }
189 Blocks.push_front(B);
190 return B;
191}
192
Chris Lattner54266522004-11-20 23:57:07 +0000193//===----------------------------------------------------------------------===//
194// JIT lazy compilation code.
195//
196namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000197 class JITResolverState {
198 private:
199 /// FunctionToStubMap - Keep track of the stub created for a particular
200 /// function so that we can reuse them if necessary.
201 std::map<Function*, void*> FunctionToStubMap;
202
203 /// StubToFunctionMap - Keep track of the function that each stub
204 /// corresponds to.
205 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000206
Reid Spenceree448632005-07-12 15:51:55 +0000207 public:
208 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
209 assert(locked.holds(TheJIT->lock));
210 return FunctionToStubMap;
211 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000212
Reid Spenceree448632005-07-12 15:51:55 +0000213 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
214 assert(locked.holds(TheJIT->lock));
215 return StubToFunctionMap;
216 }
217 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000218
Chris Lattner54266522004-11-20 23:57:07 +0000219 /// JITResolver - Keep track of, and resolve, call sites for functions that
220 /// have not yet been compiled.
221 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000222 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000223 MachineCodeEmitter &MCE;
224
Chris Lattner5e225582004-11-21 03:37:42 +0000225 /// LazyResolverFn - The target lazy resolver function that we actually
226 /// rewrite instructions to use.
227 TargetJITInfo::LazyResolverFn LazyResolverFn;
228
Reid Spenceree448632005-07-12 15:51:55 +0000229 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000230
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000231 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
232 /// external functions.
233 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000234
235 //map addresses to indexes in the GOT
236 std::map<void*, unsigned> revGOTMap;
237 unsigned nextGOTIndex;
238
Chris Lattner54266522004-11-20 23:57:07 +0000239 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000240 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000241 LazyResolverFn =
242 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
243 }
Chris Lattner54266522004-11-20 23:57:07 +0000244
245 /// getFunctionStub - This returns a pointer to a function stub, creating
246 /// one on demand as needed.
247 void *getFunctionStub(Function *F);
248
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000249 /// getExternalFunctionStub - Return a stub for the function at the
250 /// specified address, created lazily on demand.
251 void *getExternalFunctionStub(void *FnAddr);
252
Chris Lattner5e225582004-11-21 03:37:42 +0000253 /// AddCallbackAtLocation - If the target is capable of rewriting an
254 /// instruction without the use of a stub, record the location of the use so
255 /// we know which function is being used at the location.
256 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000257 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000258 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000259 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner5e225582004-11-21 03:37:42 +0000260 return (void*)LazyResolverFn;
261 }
262
Andrew Lenharth6a974612005-07-28 12:44:13 +0000263 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
264 /// and address. This function only manages slots, it does not manage the
265 /// contents of the slots or the memory associated with the GOT.
266 unsigned getGOTIndexForAddr(void* addr);
267
Chris Lattner54266522004-11-20 23:57:07 +0000268 /// JITCompilerFn - This function is called to resolve a stub to a compiled
269 /// address. If the LLVM Function corresponding to the stub has not yet
270 /// been compiled, this function compiles it first.
271 static void *JITCompilerFn(void *Stub);
272 };
273}
274
275/// getJITResolver - This function returns the one instance of the JIT resolver.
276///
277static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
278 static JITResolver TheJITResolver(*MCE);
279 return TheJITResolver;
280}
281
282/// getFunctionStub - This returns a pointer to a function stub, creating
283/// one on demand as needed.
284void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000285 MutexGuard locked(TheJIT->lock);
286
Chris Lattner54266522004-11-20 23:57:07 +0000287 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000288 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000289 if (Stub) return Stub;
290
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000291 // Call the lazy resolver function unless we already KNOW it is an external
292 // function, in which case we just skip the lazy resolution step.
293 void *Actual = (void*)LazyResolverFn;
Chris Lattner69435702005-02-20 18:43:35 +0000294 if (F->isExternal() && F->hasExternalLinkage())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000295 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000296
Chris Lattner54266522004-11-20 23:57:07 +0000297 // Otherwise, codegen a new stub. For now, the stub will call the lazy
298 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000299 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
300
Chris Lattner69435702005-02-20 18:43:35 +0000301 if (Actual != (void*)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000302 // If we are getting the stub for an external function, we really want the
303 // address of the stub in the GlobalAddressMap for the JIT, not the address
304 // of the external function.
305 TheJIT->updateGlobalMapping(F, Stub);
306 }
Chris Lattner54266522004-11-20 23:57:07 +0000307
Chris Lattnercb479412004-11-21 03:44:32 +0000308 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Chris Lattner6f717202004-11-22 21:48:33 +0000309 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000310
Chris Lattner54266522004-11-20 23:57:07 +0000311 // Finally, keep track of the stub-to-Function mapping so that the
312 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000313 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000314 return Stub;
315}
316
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000317/// getExternalFunctionStub - Return a stub for the function at the
318/// specified address, created lazily on demand.
319void *JITResolver::getExternalFunctionStub(void *FnAddr) {
320 // If we already have a stub for this function, recycle it.
321 void *&Stub = ExternalFnToStubMap[FnAddr];
322 if (Stub) return Stub;
323
324 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
325 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
326 << "] for external function at '" << FnAddr << "'\n");
327 return Stub;
328}
329
Andrew Lenharth6a974612005-07-28 12:44:13 +0000330unsigned JITResolver::getGOTIndexForAddr(void* addr) {
331 unsigned idx = revGOTMap[addr];
332 if (!idx) {
333 idx = ++nextGOTIndex;
334 revGOTMap[addr] = idx;
335 DEBUG(std::cerr << "Adding GOT entry " << idx
336 << " for addr " << addr << "\n");
337 // ((void**)MemMgr.getGOTBase())[idx] = addr;
338 }
339 return idx;
340}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000341
Chris Lattner54266522004-11-20 23:57:07 +0000342/// JITCompilerFn - This function is called when a lazy compilation stub has
343/// been entered. It looks up which function this stub corresponds to, compiles
344/// it if necessary, then returns the resultant function pointer.
345void *JITResolver::JITCompilerFn(void *Stub) {
346 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000347
Reid Spenceree448632005-07-12 15:51:55 +0000348 MutexGuard locked(TheJIT->lock);
349
Chris Lattner54266522004-11-20 23:57:07 +0000350 // The address given to us for the stub may not be exactly right, it might be
351 // a little bit after the stub. As such, use upper_bound to find it.
352 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000353 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000354 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
355 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000356 Function *F = (--I)->second;
357
Reid Spenceree448632005-07-12 15:51:55 +0000358 // We might like to remove the stub from the StubToFunction map.
359 // We can't do that! Multiple threads could be stuck, waiting to acquire the
360 // lock above. As soon as the 1st function finishes compiling the function,
Chris Lattner21998772006-01-07 06:20:51 +0000361 // the next one will be released, and needs to be able to find the function it
362 // needs to call.
Reid Spenceree448632005-07-12 15:51:55 +0000363 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000364
Chris Lattnercb479412004-11-21 03:44:32 +0000365 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
Chris Lattner54266522004-11-20 23:57:07 +0000366 << "' In stub ptr = " << Stub << " actual ptr = "
367 << I->first << "\n");
368
369 void *Result = TheJIT->getPointerToFunction(F);
370
371 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000372 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000373
374 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000375
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000376 // What we will do is set the compiled function address to map to the
377 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000378 // if they see it still using the stub address.
379 // Note: this is done so the Resolver doesn't have to manage GOT memory
380 // Do this without allocating map space if the target isn't using a GOT
381 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
382 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
383
Chris Lattner54266522004-11-20 23:57:07 +0000384 return Result;
385}
Chris Lattner688506d2003-08-14 18:35:27 +0000386
387
Chris Lattnere518b712004-12-05 07:19:16 +0000388// getPointerToFunctionOrStub - If the specified function has been
389// code-gen'd, return a pointer to the function. If not, compile it, or use
390// a stub to implement lazy compilation if available.
391//
392void *JIT::getPointerToFunctionOrStub(Function *F) {
393 // If we have already code generated the function, just return the address.
394 if (void *Addr = getPointerToGlobalIfAvailable(F))
395 return Addr;
396
397 // Get a stub if the target supports it
398 return getJITResolver(MCE).getFunctionStub(F);
399}
400
401
402
Chris Lattner54266522004-11-20 23:57:07 +0000403//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000404// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000405//
Chris Lattner688506d2003-08-14 18:35:27 +0000406namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000407 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
408 /// used to output functions to memory for execution.
409 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000410 JITMemoryManager MemMgr;
411
Chris Lattner6125fdd2003-05-09 03:30:07 +0000412 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000413 // save BufferBegin/BufferEnd/CurBufferPtr here.
414 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000415
Chris Lattner5be478f2004-11-20 03:46:14 +0000416 /// Relocations - These are the relocations that the function needs, as
417 /// emitted.
418 std::vector<MachineRelocation> Relocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000419
Chris Lattner239862c2006-02-09 04:49:59 +0000420 /// ConstantPool - The constant pool for the current function.
421 ///
422 MachineConstantPool *ConstantPool;
423
424 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
425 ///
426 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000427
428 /// ConstantPool - The constant pool for the current function.
429 ///
430 MachineJumpTableInfo *JumpTable;
431
432 /// JumpTableBase - A pointer to the first entry in the jump table.
433 ///
434 void *JumpTableBase;
435public:
Chris Lattner239862c2006-02-09 04:49:59 +0000436 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000437 TheJIT = &jit;
Chris Lattnera726c7f2006-05-02 21:44:14 +0000438 DEBUG(if (MemMgr.isManagingGOT()) std::cerr << "JIT is managing a GOT\n");
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000439 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000440
441 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000442 virtual bool finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000443 virtual void emitConstantPool(MachineConstantPool *MCP);
Nate Begeman37efe672006-04-22 18:53:45 +0000444 virtual void initJumpTableInfo(MachineJumpTableInfo *MJTI);
445 virtual void emitJumpTableInfo(MachineJumpTableInfo *MJTI,
446 std::map<MachineBasicBlock*,uint64_t> &MBBM);
Chris Lattner54266522004-11-20 23:57:07 +0000447 virtual void startFunctionStub(unsigned StubSize);
448 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000449
Chris Lattner5be478f2004-11-20 03:46:14 +0000450 virtual void addRelocation(const MachineRelocation &MR) {
451 Relocations.push_back(MR);
452 }
453
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000454 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
Nate Begeman37efe672006-04-22 18:53:45 +0000455 virtual uint64_t getJumpTableEntryAddress(unsigned Entry);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000456 virtual unsigned char* allocateGlobal(unsigned size, unsigned alignment);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000457
Chris Lattner54266522004-11-20 23:57:07 +0000458 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000459 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000460 };
461}
462
Chris Lattner4d326fa2003-12-20 01:46:27 +0000463MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
Chris Lattner166f2262004-11-22 22:00:25 +0000464 return new JITEmitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000465}
466
Chris Lattner166f2262004-11-22 22:00:25 +0000467void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
468 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000469 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
470 /// FIXME: If we straightened things out, this could actually emit the
471 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000472 return TheJIT->getOrEmitGlobalVariable(GV);
473 }
474
475 // If we have already compiled the function, return a pointer to its body.
476 Function *F = cast<Function>(V);
477 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
478 if (ResultPtr) return ResultPtr;
479
Chris Lattner532343b2004-11-30 17:41:49 +0000480 if (F->hasExternalLinkage() && F->isExternal()) {
Chris Lattner54266522004-11-20 23:57:07 +0000481 // If this is an external function pointer, we can force the JIT to
482 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000483 if (DoesntNeedStub)
484 return TheJIT->getPointerToFunction(F);
485
486 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000487 }
488
Chris Lattner5e225582004-11-21 03:37:42 +0000489 // Okay, the function has not been compiled yet, if the target callback
490 // mechanism is capable of rewriting the instruction directly, prefer to do
491 // that instead of emitting a stub.
492 if (DoesntNeedStub)
493 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
494
Chris Lattner54266522004-11-20 23:57:07 +0000495 // Otherwise, we have to emit a lazy resolving stub.
496 return getJITResolver(this).getFunctionStub(F);
497}
498
Chris Lattner166f2262004-11-22 22:00:25 +0000499void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000500 BufferBegin = CurBufferPtr = MemMgr.startFunctionBody();
501 TheJIT->updateGlobalMapping(F.getFunction(), BufferBegin);
502
503 /// FIXME: implement out of space handling correctly!
504 BufferEnd = (unsigned char*)(intptr_t)~0ULL;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000505}
506
Chris Lattner43b429b2006-05-02 18:27:26 +0000507bool JITEmitter::finishFunction(MachineFunction &F) {
508 MemMgr.endFunctionBody(CurBufferPtr);
509 NumBytes += getCurrentPCOffset();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000510
Chris Lattner5be478f2004-11-20 03:46:14 +0000511 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000512 NumRelos += Relocations.size();
513
Chris Lattner5be478f2004-11-20 03:46:14 +0000514 // Resolve the relocations to concrete pointers.
515 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
516 MachineRelocation &MR = Relocations[i];
517 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000518 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000519 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000520
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000521 // If the target REALLY wants a stub for this function, emit it now.
522 if (!MR.doesntNeedFunctionStub())
523 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Jeff Cohen00b168892005-07-27 06:12:32 +0000524 } else if (MR.isGlobalValue())
Chris Lattner5e225582004-11-21 03:37:42 +0000525 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000526 BufferBegin+MR.getMachineCodeOffset(),
Chris Lattner5e225582004-11-21 03:37:42 +0000527 MR.doesntNeedFunctionStub());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000528 else //ConstantPoolIndex
Jeff Cohen00b168892005-07-27 06:12:32 +0000529 ResultPtr =
Chris Lattnerd6bbac52005-07-25 23:42:58 +0000530 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Jeff Cohen00b168892005-07-27 06:12:32 +0000531
Chris Lattner5be478f2004-11-20 03:46:14 +0000532 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000533
Andrew Lenharth6a974612005-07-28 12:44:13 +0000534 // if we are managing the GOT and the relocation wants an index,
535 // give it one
536 if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
537 MR.isGOTRelative()) {
538 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
539 MR.setGOTIndex(idx);
540 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
541 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
Chris Lattner21998772006-01-07 06:20:51 +0000542 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
543 << "\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000544 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
545 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000546 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000547 }
548
Chris Lattner43b429b2006-05-02 18:27:26 +0000549 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000550 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000551 }
552
Andrew Lenharth6a974612005-07-28 12:44:13 +0000553 //Update the GOT entry for F to point to the new code.
554 if(MemMgr.isManagingGOT()) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000555 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
556 if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
557 DEBUG(std::cerr << "GOT was out of date for " << (void*)BufferBegin
Andrew Lenharth6a974612005-07-28 12:44:13 +0000558 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
Chris Lattner43b429b2006-05-02 18:27:26 +0000559 ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000560 }
561 }
562
Chris Lattner43b429b2006-05-02 18:27:26 +0000563 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)BufferBegin
Misha Brukman1d440852003-06-06 06:52:35 +0000564 << "] Function: " << F.getFunction()->getName()
Chris Lattner43b429b2006-05-02 18:27:26 +0000565 << ": " << getCurrentPCOffset() << " bytes of text, "
Chris Lattner5be478f2004-11-20 03:46:14 +0000566 << Relocations.size() << " relocations\n");
567 Relocations.clear();
Chris Lattner43b429b2006-05-02 18:27:26 +0000568 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000569}
570
Chris Lattner166f2262004-11-22 22:00:25 +0000571void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000572 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000573 if (Constants.empty()) return;
574
Chris Lattner3029f922006-02-09 04:46:04 +0000575 unsigned Size = Constants.back().Offset;
576 Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000577
Chris Lattner239862c2006-02-09 04:49:59 +0000578 ConstantPoolBase = MemMgr.allocateConstant(Size,
Chris Lattner3029f922006-02-09 04:46:04 +0000579 1 << MCP->getConstantPoolAlignment());
Chris Lattner239862c2006-02-09 04:49:59 +0000580 ConstantPool = MCP;
581
582 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000583 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000584 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Chris Lattner3029f922006-02-09 04:46:04 +0000585 TheJIT->InitializeMemory(Constants[i].Val, CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000586 }
587}
588
Nate Begeman37efe672006-04-22 18:53:45 +0000589void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
590 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
591 if (JT.empty()) return;
592
593 unsigned Size = 0;
594 unsigned EntrySize = MJTI->getEntrySize();
595 for (unsigned i = 0, e = JT.size(); i != e; ++i)
596 Size += JT[i].MBBs.size() * EntrySize;
597
598 // Just allocate space for all the jump tables now. We will fix up the actual
599 // MBB entries in the tables after we emit the code for each block, since then
600 // we will know the final locations of the MBBs in memory.
601 JumpTable = MJTI;
602 JumpTableBase = MemMgr.allocateConstant(Size, MJTI->getAlignment());
603}
604
605void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI,
606 std::map<MachineBasicBlock*,uint64_t> &MBBM){
607 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
608 if (JT.empty()) return;
609
610 unsigned Offset = 0;
611 unsigned EntrySize = MJTI->getEntrySize();
612
613 // For each jump table, map each target in the jump table to the address of
614 // an emitted MachineBasicBlock.
615 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
616 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
617 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
618 uint64_t addr = MBBM[MBBs[mi]];
619 GenericValue addrgv;
620 const Type *Ty;
621 if (EntrySize == 4) {
622 addrgv.UIntVal = addr;
623 Ty = Type::UIntTy;
624 } else if (EntrySize == 8) {
625 addrgv.ULongVal = addr;
626 Ty = Type::ULongTy;
627 } else {
628 assert(0 && "Unhandled jump table entry size!");
629 abort();
630 }
631 // Store the address of the basic block for this jump table slot in the
632 // memory we allocated for the jump table in 'initJumpTableInfo'
633 void *ptr = (void *)((char *)JumpTableBase + Offset);
634 TheJIT->StoreValueToMemory(addrgv, (GenericValue *)ptr, Ty);
635 Offset += EntrySize;
636 }
637 }
638}
639
Chris Lattner166f2262004-11-22 22:00:25 +0000640void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000641 SavedBufferBegin = BufferBegin;
642 SavedBufferEnd = BufferEnd;
643 SavedCurBufferPtr = CurBufferPtr;
644
645 BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize);
646 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000647}
648
Chris Lattner166f2262004-11-22 22:00:25 +0000649void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000650 NumBytes += getCurrentPCOffset();
651 std::swap(SavedBufferBegin, BufferBegin);
652 BufferEnd = SavedBufferEnd;
653 CurBufferPtr = SavedCurBufferPtr;
654 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000655}
656
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000657// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
658// in the constant pool that was last emitted with the 'emitConstantPool'
659// method.
660//
Chris Lattner166f2262004-11-22 22:00:25 +0000661uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
Chris Lattner239862c2006-02-09 04:49:59 +0000662 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000663 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000664 return (intptr_t)ConstantPoolBase +
665 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000666}
667
Nate Begeman37efe672006-04-22 18:53:45 +0000668// getJumpTableEntryAddress - Return the address of the JumpTable with index
669// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
670//
671uint64_t JITEmitter::getJumpTableEntryAddress(unsigned Index) {
672 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
673 assert(Index < JT.size() && "Invalid jump table index!");
674
675 unsigned Offset = 0;
676 unsigned EntrySize = JumpTable->getEntrySize();
677
678 for (unsigned i = 0; i < Index; ++i)
679 Offset += JT[i].MBBs.size() * EntrySize;
680
Nate Begemanc34b2272006-04-25 17:46:32 +0000681 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000682}
683
Andrew Lenharth6a974612005-07-28 12:44:13 +0000684unsigned char* JITEmitter::allocateGlobal(unsigned size, unsigned alignment)
685{
686 return MemMgr.allocateGlobal(size, alignment);
687}
688
Misha Brukmand69c1e62003-07-28 19:09:06 +0000689// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000690// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000691// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
692// need to resolve function(s) that are being mis-codegenerated, so we need to
693// resolve their addresses at runtime, and this is the way to do it.
694extern "C" {
695 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000696 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000697 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000698 return TheJIT->getPointerToFunction(F);
699 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000700 }
701}