blob: b67dfe1953b550a8b878176f964d48e409062722 [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 Lattnerbba1b6d2003-06-01 23:24:36 +0000416 // CurBlock - The start of the current block of memory. CurByte - The
417 // current byte being emitted to.
Chris Lattner6125fdd2003-05-09 03:30:07 +0000418 unsigned char *CurBlock, *CurByte;
419
420 // When outputting a function stub in the context of some other function, we
421 // save CurBlock and CurByte here.
422 unsigned char *SavedCurBlock, *SavedCurByte;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000423
Chris Lattner5be478f2004-11-20 03:46:14 +0000424 /// Relocations - These are the relocations that the function needs, as
425 /// emitted.
426 std::vector<MachineRelocation> Relocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000427
Chris Lattner239862c2006-02-09 04:49:59 +0000428 /// ConstantPool - The constant pool for the current function.
429 ///
430 MachineConstantPool *ConstantPool;
431
432 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
433 ///
434 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000435
436 /// ConstantPool - The constant pool for the current function.
437 ///
438 MachineJumpTableInfo *JumpTable;
439
440 /// JumpTableBase - A pointer to the first entry in the jump table.
441 ///
442 void *JumpTableBase;
443public:
Chris Lattner239862c2006-02-09 04:49:59 +0000444 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000445 TheJIT = &jit;
446 DEBUG(std::cerr <<
447 (MemMgr.isManagingGOT() ? "JIT is managing GOT\n"
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000448 : "JIT is not managing GOT\n"));
449 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000450
451 virtual void startFunction(MachineFunction &F);
452 virtual void finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000453 virtual void emitConstantPool(MachineConstantPool *MCP);
Nate Begeman37efe672006-04-22 18:53:45 +0000454 virtual void initJumpTableInfo(MachineJumpTableInfo *MJTI);
455 virtual void emitJumpTableInfo(MachineJumpTableInfo *MJTI,
456 std::map<MachineBasicBlock*,uint64_t> &MBBM);
Chris Lattner54266522004-11-20 23:57:07 +0000457 virtual void startFunctionStub(unsigned StubSize);
458 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000459 virtual void emitByte(unsigned char B);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000460 virtual void emitWord(unsigned W);
Brian Gaekeaea1b582004-04-23 17:11:14 +0000461 virtual void emitWordAt(unsigned W, unsigned *Ptr);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000462
Chris Lattner5be478f2004-11-20 03:46:14 +0000463 virtual void addRelocation(const MachineRelocation &MR) {
464 Relocations.push_back(MR);
465 }
466
467 virtual uint64_t getCurrentPCValue();
468 virtual uint64_t getCurrentPCOffset();
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000469 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
Nate Begeman37efe672006-04-22 18:53:45 +0000470 virtual uint64_t getJumpTableEntryAddress(unsigned Entry);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000471 virtual unsigned char* allocateGlobal(unsigned size, unsigned alignment);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000472
Chris Lattner54266522004-11-20 23:57:07 +0000473 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000474 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000475 };
476}
477
Chris Lattner4d326fa2003-12-20 01:46:27 +0000478MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
Chris Lattner166f2262004-11-22 22:00:25 +0000479 return new JITEmitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000480}
481
Chris Lattner166f2262004-11-22 22:00:25 +0000482void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
483 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000484 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
485 /// FIXME: If we straightened things out, this could actually emit the
486 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000487 return TheJIT->getOrEmitGlobalVariable(GV);
488 }
489
490 // If we have already compiled the function, return a pointer to its body.
491 Function *F = cast<Function>(V);
492 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
493 if (ResultPtr) return ResultPtr;
494
Chris Lattner532343b2004-11-30 17:41:49 +0000495 if (F->hasExternalLinkage() && F->isExternal()) {
Chris Lattner54266522004-11-20 23:57:07 +0000496 // If this is an external function pointer, we can force the JIT to
497 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000498 if (DoesntNeedStub)
499 return TheJIT->getPointerToFunction(F);
500
501 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000502 }
503
Chris Lattner5e225582004-11-21 03:37:42 +0000504 // Okay, the function has not been compiled yet, if the target callback
505 // mechanism is capable of rewriting the instruction directly, prefer to do
506 // that instead of emitting a stub.
507 if (DoesntNeedStub)
508 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
509
Chris Lattner54266522004-11-20 23:57:07 +0000510 // Otherwise, we have to emit a lazy resolving stub.
511 return getJITResolver(this).getFunctionStub(F);
512}
513
Chris Lattner166f2262004-11-22 22:00:25 +0000514void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000515 CurByte = CurBlock = MemMgr.startFunctionBody();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000516 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000517}
518
Chris Lattner166f2262004-11-22 22:00:25 +0000519void JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000520 MemMgr.endFunctionBody(CurByte);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000521 NumBytes += CurByte-CurBlock;
522
Chris Lattner5be478f2004-11-20 03:46:14 +0000523 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000524 NumRelos += Relocations.size();
525
Chris Lattner5be478f2004-11-20 03:46:14 +0000526 // Resolve the relocations to concrete pointers.
527 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
528 MachineRelocation &MR = Relocations[i];
529 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000530 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000531 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000532
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000533 // If the target REALLY wants a stub for this function, emit it now.
534 if (!MR.doesntNeedFunctionStub())
535 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Jeff Cohen00b168892005-07-27 06:12:32 +0000536 } else if (MR.isGlobalValue())
Chris Lattner5e225582004-11-21 03:37:42 +0000537 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
538 CurBlock+MR.getMachineCodeOffset(),
539 MR.doesntNeedFunctionStub());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000540 else //ConstantPoolIndex
Jeff Cohen00b168892005-07-27 06:12:32 +0000541 ResultPtr =
Chris Lattnerd6bbac52005-07-25 23:42:58 +0000542 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Jeff Cohen00b168892005-07-27 06:12:32 +0000543
Chris Lattner5be478f2004-11-20 03:46:14 +0000544 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000545
Andrew Lenharth6a974612005-07-28 12:44:13 +0000546 // if we are managing the GOT and the relocation wants an index,
547 // give it one
548 if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
549 MR.isGOTRelative()) {
550 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
551 MR.setGOTIndex(idx);
552 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
553 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
Chris Lattner21998772006-01-07 06:20:51 +0000554 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
555 << "\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000556 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
557 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000558 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000559 }
560
561 TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000562 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000563 }
564
Andrew Lenharth6a974612005-07-28 12:44:13 +0000565 //Update the GOT entry for F to point to the new code.
566 if(MemMgr.isManagingGOT()) {
567 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)CurBlock);
568 if (((void**)MemMgr.getGOTBase())[idx] != (void*)CurBlock) {
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000569 DEBUG(std::cerr << "GOT was out of date for " << (void*)CurBlock
Andrew Lenharth6a974612005-07-28 12:44:13 +0000570 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
571 ((void**)MemMgr.getGOTBase())[idx] = (void*)CurBlock;
572 }
573 }
574
Chris Lattnercb479412004-11-21 03:44:32 +0000575 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
Misha Brukman1d440852003-06-06 06:52:35 +0000576 << "] Function: " << F.getFunction()->getName()
Chris Lattner5be478f2004-11-20 03:46:14 +0000577 << ": " << CurByte-CurBlock << " bytes of text, "
578 << Relocations.size() << " relocations\n");
579 Relocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000580}
581
Chris Lattner166f2262004-11-22 22:00:25 +0000582void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000583 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000584 if (Constants.empty()) return;
585
Chris Lattner3029f922006-02-09 04:46:04 +0000586 unsigned Size = Constants.back().Offset;
587 Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000588
Chris Lattner239862c2006-02-09 04:49:59 +0000589 ConstantPoolBase = MemMgr.allocateConstant(Size,
Chris Lattner3029f922006-02-09 04:46:04 +0000590 1 << MCP->getConstantPoolAlignment());
Chris Lattner239862c2006-02-09 04:49:59 +0000591 ConstantPool = MCP;
592
593 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000594 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000595 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Chris Lattner3029f922006-02-09 04:46:04 +0000596 TheJIT->InitializeMemory(Constants[i].Val, CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000597 }
598}
599
Nate Begeman37efe672006-04-22 18:53:45 +0000600void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
601 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
602 if (JT.empty()) return;
603
604 unsigned Size = 0;
605 unsigned EntrySize = MJTI->getEntrySize();
606 for (unsigned i = 0, e = JT.size(); i != e; ++i)
607 Size += JT[i].MBBs.size() * EntrySize;
608
609 // Just allocate space for all the jump tables now. We will fix up the actual
610 // MBB entries in the tables after we emit the code for each block, since then
611 // we will know the final locations of the MBBs in memory.
612 JumpTable = MJTI;
613 JumpTableBase = MemMgr.allocateConstant(Size, MJTI->getAlignment());
614}
615
616void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI,
617 std::map<MachineBasicBlock*,uint64_t> &MBBM){
618 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
619 if (JT.empty()) return;
620
621 unsigned Offset = 0;
622 unsigned EntrySize = MJTI->getEntrySize();
623
624 // For each jump table, map each target in the jump table to the address of
625 // an emitted MachineBasicBlock.
626 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
627 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
628 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
629 uint64_t addr = MBBM[MBBs[mi]];
630 GenericValue addrgv;
631 const Type *Ty;
632 if (EntrySize == 4) {
633 addrgv.UIntVal = addr;
634 Ty = Type::UIntTy;
635 } else if (EntrySize == 8) {
636 addrgv.ULongVal = addr;
637 Ty = Type::ULongTy;
638 } else {
639 assert(0 && "Unhandled jump table entry size!");
640 abort();
641 }
642 // Store the address of the basic block for this jump table slot in the
643 // memory we allocated for the jump table in 'initJumpTableInfo'
644 void *ptr = (void *)((char *)JumpTableBase + Offset);
645 TheJIT->StoreValueToMemory(addrgv, (GenericValue *)ptr, Ty);
646 Offset += EntrySize;
647 }
648 }
649}
650
Chris Lattner166f2262004-11-22 22:00:25 +0000651void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner6125fdd2003-05-09 03:30:07 +0000652 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
Chris Lattner688506d2003-08-14 18:35:27 +0000653 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000654}
655
Chris Lattner166f2262004-11-22 22:00:25 +0000656void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner6125fdd2003-05-09 03:30:07 +0000657 NumBytes += CurByte-CurBlock;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000658 std::swap(CurBlock, SavedCurBlock);
659 CurByte = SavedCurByte;
660 return SavedCurBlock;
661}
662
Chris Lattner166f2262004-11-22 22:00:25 +0000663void JITEmitter::emitByte(unsigned char B) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000664 *CurByte++ = B; // Write the byte to memory
665}
666
Chris Lattner166f2262004-11-22 22:00:25 +0000667void JITEmitter::emitWord(unsigned W) {
Chris Lattner688506d2003-08-14 18:35:27 +0000668 // This won't work if the endianness of the host and target don't agree! (For
669 // a JIT this can't happen though. :)
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000670 *(unsigned*)CurByte = W;
671 CurByte += sizeof(unsigned);
672}
673
Chris Lattner166f2262004-11-22 22:00:25 +0000674void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
Brian Gaekeaea1b582004-04-23 17:11:14 +0000675 *Ptr = W;
676}
677
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000678// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
679// in the constant pool that was last emitted with the 'emitConstantPool'
680// method.
681//
Chris Lattner166f2262004-11-22 22:00:25 +0000682uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
Chris Lattner239862c2006-02-09 04:49:59 +0000683 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000684 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000685 return (intptr_t)ConstantPoolBase +
686 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000687}
688
Nate Begeman37efe672006-04-22 18:53:45 +0000689// getJumpTableEntryAddress - Return the address of the JumpTable with index
690// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
691//
692uint64_t JITEmitter::getJumpTableEntryAddress(unsigned Index) {
693 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
694 assert(Index < JT.size() && "Invalid jump table index!");
695
696 unsigned Offset = 0;
697 unsigned EntrySize = JumpTable->getEntrySize();
698
699 for (unsigned i = 0; i < Index; ++i)
700 Offset += JT[i].MBBs.size() * EntrySize;
701
702 return (uint64_t)((char *)JumpTableBase + Offset);
703}
704
Andrew Lenharth6a974612005-07-28 12:44:13 +0000705unsigned char* JITEmitter::allocateGlobal(unsigned size, unsigned alignment)
706{
707 return MemMgr.allocateGlobal(size, alignment);
708}
709
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000710// getCurrentPCValue - This returns the address that the next emitted byte
711// will be output to.
712//
Chris Lattner166f2262004-11-22 22:00:25 +0000713uint64_t JITEmitter::getCurrentPCValue() {
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000714 return (intptr_t)CurByte;
715}
716
Chris Lattner166f2262004-11-22 22:00:25 +0000717uint64_t JITEmitter::getCurrentPCOffset() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000718 return (intptr_t)CurByte-(intptr_t)CurBlock;
719}
720
Misha Brukmand69c1e62003-07-28 19:09:06 +0000721// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000722// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000723// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
724// need to resolve function(s) that are being mis-codegenerated, so we need to
725// resolve their addresses at runtime, and this is the way to do it.
726extern "C" {
727 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000728 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000729 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000730 return TheJIT->getPointerToFunction(F);
731 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000732 }
733}