blob: 3f41222b742673edceb3e4852f6fa6ccee778c12 [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"
Chris Lattner5be478f2004-11-20 03:46:14 +000023#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000024#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000025#include "llvm/Target/TargetJITInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/Support/Debug.h"
27#include "llvm/ADT/Statistic.h"
Reid Spencer52b0ba62004-09-11 04:31:03 +000028#include "llvm/System/Memory.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000029#include <algorithm>
Chris Lattnerca261802006-01-22 23:41:42 +000030#include <iostream>
31#include <list>
Chris Lattnerc19aade2003-12-08 08:06:28 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattnerbd199fb2002-12-24 00:01:05 +000034namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000035 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Chris Lattnere884dc22005-07-20 16:29:20 +000036 Statistic<> NumRelos("jit", "Number of relocations applied");
Chris Lattner4d326fa2003-12-20 01:46:27 +000037 JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000038}
Chris Lattnerbd199fb2002-12-24 00:01:05 +000039
Chris Lattner54266522004-11-20 23:57:07 +000040
41//===----------------------------------------------------------------------===//
42// JITMemoryManager code.
43//
44namespace {
Chris Lattner688506d2003-08-14 18:35:27 +000045 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
46 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
47 /// sections, one for function stubs, one for the functions themselves. We
48 /// have to do this because we may need to emit a function stub while in the
49 /// middle of emitting a function, and we don't know how large the function we
50 /// are emitting is. This never bothers to release the memory, because when
51 /// we are ready to destroy the JIT, the program exits.
52 class JITMemoryManager {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000053 std::list<sys::MemoryBlock> Blocks; // List of blocks allocated by the JIT
Chris Lattner688506d2003-08-14 18:35:27 +000054 unsigned char *FunctionBase; // Start of the function body area
Andrew Lenhartha00269b2005-07-29 23:40:16 +000055 unsigned char *GlobalBase; // Start of the Global area
56 unsigned char *ConstantBase; // Memory allocated for constant pools
57 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr, *CurGlobalPtr;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000058 unsigned char *GOTBase; //Target Specific reserved memory
Andrew Lenhartha00269b2005-07-29 23:40:16 +000059
60 // centralize memory block allocation
61 sys::MemoryBlock getNewMemoryBlock(unsigned size);
Chris Lattner688506d2003-08-14 18:35:27 +000062 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000063 JITMemoryManager(bool useGOT);
Reid Spencer4af3da62004-12-13 16:04:04 +000064 ~JITMemoryManager();
Misha Brukmanf976c852005-04-21 22:55:34 +000065
Chris Lattner688506d2003-08-14 18:35:27 +000066 inline unsigned char *allocateStub(unsigned StubSize);
Chris Lattner281a6012005-01-10 18:23:22 +000067 inline unsigned char *allocateConstant(unsigned ConstantSize,
68 unsigned Alignment);
Jeff Cohend29b6aa2005-07-30 18:33:25 +000069 inline unsigned char* allocateGlobal(unsigned Size,
Andrew Lenharth6a974612005-07-28 12:44:13 +000070 unsigned Alignment);
Chris Lattner688506d2003-08-14 18:35:27 +000071 inline unsigned char *startFunctionBody();
Chris Lattner281a6012005-01-10 18:23:22 +000072 inline void endFunctionBody(unsigned char *FunctionEnd);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000073 inline unsigned char* getGOTBase() const;
74
75 inline bool isManagingGOT() const;
Chris Lattner688506d2003-08-14 18:35:27 +000076 };
77}
78
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000079JITMemoryManager::JITMemoryManager(bool useGOT) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000080 // Allocate a 16M block of memory for functions
81 sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
82 // Allocate a 1M block of memory for Constants
83 sys::MemoryBlock ConstBlock = getNewMemoryBlock(1 << 20);
84 // Allocate a 1M Block of memory for Globals
85 sys::MemoryBlock GVBlock = getNewMemoryBlock(1 << 20);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000086
Andrew Lenhartha00269b2005-07-29 23:40:16 +000087 Blocks.push_front(FunBlock);
88 Blocks.push_front(ConstBlock);
89 Blocks.push_front(GVBlock);
Chris Lattner688506d2003-08-14 18:35:27 +000090
Andrew Lenhartha00269b2005-07-29 23:40:16 +000091 FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
92 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
93 GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
Chris Lattner281a6012005-01-10 18:23:22 +000094
Andrew Lenhartha00269b2005-07-29 23:40:16 +000095 // Allocate stubs backwards from the base, allocate functions forward
96 // from the base.
97 CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
98
99 CurConstantPtr = ConstantBase + ConstBlock.size();
100 CurGlobalPtr = GlobalBase + GVBlock.size();
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +0000101
102 //Allocate the GOT just like a global array
103 GOTBase = NULL;
104 if (useGOT)
105 GOTBase = allocateGlobal(sizeof(void*) * 8192, 8);
Chris Lattner688506d2003-08-14 18:35:27 +0000106}
107
Reid Spencer4af3da62004-12-13 16:04:04 +0000108JITMemoryManager::~JITMemoryManager() {
Chris Lattner21998772006-01-07 06:20:51 +0000109 for (std::list<sys::MemoryBlock>::iterator ib = Blocks.begin(),
110 ie = Blocks.end(); ib != ie; ++ib)
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000111 sys::Memory::ReleaseRWX(*ib);
112 Blocks.clear();
Reid Spencer4af3da62004-12-13 16:04:04 +0000113}
114
Chris Lattner688506d2003-08-14 18:35:27 +0000115unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
116 CurStubPtr -= StubSize;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000117 if (CurStubPtr < FunctionBase) {
118 //FIXME: allocate a new block
Chris Lattner688506d2003-08-14 18:35:27 +0000119 std::cerr << "JIT ran out of memory for function stubs!\n";
120 abort();
121 }
122 return CurStubPtr;
123}
124
Chris Lattner281a6012005-01-10 18:23:22 +0000125unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
126 unsigned Alignment) {
127 // Reserve space and align pointer.
128 CurConstantPtr -= ConstantSize;
129 CurConstantPtr =
130 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
131
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000132 if (CurConstantPtr < ConstantBase) {
133 //Either allocate another MB or 2xConstantSize
134 sys::MemoryBlock ConstBlock = getNewMemoryBlock(2 * ConstantSize);
135 ConstantBase = reinterpret_cast<unsigned char*>(ConstBlock.base());
136 CurConstantPtr = ConstantBase + ConstBlock.size();
137 return allocateConstant(ConstantSize, Alignment);
Chris Lattner281a6012005-01-10 18:23:22 +0000138 }
139 return CurConstantPtr;
140}
141
Andrew Lenharth6a974612005-07-28 12:44:13 +0000142unsigned char *JITMemoryManager::allocateGlobal(unsigned Size,
143 unsigned Alignment) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000144 // Reserve space and align pointer.
145 CurGlobalPtr -= Size;
146 CurGlobalPtr =
147 (unsigned char *)((intptr_t)CurGlobalPtr & ~((intptr_t)Alignment - 1));
Andrew Lenharth6a974612005-07-28 12:44:13 +0000148
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000149 if (CurGlobalPtr < GlobalBase) {
150 //Either allocate another MB or 2xSize
151 sys::MemoryBlock GVBlock = getNewMemoryBlock(2 * Size);
152 GlobalBase = reinterpret_cast<unsigned char*>(GVBlock.base());
153 CurGlobalPtr = GlobalBase + GVBlock.size();
154 return allocateGlobal(Size, Alignment);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000155 }
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000156 return CurGlobalPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000157}
158
Chris Lattner688506d2003-08-14 18:35:27 +0000159unsigned char *JITMemoryManager::startFunctionBody() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000160 // Round up to an even multiple of 8 bytes, this should eventually be target
Chris Lattner688506d2003-08-14 18:35:27 +0000161 // specific.
Chris Lattner5be478f2004-11-20 03:46:14 +0000162 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
Chris Lattner688506d2003-08-14 18:35:27 +0000163}
164
165void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
166 assert(FunctionEnd > CurFunctionPtr);
167 CurFunctionPtr = FunctionEnd;
168}
169
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000170unsigned char* JITMemoryManager::getGOTBase() const {
171 return GOTBase;
172}
173
174bool JITMemoryManager::isManagingGOT() const {
175 return GOTBase != NULL;
176}
177
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000178sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
179 const sys::MemoryBlock* BOld = 0;
180 if (Blocks.size())
181 BOld = &Blocks.front();
182 //never allocate less than 1 MB
183 sys::MemoryBlock B;
184 try {
185 B = sys::Memory::AllocateRWX(std::max(((unsigned)1 << 20), size), BOld);
186 } catch (std::string& err) {
187 std::cerr << "Allocation failed when allocating new memory in the JIT\n";
188 std::cerr << err << "\n";
189 abort();
190 }
191 Blocks.push_front(B);
192 return B;
193}
194
Chris Lattner54266522004-11-20 23:57:07 +0000195//===----------------------------------------------------------------------===//
196// JIT lazy compilation code.
197//
198namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000199 class JITResolverState {
200 private:
201 /// FunctionToStubMap - Keep track of the stub created for a particular
202 /// function so that we can reuse them if necessary.
203 std::map<Function*, void*> FunctionToStubMap;
204
205 /// StubToFunctionMap - Keep track of the function that each stub
206 /// corresponds to.
207 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000208
Reid Spenceree448632005-07-12 15:51:55 +0000209 public:
210 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
211 assert(locked.holds(TheJIT->lock));
212 return FunctionToStubMap;
213 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000214
Reid Spenceree448632005-07-12 15:51:55 +0000215 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
216 assert(locked.holds(TheJIT->lock));
217 return StubToFunctionMap;
218 }
219 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000220
Chris Lattner54266522004-11-20 23:57:07 +0000221 /// JITResolver - Keep track of, and resolve, call sites for functions that
222 /// have not yet been compiled.
223 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000224 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000225 MachineCodeEmitter &MCE;
226
Chris Lattner5e225582004-11-21 03:37:42 +0000227 /// LazyResolverFn - The target lazy resolver function that we actually
228 /// rewrite instructions to use.
229 TargetJITInfo::LazyResolverFn LazyResolverFn;
230
Reid Spenceree448632005-07-12 15:51:55 +0000231 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000232
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000233 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
234 /// external functions.
235 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000236
237 //map addresses to indexes in the GOT
238 std::map<void*, unsigned> revGOTMap;
239 unsigned nextGOTIndex;
240
Chris Lattner54266522004-11-20 23:57:07 +0000241 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000242 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000243 LazyResolverFn =
244 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
245 }
Chris Lattner54266522004-11-20 23:57:07 +0000246
247 /// getFunctionStub - This returns a pointer to a function stub, creating
248 /// one on demand as needed.
249 void *getFunctionStub(Function *F);
250
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000251 /// getExternalFunctionStub - Return a stub for the function at the
252 /// specified address, created lazily on demand.
253 void *getExternalFunctionStub(void *FnAddr);
254
Chris Lattner5e225582004-11-21 03:37:42 +0000255 /// AddCallbackAtLocation - If the target is capable of rewriting an
256 /// instruction without the use of a stub, record the location of the use so
257 /// we know which function is being used at the location.
258 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000259 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000260 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000261 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner5e225582004-11-21 03:37:42 +0000262 return (void*)LazyResolverFn;
263 }
264
Andrew Lenharth6a974612005-07-28 12:44:13 +0000265 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
266 /// and address. This function only manages slots, it does not manage the
267 /// contents of the slots or the memory associated with the GOT.
268 unsigned getGOTIndexForAddr(void* addr);
269
Chris Lattner54266522004-11-20 23:57:07 +0000270 /// JITCompilerFn - This function is called to resolve a stub to a compiled
271 /// address. If the LLVM Function corresponding to the stub has not yet
272 /// been compiled, this function compiles it first.
273 static void *JITCompilerFn(void *Stub);
274 };
275}
276
277/// getJITResolver - This function returns the one instance of the JIT resolver.
278///
279static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
280 static JITResolver TheJITResolver(*MCE);
281 return TheJITResolver;
282}
283
284/// getFunctionStub - This returns a pointer to a function stub, creating
285/// one on demand as needed.
286void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000287 MutexGuard locked(TheJIT->lock);
288
Chris Lattner54266522004-11-20 23:57:07 +0000289 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000290 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000291 if (Stub) return Stub;
292
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000293 // Call the lazy resolver function unless we already KNOW it is an external
294 // function, in which case we just skip the lazy resolution step.
295 void *Actual = (void*)LazyResolverFn;
Chris Lattner69435702005-02-20 18:43:35 +0000296 if (F->isExternal() && F->hasExternalLinkage())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000297 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000298
Chris Lattner54266522004-11-20 23:57:07 +0000299 // Otherwise, codegen a new stub. For now, the stub will call the lazy
300 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000301 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
302
Chris Lattner69435702005-02-20 18:43:35 +0000303 if (Actual != (void*)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000304 // If we are getting the stub for an external function, we really want the
305 // address of the stub in the GlobalAddressMap for the JIT, not the address
306 // of the external function.
307 TheJIT->updateGlobalMapping(F, Stub);
308 }
Chris Lattner54266522004-11-20 23:57:07 +0000309
Chris Lattnercb479412004-11-21 03:44:32 +0000310 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Chris Lattner6f717202004-11-22 21:48:33 +0000311 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000312
Chris Lattner54266522004-11-20 23:57:07 +0000313 // Finally, keep track of the stub-to-Function mapping so that the
314 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000315 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000316 return Stub;
317}
318
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000319/// getExternalFunctionStub - Return a stub for the function at the
320/// specified address, created lazily on demand.
321void *JITResolver::getExternalFunctionStub(void *FnAddr) {
322 // If we already have a stub for this function, recycle it.
323 void *&Stub = ExternalFnToStubMap[FnAddr];
324 if (Stub) return Stub;
325
326 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
327 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
328 << "] for external function at '" << FnAddr << "'\n");
329 return Stub;
330}
331
Andrew Lenharth6a974612005-07-28 12:44:13 +0000332unsigned JITResolver::getGOTIndexForAddr(void* addr) {
333 unsigned idx = revGOTMap[addr];
334 if (!idx) {
335 idx = ++nextGOTIndex;
336 revGOTMap[addr] = idx;
337 DEBUG(std::cerr << "Adding GOT entry " << idx
338 << " for addr " << addr << "\n");
339 // ((void**)MemMgr.getGOTBase())[idx] = addr;
340 }
341 return idx;
342}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000343
Chris Lattner54266522004-11-20 23:57:07 +0000344/// JITCompilerFn - This function is called when a lazy compilation stub has
345/// been entered. It looks up which function this stub corresponds to, compiles
346/// it if necessary, then returns the resultant function pointer.
347void *JITResolver::JITCompilerFn(void *Stub) {
348 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000349
Reid Spenceree448632005-07-12 15:51:55 +0000350 MutexGuard locked(TheJIT->lock);
351
Chris Lattner54266522004-11-20 23:57:07 +0000352 // The address given to us for the stub may not be exactly right, it might be
353 // a little bit after the stub. As such, use upper_bound to find it.
354 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000355 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000356 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
357 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000358 Function *F = (--I)->second;
359
Reid Spenceree448632005-07-12 15:51:55 +0000360 // We might like to remove the stub from the StubToFunction map.
361 // We can't do that! Multiple threads could be stuck, waiting to acquire the
362 // lock above. As soon as the 1st function finishes compiling the function,
Chris Lattner21998772006-01-07 06:20:51 +0000363 // the next one will be released, and needs to be able to find the function it
364 // needs to call.
Reid Spenceree448632005-07-12 15:51:55 +0000365 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000366
Chris Lattnercb479412004-11-21 03:44:32 +0000367 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
Chris Lattner54266522004-11-20 23:57:07 +0000368 << "' In stub ptr = " << Stub << " actual ptr = "
369 << I->first << "\n");
370
371 void *Result = TheJIT->getPointerToFunction(F);
372
373 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000374 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000375
376 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000377
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000378 // What we will do is set the compiled function address to map to the
379 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000380 // if they see it still using the stub address.
381 // Note: this is done so the Resolver doesn't have to manage GOT memory
382 // Do this without allocating map space if the target isn't using a GOT
383 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
384 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
385
Chris Lattner54266522004-11-20 23:57:07 +0000386 return Result;
387}
Chris Lattner688506d2003-08-14 18:35:27 +0000388
389
Chris Lattnere518b712004-12-05 07:19:16 +0000390// getPointerToFunctionOrStub - If the specified function has been
391// code-gen'd, return a pointer to the function. If not, compile it, or use
392// a stub to implement lazy compilation if available.
393//
394void *JIT::getPointerToFunctionOrStub(Function *F) {
395 // If we have already code generated the function, just return the address.
396 if (void *Addr = getPointerToGlobalIfAvailable(F))
397 return Addr;
398
399 // Get a stub if the target supports it
400 return getJITResolver(MCE).getFunctionStub(F);
401}
402
403
404
Chris Lattner54266522004-11-20 23:57:07 +0000405//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000406// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000407//
Chris Lattner688506d2003-08-14 18:35:27 +0000408namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000409 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
410 /// used to output functions to memory for execution.
411 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000412 JITMemoryManager MemMgr;
413
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000414 // CurBlock - The start of the current block of memory. CurByte - The
415 // current byte being emitted to.
Chris Lattner6125fdd2003-05-09 03:30:07 +0000416 unsigned char *CurBlock, *CurByte;
417
418 // When outputting a function stub in the context of some other function, we
419 // save CurBlock and CurByte here.
420 unsigned char *SavedCurBlock, *SavedCurByte;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000421
422 // ConstantPoolAddresses - Contains the location for each entry in the
423 // constant pool.
Chris Lattner1cc08382003-01-13 01:00:12 +0000424 std::vector<void*> ConstantPoolAddresses;
Chris Lattner5be478f2004-11-20 03:46:14 +0000425
426 /// Relocations - These are the relocations that the function needs, as
427 /// emitted.
428 std::vector<MachineRelocation> Relocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000429
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000430 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000431 JITEmitter(JIT &jit)
Andrew Lenharth6a974612005-07-28 12:44:13 +0000432 :MemMgr(jit.getJITInfo().needsGOT())
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000433 {
Jeff Cohen00b168892005-07-27 06:12:32 +0000434 TheJIT = &jit;
435 DEBUG(std::cerr <<
436 (MemMgr.isManagingGOT() ? "JIT is managing GOT\n"
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000437 : "JIT is not managing GOT\n"));
438 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000439
440 virtual void startFunction(MachineFunction &F);
441 virtual void finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000442 virtual void emitConstantPool(MachineConstantPool *MCP);
Chris Lattner54266522004-11-20 23:57:07 +0000443 virtual void startFunctionStub(unsigned StubSize);
444 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000445 virtual void emitByte(unsigned char B);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000446 virtual void emitWord(unsigned W);
Brian Gaekeaea1b582004-04-23 17:11:14 +0000447 virtual void emitWordAt(unsigned W, unsigned *Ptr);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000448
Chris Lattner5be478f2004-11-20 03:46:14 +0000449 virtual void addRelocation(const MachineRelocation &MR) {
450 Relocations.push_back(MR);
451 }
452
453 virtual uint64_t getCurrentPCValue();
454 virtual uint64_t getCurrentPCOffset();
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000455 virtual uint64_t getConstantPoolEntryAddress(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 Lattner688506d2003-08-14 18:35:27 +0000500 CurByte = CurBlock = MemMgr.startFunctionBody();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000501 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000502}
503
Chris Lattner166f2262004-11-22 22:00:25 +0000504void JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000505 MemMgr.endFunctionBody(CurByte);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000506 NumBytes += CurByte-CurBlock;
507
Chris Lattner5be478f2004-11-20 03:46:14 +0000508 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000509 NumRelos += Relocations.size();
510
Chris Lattner5be478f2004-11-20 03:46:14 +0000511 // Resolve the relocations to concrete pointers.
512 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
513 MachineRelocation &MR = Relocations[i];
514 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000515 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000516 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000517
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000518 // If the target REALLY wants a stub for this function, emit it now.
519 if (!MR.doesntNeedFunctionStub())
520 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Jeff Cohen00b168892005-07-27 06:12:32 +0000521 } else if (MR.isGlobalValue())
Chris Lattner5e225582004-11-21 03:37:42 +0000522 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
523 CurBlock+MR.getMachineCodeOffset(),
524 MR.doesntNeedFunctionStub());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000525 else //ConstantPoolIndex
Jeff Cohen00b168892005-07-27 06:12:32 +0000526 ResultPtr =
Chris Lattnerd6bbac52005-07-25 23:42:58 +0000527 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Jeff Cohen00b168892005-07-27 06:12:32 +0000528
Chris Lattner5be478f2004-11-20 03:46:14 +0000529 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000530
Andrew Lenharth6a974612005-07-28 12:44:13 +0000531 // if we are managing the GOT and the relocation wants an index,
532 // give it one
533 if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
534 MR.isGOTRelative()) {
535 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
536 MR.setGOTIndex(idx);
537 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
538 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
Chris Lattner21998772006-01-07 06:20:51 +0000539 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
540 << "\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000541 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
542 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000543 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000544 }
545
546 TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000547 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000548 }
549
Andrew Lenharth6a974612005-07-28 12:44:13 +0000550 //Update the GOT entry for F to point to the new code.
551 if(MemMgr.isManagingGOT()) {
552 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)CurBlock);
553 if (((void**)MemMgr.getGOTBase())[idx] != (void*)CurBlock) {
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000554 DEBUG(std::cerr << "GOT was out of date for " << (void*)CurBlock
Andrew Lenharth6a974612005-07-28 12:44:13 +0000555 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
556 ((void**)MemMgr.getGOTBase())[idx] = (void*)CurBlock;
557 }
558 }
559
Chris Lattnercb479412004-11-21 03:44:32 +0000560 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
Misha Brukman1d440852003-06-06 06:52:35 +0000561 << "] Function: " << F.getFunction()->getName()
Chris Lattner5be478f2004-11-20 03:46:14 +0000562 << ": " << CurByte-CurBlock << " bytes of text, "
563 << Relocations.size() << " relocations\n");
564 Relocations.clear();
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000565 ConstantPoolAddresses.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000566}
567
Chris Lattner166f2262004-11-22 22:00:25 +0000568void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000569 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000570 if (Constants.empty()) return;
571
Chris Lattner3029f922006-02-09 04:46:04 +0000572 unsigned Size = Constants.back().Offset;
573 Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000574
Chris Lattner3029f922006-02-09 04:46:04 +0000575 void *Addr = MemMgr.allocateConstant(Size,
576 1 << MCP->getConstantPoolAlignment());
577
578 // FIXME: Can eliminate ConstantPoolAddresses!
579 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
580 void *CAddr = (char*)Addr+Constants[i].Offset;
581 TheJIT->InitializeMemory(Constants[i].Val, CAddr);
582 ConstantPoolAddresses.push_back(CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000583 }
584}
585
Chris Lattner166f2262004-11-22 22:00:25 +0000586void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner6125fdd2003-05-09 03:30:07 +0000587 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
Chris Lattner688506d2003-08-14 18:35:27 +0000588 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000589}
590
Chris Lattner166f2262004-11-22 22:00:25 +0000591void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner6125fdd2003-05-09 03:30:07 +0000592 NumBytes += CurByte-CurBlock;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000593 std::swap(CurBlock, SavedCurBlock);
594 CurByte = SavedCurByte;
595 return SavedCurBlock;
596}
597
Chris Lattner166f2262004-11-22 22:00:25 +0000598void JITEmitter::emitByte(unsigned char B) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000599 *CurByte++ = B; // Write the byte to memory
600}
601
Chris Lattner166f2262004-11-22 22:00:25 +0000602void JITEmitter::emitWord(unsigned W) {
Chris Lattner688506d2003-08-14 18:35:27 +0000603 // This won't work if the endianness of the host and target don't agree! (For
604 // a JIT this can't happen though. :)
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000605 *(unsigned*)CurByte = W;
606 CurByte += sizeof(unsigned);
607}
608
Chris Lattner166f2262004-11-22 22:00:25 +0000609void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
Brian Gaekeaea1b582004-04-23 17:11:14 +0000610 *Ptr = W;
611}
612
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000613// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
614// in the constant pool that was last emitted with the 'emitConstantPool'
615// method.
616//
Chris Lattner166f2262004-11-22 22:00:25 +0000617uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000618 assert(ConstantNum < ConstantPoolAddresses.size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000619 "Invalid ConstantPoolIndex!");
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000620 return (intptr_t)ConstantPoolAddresses[ConstantNum];
621}
622
Andrew Lenharth6a974612005-07-28 12:44:13 +0000623unsigned char* JITEmitter::allocateGlobal(unsigned size, unsigned alignment)
624{
625 return MemMgr.allocateGlobal(size, alignment);
626}
627
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000628// getCurrentPCValue - This returns the address that the next emitted byte
629// will be output to.
630//
Chris Lattner166f2262004-11-22 22:00:25 +0000631uint64_t JITEmitter::getCurrentPCValue() {
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000632 return (intptr_t)CurByte;
633}
634
Chris Lattner166f2262004-11-22 22:00:25 +0000635uint64_t JITEmitter::getCurrentPCOffset() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000636 return (intptr_t)CurByte-(intptr_t)CurBlock;
637}
638
Misha Brukmand69c1e62003-07-28 19:09:06 +0000639// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000640// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000641// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
642// need to resolve function(s) that are being mis-codegenerated, so we need to
643// resolve their addresses at runtime, and this is the way to do it.
644extern "C" {
645 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000646 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000647 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000648 return TheJIT->getPointerToFunction(F);
649 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000650 }
651}