blob: 6e4ace9bf4d38968dae814d49bf97c0cea5b02b9 [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>
Chris Lattnerc19aade2003-12-08 08:06:28 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000036 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Chris Lattnere884dc22005-07-20 16:29:20 +000037 Statistic<> NumRelos("jit", "Number of relocations applied");
Chris Lattner4d326fa2003-12-20 01:46:27 +000038 JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000039}
Chris Lattnerbd199fb2002-12-24 00:01:05 +000040
Chris Lattner54266522004-11-20 23:57:07 +000041
42//===----------------------------------------------------------------------===//
43// JITMemoryManager code.
44//
45namespace {
Chris Lattner688506d2003-08-14 18:35:27 +000046 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
47 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
48 /// sections, one for function stubs, one for the functions themselves. We
49 /// have to do this because we may need to emit a function stub while in the
50 /// middle of emitting a function, and we don't know how large the function we
51 /// are emitting is. This never bothers to release the memory, because when
52 /// we are ready to destroy the JIT, the program exits.
53 class JITMemoryManager {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +000054 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
Chris Lattner688506d2003-08-14 18:35:27 +000055 unsigned char *FunctionBase; // Start of the function body area
Chris Lattnerf75f9be2006-05-02 23:22:24 +000056 unsigned char *CurStubPtr, *CurFunctionPtr;
Chris Lattnera726c7f2006-05-02 21:44:14 +000057 unsigned char *GOTBase; // Target Specific reserved memory
Andrew Lenhartha00269b2005-07-29 23:40:16 +000058
59 // centralize memory block allocation
60 sys::MemoryBlock getNewMemoryBlock(unsigned size);
Chris Lattner688506d2003-08-14 18:35:27 +000061 public:
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000062 JITMemoryManager(bool useGOT);
Reid Spencer4af3da62004-12-13 16:04:04 +000063 ~JITMemoryManager();
Misha Brukmanf976c852005-04-21 22:55:34 +000064
Chris Lattner688506d2003-08-14 18:35:27 +000065 inline unsigned char *allocateStub(unsigned StubSize);
66 inline unsigned char *startFunctionBody();
Chris Lattner281a6012005-01-10 18:23:22 +000067 inline void endFunctionBody(unsigned char *FunctionEnd);
Chris Lattnera726c7f2006-05-02 21:44:14 +000068
69 unsigned char *getGOTBase() const {
70 return GOTBase;
71 }
72 bool isManagingGOT() const {
73 return GOTBase != NULL;
74 }
Chris Lattner688506d2003-08-14 18:35:27 +000075 };
76}
77
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000078JITMemoryManager::JITMemoryManager(bool useGOT) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +000079 // Allocate a 16M block of memory for functions
80 sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +000081
Andrew Lenhartha00269b2005-07-29 23:40:16 +000082 FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
Chris Lattner281a6012005-01-10 18:23:22 +000083
Andrew Lenhartha00269b2005-07-29 23:40:16 +000084 // Allocate stubs backwards from the base, allocate functions forward
85 // from the base.
86 CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
87
Chris Lattnerf5d438c2006-05-02 21:57:51 +000088 // Allocate the GOT.
Andrew Lenharth2b3b89c2005-08-01 17:35:40 +000089 GOTBase = NULL;
Chris Lattnerf5d438c2006-05-02 21:57:51 +000090 if (useGOT) GOTBase = (unsigned char*)malloc(sizeof(void*) * 8192);
Chris Lattner688506d2003-08-14 18:35:27 +000091}
92
Reid Spencer4af3da62004-12-13 16:04:04 +000093JITMemoryManager::~JITMemoryManager() {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +000094 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
95 sys::Memory::ReleaseRWX(Blocks[i]);
Andrew Lenhartha00269b2005-07-29 23:40:16 +000096 Blocks.clear();
Reid Spencer4af3da62004-12-13 16:04:04 +000097}
98
Chris Lattner688506d2003-08-14 18:35:27 +000099unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
100 CurStubPtr -= StubSize;
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000101 if (CurStubPtr < FunctionBase) {
Chris Lattnera726c7f2006-05-02 21:44:14 +0000102 // FIXME: allocate a new block
Chris Lattner688506d2003-08-14 18:35:27 +0000103 std::cerr << "JIT ran out of memory for function stubs!\n";
104 abort();
105 }
106 return CurStubPtr;
107}
108
109unsigned char *JITMemoryManager::startFunctionBody() {
Chris Lattner5be478f2004-11-20 03:46:14 +0000110 // Round up to an even multiple of 8 bytes, this should eventually be target
Chris Lattner688506d2003-08-14 18:35:27 +0000111 // specific.
Chris Lattner5be478f2004-11-20 03:46:14 +0000112 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
Chris Lattner688506d2003-08-14 18:35:27 +0000113}
114
115void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
116 assert(FunctionEnd > CurFunctionPtr);
117 CurFunctionPtr = FunctionEnd;
118}
119
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000120sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000121 try {
Chris Lattnere6fdcbf2006-05-03 00:54:49 +0000122 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
123 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld);
124 Blocks.push_back(B);
125 return B;
126 } catch (std::string &err) {
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000127 std::cerr << "Allocation failed when allocating new memory in the JIT\n";
128 std::cerr << err << "\n";
129 abort();
130 }
Andrew Lenhartha00269b2005-07-29 23:40:16 +0000131}
132
Chris Lattner54266522004-11-20 23:57:07 +0000133//===----------------------------------------------------------------------===//
134// JIT lazy compilation code.
135//
136namespace {
Reid Spenceree448632005-07-12 15:51:55 +0000137 class JITResolverState {
138 private:
139 /// FunctionToStubMap - Keep track of the stub created for a particular
140 /// function so that we can reuse them if necessary.
141 std::map<Function*, void*> FunctionToStubMap;
142
143 /// StubToFunctionMap - Keep track of the function that each stub
144 /// corresponds to.
145 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000146
Reid Spenceree448632005-07-12 15:51:55 +0000147 public:
148 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
149 assert(locked.holds(TheJIT->lock));
150 return FunctionToStubMap;
151 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000152
Reid Spenceree448632005-07-12 15:51:55 +0000153 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
154 assert(locked.holds(TheJIT->lock));
155 return StubToFunctionMap;
156 }
157 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000158
Chris Lattner54266522004-11-20 23:57:07 +0000159 /// JITResolver - Keep track of, and resolve, call sites for functions that
160 /// have not yet been compiled.
161 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +0000162 /// MCE - The MachineCodeEmitter to use to emit stubs with.
Chris Lattner54266522004-11-20 23:57:07 +0000163 MachineCodeEmitter &MCE;
164
Chris Lattner5e225582004-11-21 03:37:42 +0000165 /// LazyResolverFn - The target lazy resolver function that we actually
166 /// rewrite instructions to use.
167 TargetJITInfo::LazyResolverFn LazyResolverFn;
168
Reid Spenceree448632005-07-12 15:51:55 +0000169 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000170
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000171 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
172 /// external functions.
173 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000174
175 //map addresses to indexes in the GOT
176 std::map<void*, unsigned> revGOTMap;
177 unsigned nextGOTIndex;
178
Chris Lattner54266522004-11-20 23:57:07 +0000179 public:
Andrew Lenharth6a974612005-07-28 12:44:13 +0000180 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
Chris Lattner5e225582004-11-21 03:37:42 +0000181 LazyResolverFn =
182 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
183 }
Chris Lattner54266522004-11-20 23:57:07 +0000184
185 /// getFunctionStub - This returns a pointer to a function stub, creating
186 /// one on demand as needed.
187 void *getFunctionStub(Function *F);
188
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000189 /// getExternalFunctionStub - Return a stub for the function at the
190 /// specified address, created lazily on demand.
191 void *getExternalFunctionStub(void *FnAddr);
192
Chris Lattner5e225582004-11-21 03:37:42 +0000193 /// AddCallbackAtLocation - If the target is capable of rewriting an
194 /// instruction without the use of a stub, record the location of the use so
195 /// we know which function is being used at the location.
196 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000197 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000198 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000199 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner5e225582004-11-21 03:37:42 +0000200 return (void*)LazyResolverFn;
201 }
202
Andrew Lenharth6a974612005-07-28 12:44:13 +0000203 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
204 /// and address. This function only manages slots, it does not manage the
205 /// contents of the slots or the memory associated with the GOT.
206 unsigned getGOTIndexForAddr(void* addr);
207
Chris Lattner54266522004-11-20 23:57:07 +0000208 /// JITCompilerFn - This function is called to resolve a stub to a compiled
209 /// address. If the LLVM Function corresponding to the stub has not yet
210 /// been compiled, this function compiles it first.
211 static void *JITCompilerFn(void *Stub);
212 };
213}
214
215/// getJITResolver - This function returns the one instance of the JIT resolver.
216///
217static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
218 static JITResolver TheJITResolver(*MCE);
219 return TheJITResolver;
220}
221
222/// getFunctionStub - This returns a pointer to a function stub, creating
223/// one on demand as needed.
224void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000225 MutexGuard locked(TheJIT->lock);
226
Chris Lattner54266522004-11-20 23:57:07 +0000227 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000228 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000229 if (Stub) return Stub;
230
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000231 // Call the lazy resolver function unless we already KNOW it is an external
232 // function, in which case we just skip the lazy resolution step.
233 void *Actual = (void*)LazyResolverFn;
Chris Lattner69435702005-02-20 18:43:35 +0000234 if (F->isExternal() && F->hasExternalLinkage())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000235 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000236
Chris Lattner54266522004-11-20 23:57:07 +0000237 // Otherwise, codegen a new stub. For now, the stub will call the lazy
238 // resolver function.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000239 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
240
Chris Lattner69435702005-02-20 18:43:35 +0000241 if (Actual != (void*)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000242 // If we are getting the stub for an external function, we really want the
243 // address of the stub in the GlobalAddressMap for the JIT, not the address
244 // of the external function.
245 TheJIT->updateGlobalMapping(F, Stub);
246 }
Chris Lattner54266522004-11-20 23:57:07 +0000247
Chris Lattnercb479412004-11-21 03:44:32 +0000248 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
Chris Lattner6f717202004-11-22 21:48:33 +0000249 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000250
Chris Lattner54266522004-11-20 23:57:07 +0000251 // Finally, keep track of the stub-to-Function mapping so that the
252 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000253 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000254 return Stub;
255}
256
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000257/// getExternalFunctionStub - Return a stub for the function at the
258/// specified address, created lazily on demand.
259void *JITResolver::getExternalFunctionStub(void *FnAddr) {
260 // If we already have a stub for this function, recycle it.
261 void *&Stub = ExternalFnToStubMap[FnAddr];
262 if (Stub) return Stub;
263
264 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
265 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
266 << "] for external function at '" << FnAddr << "'\n");
267 return Stub;
268}
269
Andrew Lenharth6a974612005-07-28 12:44:13 +0000270unsigned JITResolver::getGOTIndexForAddr(void* addr) {
271 unsigned idx = revGOTMap[addr];
272 if (!idx) {
273 idx = ++nextGOTIndex;
274 revGOTMap[addr] = idx;
275 DEBUG(std::cerr << "Adding GOT entry " << idx
276 << " for addr " << addr << "\n");
277 // ((void**)MemMgr.getGOTBase())[idx] = addr;
278 }
279 return idx;
280}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000281
Chris Lattner54266522004-11-20 23:57:07 +0000282/// JITCompilerFn - This function is called when a lazy compilation stub has
283/// been entered. It looks up which function this stub corresponds to, compiles
284/// it if necessary, then returns the resultant function pointer.
285void *JITResolver::JITCompilerFn(void *Stub) {
286 JITResolver &JR = getJITResolver();
Misha Brukmanf976c852005-04-21 22:55:34 +0000287
Reid Spenceree448632005-07-12 15:51:55 +0000288 MutexGuard locked(TheJIT->lock);
289
Chris Lattner54266522004-11-20 23:57:07 +0000290 // The address given to us for the stub may not be exactly right, it might be
291 // a little bit after the stub. As such, use upper_bound to find it.
292 std::map<void*, Function*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000293 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
Chris Lattner21998772006-01-07 06:20:51 +0000294 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
295 "This is not a known stub!");
Chris Lattner54266522004-11-20 23:57:07 +0000296 Function *F = (--I)->second;
297
Reid Spenceree448632005-07-12 15:51:55 +0000298 // We might like to remove the stub from the StubToFunction map.
299 // We can't do that! Multiple threads could be stuck, waiting to acquire the
300 // lock above. As soon as the 1st function finishes compiling the function,
Chris Lattner21998772006-01-07 06:20:51 +0000301 // the next one will be released, and needs to be able to find the function it
302 // needs to call.
Reid Spenceree448632005-07-12 15:51:55 +0000303 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000304
Chris Lattnercb479412004-11-21 03:44:32 +0000305 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
Chris Lattner54266522004-11-20 23:57:07 +0000306 << "' In stub ptr = " << Stub << " actual ptr = "
307 << I->first << "\n");
308
309 void *Result = TheJIT->getPointerToFunction(F);
310
311 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000312 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000313
314 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000315
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000316 // What we will do is set the compiled function address to map to the
317 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000318 // if they see it still using the stub address.
319 // Note: this is done so the Resolver doesn't have to manage GOT memory
320 // Do this without allocating map space if the target isn't using a GOT
321 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
322 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
323
Chris Lattner54266522004-11-20 23:57:07 +0000324 return Result;
325}
Chris Lattner688506d2003-08-14 18:35:27 +0000326
327
Chris Lattnere518b712004-12-05 07:19:16 +0000328// getPointerToFunctionOrStub - If the specified function has been
329// code-gen'd, return a pointer to the function. If not, compile it, or use
330// a stub to implement lazy compilation if available.
331//
332void *JIT::getPointerToFunctionOrStub(Function *F) {
333 // If we have already code generated the function, just return the address.
334 if (void *Addr = getPointerToGlobalIfAvailable(F))
335 return Addr;
336
337 // Get a stub if the target supports it
338 return getJITResolver(MCE).getFunctionStub(F);
339}
340
341
342
Chris Lattner54266522004-11-20 23:57:07 +0000343//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000344// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000345//
Chris Lattner688506d2003-08-14 18:35:27 +0000346namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000347 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
348 /// used to output functions to memory for execution.
349 class JITEmitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000350 JITMemoryManager MemMgr;
351
Chris Lattner6125fdd2003-05-09 03:30:07 +0000352 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000353 // save BufferBegin/BufferEnd/CurBufferPtr here.
354 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000355
Chris Lattner5be478f2004-11-20 03:46:14 +0000356 /// Relocations - These are the relocations that the function needs, as
357 /// emitted.
358 std::vector<MachineRelocation> Relocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000359
Chris Lattner239862c2006-02-09 04:49:59 +0000360 /// ConstantPool - The constant pool for the current function.
361 ///
362 MachineConstantPool *ConstantPool;
363
364 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
365 ///
366 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000367
368 /// ConstantPool - The constant pool for the current function.
369 ///
370 MachineJumpTableInfo *JumpTable;
371
372 /// JumpTableBase - A pointer to the first entry in the jump table.
373 ///
374 void *JumpTableBase;
375public:
Chris Lattner239862c2006-02-09 04:49:59 +0000376 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000377 TheJIT = &jit;
Chris Lattnera726c7f2006-05-02 21:44:14 +0000378 DEBUG(if (MemMgr.isManagingGOT()) std::cerr << "JIT is managing a GOT\n");
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000379 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000380
381 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000382 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000383
384 void emitConstantPool(MachineConstantPool *MCP);
385 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Nate Begeman37efe672006-04-22 18:53:45 +0000386 virtual void emitJumpTableInfo(MachineJumpTableInfo *MJTI,
Chris Lattneraf1563f2006-05-03 00:32:55 +0000387 std::vector<uint64_t> &MBBM);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000388
Chris Lattner54266522004-11-20 23:57:07 +0000389 virtual void startFunctionStub(unsigned StubSize);
390 virtual void* finishFunctionStub(const Function *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000391
Chris Lattner5be478f2004-11-20 03:46:14 +0000392 virtual void addRelocation(const MachineRelocation &MR) {
393 Relocations.push_back(MR);
394 }
395
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000396 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
Nate Begeman37efe672006-04-22 18:53:45 +0000397 virtual uint64_t getJumpTableEntryAddress(unsigned Entry);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000398
Chris Lattner54266522004-11-20 23:57:07 +0000399 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000400 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000401 };
402}
403
Chris Lattner4d326fa2003-12-20 01:46:27 +0000404MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
Chris Lattner166f2262004-11-22 22:00:25 +0000405 return new JITEmitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000406}
407
Chris Lattner166f2262004-11-22 22:00:25 +0000408void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
409 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000410 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
411 /// FIXME: If we straightened things out, this could actually emit the
412 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000413 return TheJIT->getOrEmitGlobalVariable(GV);
414 }
415
416 // If we have already compiled the function, return a pointer to its body.
417 Function *F = cast<Function>(V);
418 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
419 if (ResultPtr) return ResultPtr;
420
Chris Lattner532343b2004-11-30 17:41:49 +0000421 if (F->hasExternalLinkage() && F->isExternal()) {
Chris Lattner54266522004-11-20 23:57:07 +0000422 // If this is an external function pointer, we can force the JIT to
423 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000424 if (DoesntNeedStub)
425 return TheJIT->getPointerToFunction(F);
426
427 return getJITResolver(this).getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000428 }
429
Chris Lattner5e225582004-11-21 03:37:42 +0000430 // Okay, the function has not been compiled yet, if the target callback
431 // mechanism is capable of rewriting the instruction directly, prefer to do
432 // that instead of emitting a stub.
433 if (DoesntNeedStub)
434 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
435
Chris Lattner54266522004-11-20 23:57:07 +0000436 // Otherwise, we have to emit a lazy resolving stub.
437 return getJITResolver(this).getFunctionStub(F);
438}
439
Chris Lattner166f2262004-11-22 22:00:25 +0000440void JITEmitter::startFunction(MachineFunction &F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000441 BufferBegin = CurBufferPtr = MemMgr.startFunctionBody();
Chris Lattner43b429b2006-05-02 18:27:26 +0000442
443 /// FIXME: implement out of space handling correctly!
444 BufferEnd = (unsigned char*)(intptr_t)~0ULL;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000445
446 emitConstantPool(F.getConstantPool());
447 initJumpTableInfo(F.getJumpTableInfo());
448
449 // About to start emitting the machine code for the function.
450 // FIXME: align it?
451 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000452}
453
Chris Lattner43b429b2006-05-02 18:27:26 +0000454bool JITEmitter::finishFunction(MachineFunction &F) {
455 MemMgr.endFunctionBody(CurBufferPtr);
456 NumBytes += getCurrentPCOffset();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000457
Chris Lattner5be478f2004-11-20 03:46:14 +0000458 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000459 NumRelos += Relocations.size();
460
Chris Lattner5be478f2004-11-20 03:46:14 +0000461 // Resolve the relocations to concrete pointers.
462 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
463 MachineRelocation &MR = Relocations[i];
464 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000465 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000466 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000467
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000468 // If the target REALLY wants a stub for this function, emit it now.
469 if (!MR.doesntNeedFunctionStub())
470 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
Jeff Cohen00b168892005-07-27 06:12:32 +0000471 } else if (MR.isGlobalValue())
Chris Lattner5e225582004-11-21 03:37:42 +0000472 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000473 BufferBegin+MR.getMachineCodeOffset(),
Chris Lattner5e225582004-11-21 03:37:42 +0000474 MR.doesntNeedFunctionStub());
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000475 else //ConstantPoolIndex
Jeff Cohen00b168892005-07-27 06:12:32 +0000476 ResultPtr =
Chris Lattnerd6bbac52005-07-25 23:42:58 +0000477 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Jeff Cohen00b168892005-07-27 06:12:32 +0000478
Chris Lattner5be478f2004-11-20 03:46:14 +0000479 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000480
Andrew Lenharth6a974612005-07-28 12:44:13 +0000481 // if we are managing the GOT and the relocation wants an index,
482 // give it one
483 if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
484 MR.isGOTRelative()) {
485 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
486 MR.setGOTIndex(idx);
487 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
488 DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
Chris Lattner21998772006-01-07 06:20:51 +0000489 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
490 << "\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000491 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
492 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000493 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000494 }
495
Chris Lattner43b429b2006-05-02 18:27:26 +0000496 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000497 Relocations.size(), MemMgr.getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000498 }
499
Andrew Lenharth6a974612005-07-28 12:44:13 +0000500 //Update the GOT entry for F to point to the new code.
501 if(MemMgr.isManagingGOT()) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000502 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
503 if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
504 DEBUG(std::cerr << "GOT was out of date for " << (void*)BufferBegin
Andrew Lenharth6a974612005-07-28 12:44:13 +0000505 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
Chris Lattner43b429b2006-05-02 18:27:26 +0000506 ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000507 }
508 }
509
Chris Lattner43b429b2006-05-02 18:27:26 +0000510 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)BufferBegin
Misha Brukman1d440852003-06-06 06:52:35 +0000511 << "] Function: " << F.getFunction()->getName()
Chris Lattner43b429b2006-05-02 18:27:26 +0000512 << ": " << getCurrentPCOffset() << " bytes of text, "
Chris Lattner5be478f2004-11-20 03:46:14 +0000513 << Relocations.size() << " relocations\n");
514 Relocations.clear();
Chris Lattner43b429b2006-05-02 18:27:26 +0000515 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000516}
517
Chris Lattner166f2262004-11-22 22:00:25 +0000518void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000519 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000520 if (Constants.empty()) return;
521
Chris Lattner3029f922006-02-09 04:46:04 +0000522 unsigned Size = Constants.back().Offset;
523 Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000524
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000525 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
Chris Lattner239862c2006-02-09 04:49:59 +0000526 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000527
528 if (ConstantPoolBase == 0) return; // Buffer overflow.
529
Chris Lattner239862c2006-02-09 04:49:59 +0000530 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +0000531 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +0000532 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Chris Lattner3029f922006-02-09 04:46:04 +0000533 TheJIT->InitializeMemory(Constants[i].Val, CAddr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000534 }
535}
536
Nate Begeman37efe672006-04-22 18:53:45 +0000537void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
538 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
539 if (JT.empty()) return;
540
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000541 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +0000542 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000543 NumEntries += JT[i].MBBs.size();
544
545 unsigned EntrySize = MJTI->getEntrySize();
546
Nate Begeman37efe672006-04-22 18:53:45 +0000547 // Just allocate space for all the jump tables now. We will fix up the actual
548 // MBB entries in the tables after we emit the code for each block, since then
549 // we will know the final locations of the MBBs in memory.
550 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000551 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +0000552}
553
554void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI,
Chris Lattneraf1563f2006-05-03 00:32:55 +0000555 std::vector<uint64_t> &MBBM) {
Nate Begeman37efe672006-04-22 18:53:45 +0000556 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000557 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +0000558
559 unsigned Offset = 0;
Chris Lattner32ca55f2006-05-03 00:13:06 +0000560 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
Nate Begeman37efe672006-04-22 18:53:45 +0000561
562 // For each jump table, map each target in the jump table to the address of
563 // an emitted MachineBasicBlock.
Chris Lattner32ca55f2006-05-03 00:13:06 +0000564 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
565
Nate Begeman37efe672006-04-22 18:53:45 +0000566 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
567 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Chris Lattner32ca55f2006-05-03 00:13:06 +0000568 // Store the address of the basic block for this jump table slot in the
569 // memory we allocated for the jump table in 'initJumpTableInfo'
570 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
Chris Lattneraf1563f2006-05-03 00:32:55 +0000571 *SlotPtr++ = (intptr_t)MBBM[MBBs[mi]->getNumber()];
Nate Begeman37efe672006-04-22 18:53:45 +0000572 }
573}
574
Chris Lattner166f2262004-11-22 22:00:25 +0000575void JITEmitter::startFunctionStub(unsigned StubSize) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000576 SavedBufferBegin = BufferBegin;
577 SavedBufferEnd = BufferEnd;
578 SavedCurBufferPtr = CurBufferPtr;
579
580 BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize);
581 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +0000582}
583
Chris Lattner166f2262004-11-22 22:00:25 +0000584void *JITEmitter::finishFunctionStub(const Function *F) {
Chris Lattner43b429b2006-05-02 18:27:26 +0000585 NumBytes += getCurrentPCOffset();
586 std::swap(SavedBufferBegin, BufferBegin);
587 BufferEnd = SavedBufferEnd;
588 CurBufferPtr = SavedCurBufferPtr;
589 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000590}
591
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000592// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
593// in the constant pool that was last emitted with the 'emitConstantPool'
594// method.
595//
Chris Lattner166f2262004-11-22 22:00:25 +0000596uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
Chris Lattner239862c2006-02-09 04:49:59 +0000597 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +0000598 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +0000599 return (intptr_t)ConstantPoolBase +
600 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000601}
602
Nate Begeman37efe672006-04-22 18:53:45 +0000603// getJumpTableEntryAddress - Return the address of the JumpTable with index
604// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
605//
606uint64_t JITEmitter::getJumpTableEntryAddress(unsigned Index) {
607 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
608 assert(Index < JT.size() && "Invalid jump table index!");
609
610 unsigned Offset = 0;
611 unsigned EntrySize = JumpTable->getEntrySize();
612
613 for (unsigned i = 0; i < Index; ++i)
614 Offset += JT[i].MBBs.size() * EntrySize;
615
Nate Begemanc34b2272006-04-25 17:46:32 +0000616 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +0000617}
618
Misha Brukmand69c1e62003-07-28 19:09:06 +0000619// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000620// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000621// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
622// need to resolve function(s) that are being mis-codegenerated, so we need to
623// resolve their addresses at runtime, and this is the way to do it.
624extern "C" {
625 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000626 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000627 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000628 return TheJIT->getPointerToFunction(F);
629 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000630 }
631}