blob: ffaeb1c4ea95dcb840248fa2731ffc62c834b690 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000017#include "JITDwarfEmitter.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000018#include "llvm/Constants.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000019#include "llvm/Module.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000020#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000021#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000023#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000026#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000029#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000030#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000031#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000032#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000034#include "llvm/Support/MutexGuard.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000035#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000036#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000037#include "llvm/Target/TargetInstrInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000039#include <algorithm>
Dale Johannesendd947ea2008-08-07 01:30:15 +000040#include <set>
Chris Lattnerc19aade2003-12-08 08:06:28 +000041using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000042
Chris Lattner36343732006-12-19 22:43:32 +000043STATISTIC(NumBytes, "Number of bytes of machine code compiled");
44STATISTIC(NumRelos, "Number of relocations applied");
45static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000046
Andrew Lenhartha00269b2005-07-29 23:40:16 +000047
Chris Lattner54266522004-11-20 23:57:07 +000048//===----------------------------------------------------------------------===//
49// JIT lazy compilation code.
50//
51namespace {
Reid Spenceree448632005-07-12 15:51:55 +000052 class JITResolverState {
53 private:
54 /// FunctionToStubMap - Keep track of the stub created for a particular
55 /// function so that we can reuse them if necessary.
56 std::map<Function*, void*> FunctionToStubMap;
57
58 /// StubToFunctionMap - Keep track of the function that each stub
59 /// corresponds to.
60 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000061
Evan Chengbe8c03f2008-01-04 10:46:51 +000062 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
63 /// particular GlobalVariable so that we can reuse them if necessary.
64 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
65
Reid Spenceree448632005-07-12 15:51:55 +000066 public:
67 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
68 assert(locked.holds(TheJIT->lock));
69 return FunctionToStubMap;
70 }
Jeff Cohen00b168892005-07-27 06:12:32 +000071
Reid Spenceree448632005-07-12 15:51:55 +000072 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
73 assert(locked.holds(TheJIT->lock));
74 return StubToFunctionMap;
75 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000076
77 std::map<GlobalValue*, void*>&
78 getGlobalToLazyPtrMap(const MutexGuard& locked) {
79 assert(locked.holds(TheJIT->lock));
80 return GlobalToLazyPtrMap;
81 }
Reid Spenceree448632005-07-12 15:51:55 +000082 };
Jeff Cohen00b168892005-07-27 06:12:32 +000083
Chris Lattner54266522004-11-20 23:57:07 +000084 /// JITResolver - Keep track of, and resolve, call sites for functions that
85 /// have not yet been compiled.
86 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000087 /// LazyResolverFn - The target lazy resolver function that we actually
88 /// rewrite instructions to use.
89 TargetJITInfo::LazyResolverFn LazyResolverFn;
90
Reid Spenceree448632005-07-12 15:51:55 +000091 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000092
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000093 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
94 /// external functions.
95 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +000096
97 //map addresses to indexes in the GOT
98 std::map<void*, unsigned> revGOTMap;
99 unsigned nextGOTIndex;
100
Chris Lattnere7484012007-02-24 02:57:03 +0000101 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000102 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000103 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000104 TheJIT = &jit;
105
106 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
107 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
108 TheJITResolver = this;
109 }
110
111 ~JITResolver() {
112 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000113 }
Chris Lattner54266522004-11-20 23:57:07 +0000114
115 /// getFunctionStub - This returns a pointer to a function stub, creating
116 /// one on demand as needed.
117 void *getFunctionStub(Function *F);
118
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000119 /// getExternalFunctionStub - Return a stub for the function at the
120 /// specified address, created lazily on demand.
121 void *getExternalFunctionStub(void *FnAddr);
122
Evan Chengbe8c03f2008-01-04 10:46:51 +0000123 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
124 /// GV address.
125 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
126
Chris Lattner5e225582004-11-21 03:37:42 +0000127 /// AddCallbackAtLocation - If the target is capable of rewriting an
128 /// instruction without the use of a stub, record the location of the use so
129 /// we know which function is being used at the location.
130 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000131 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000132 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000133 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000134 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000135 }
136
Andrew Lenharth6a974612005-07-28 12:44:13 +0000137 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000138 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000139 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000140 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000141
Chris Lattner54266522004-11-20 23:57:07 +0000142 /// JITCompilerFn - This function is called to resolve a stub to a compiled
143 /// address. If the LLVM Function corresponding to the stub has not yet
144 /// been compiled, this function compiles it first.
145 static void *JITCompilerFn(void *Stub);
146 };
147}
148
Chris Lattnere7484012007-02-24 02:57:03 +0000149JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000150
151/// getFunctionStub - This returns a pointer to a function stub, creating
152/// one on demand as needed.
153void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000154 MutexGuard locked(TheJIT->lock);
155
Chris Lattner54266522004-11-20 23:57:07 +0000156 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000157 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000158 if (Stub) return Stub;
159
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000160 // Call the lazy resolver function unless we already KNOW it is an external
161 // function, in which case we just skip the lazy resolution step.
Chris Lattner870286a2006-06-01 17:29:22 +0000162 void *Actual = (void*)(intptr_t)LazyResolverFn;
Gabor Greifa99be512007-07-05 17:07:56 +0000163 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000164 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000165
Chris Lattner54266522004-11-20 23:57:07 +0000166 // Otherwise, codegen a new stub. For now, the stub will call the lazy
167 // resolver function.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000168 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000169 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000170
Chris Lattner870286a2006-06-01 17:29:22 +0000171 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000172 // If we are getting the stub for an external function, we really want the
173 // address of the stub in the GlobalAddressMap for the JIT, not the address
174 // of the external function.
175 TheJIT->updateGlobalMapping(F, Stub);
176 }
Chris Lattner54266522004-11-20 23:57:07 +0000177
Bill Wendling832171c2006-12-07 20:04:42 +0000178 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
179 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000180
Chris Lattner54266522004-11-20 23:57:07 +0000181 // Finally, keep track of the stub-to-Function mapping so that the
182 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000183 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000184 return Stub;
185}
186
Evan Chengbe8c03f2008-01-04 10:46:51 +0000187/// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
188/// GV address.
189void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
190 MutexGuard locked(TheJIT->lock);
191
192 // If we already have a stub for this global variable, recycle it.
193 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
194 if (LazyPtr) return LazyPtr;
195
196 // Otherwise, codegen a new lazy pointer.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000197 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
Evan Chengbe8c03f2008-01-04 10:46:51 +0000198 *TheJIT->getCodeEmitter());
199
200 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
201 << GV->getName() << "'\n";
202
203 return LazyPtr;
204}
205
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000206/// getExternalFunctionStub - Return a stub for the function at the
207/// specified address, created lazily on demand.
208void *JITResolver::getExternalFunctionStub(void *FnAddr) {
209 // If we already have a stub for this function, recycle it.
210 void *&Stub = ExternalFnToStubMap[FnAddr];
211 if (Stub) return Stub;
212
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000213 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000214 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000215
Bill Wendling832171c2006-12-07 20:04:42 +0000216 DOUT << "JIT: Stub emitted at [" << Stub
217 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000218 return Stub;
219}
220
Andrew Lenharth6a974612005-07-28 12:44:13 +0000221unsigned JITResolver::getGOTIndexForAddr(void* addr) {
222 unsigned idx = revGOTMap[addr];
223 if (!idx) {
224 idx = ++nextGOTIndex;
225 revGOTMap[addr] = idx;
Evan Cheng97b8c402008-04-12 00:22:01 +0000226 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000227 }
228 return idx;
229}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000230
Chris Lattner54266522004-11-20 23:57:07 +0000231/// JITCompilerFn - This function is called when a lazy compilation stub has
232/// been entered. It looks up which function this stub corresponds to, compiles
233/// it if necessary, then returns the resultant function pointer.
234void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000235 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000236
237 Function* F = 0;
238 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000239
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000240 {
241 // Only lock for getting the Function. The call getPointerToFunction made
242 // in this function might trigger function materializing, which requires
243 // JIT lock to be unlocked.
244 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000245
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000246 // The address given to us for the stub may not be exactly right, it might be
247 // a little bit after the stub. As such, use upper_bound to find it.
248 std::map<void*, Function*>::iterator I =
249 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
250 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
251 "This is not a known stub!");
252 F = (--I)->second;
253 ActualPtr = I->first;
254 }
Chris Lattner54266522004-11-20 23:57:07 +0000255
Evan Cheng9da60f92007-06-30 00:10:37 +0000256 // If we have already code generated the function, just return the address.
257 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000258
Evan Cheng9da60f92007-06-30 00:10:37 +0000259 if (!Result) {
260 // Otherwise we don't have it, do lazy compilation now.
261
262 // If lazy compilation is disabled, emit a useful error message and abort.
263 if (TheJIT->isLazyCompilationDisabled()) {
264 cerr << "LLVM JIT requested to do lazy compilation of function '"
265 << F->getName() << "' when lazy compiles are disabled!\n";
266 abort();
267 }
268
269 // We might like to remove the stub from the StubToFunction map.
270 // We can't do that! Multiple threads could be stuck, waiting to acquire the
271 // lock above. As soon as the 1st function finishes compiling the function,
272 // the next one will be released, and needs to be able to find the function
273 // it needs to call.
274 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000275
Evan Cheng9da60f92007-06-30 00:10:37 +0000276 DOUT << "JIT: Lazily resolving function '" << F->getName()
277 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000278 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000279
Evan Cheng9da60f92007-06-30 00:10:37 +0000280 Result = TheJIT->getPointerToFunction(F);
281 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000282
283 // Reacquire the lock to erase the stub in the map.
284 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000285
286 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000287 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000288
289 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000290
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000291 // What we will do is set the compiled function address to map to the
292 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000293 // if they see it still using the stub address.
294 // Note: this is done so the Resolver doesn't have to manage GOT memory
295 // Do this without allocating map space if the target isn't using a GOT
296 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
297 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
298
Chris Lattner54266522004-11-20 23:57:07 +0000299 return Result;
300}
Chris Lattner688506d2003-08-14 18:35:27 +0000301
Chris Lattner8ac66c12008-04-04 05:51:42 +0000302//===----------------------------------------------------------------------===//
303// Function Index Support
304
305// On MacOS we generate an index of currently JIT'd functions so that
306// performance tools can determine a symbol name and accurate code range for a
307// PC value. Because performance tools are generally asynchronous, the code
308// below is written with the hope that it could be interrupted at any time and
309// have useful answers. However, we don't go crazy with atomic operations, we
310// just do a "reasonable effort".
311#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000312#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000313#endif
314
315/// JitSymbolEntry - Each function that is JIT compiled results in one of these
316/// being added to an array of symbols. This indicates the name of the function
317/// as well as the address range it occupies. This allows the client to map
318/// from a PC value to the name of the function.
319struct JitSymbolEntry {
320 const char *FnName; // FnName - a strdup'd string.
321 void *FnStart;
322 intptr_t FnSize;
323};
324
325
326struct JitSymbolTable {
327 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
328 /// pointer is not used right now, but might be used in the future. Consider
329 /// it reserved for future use.
330 JitSymbolTable *NextPtr;
331
332 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
333 /// 'NumSymbols' symbols are valid.
334 JitSymbolEntry *Symbols;
335
336 /// NumSymbols - This indicates the number entries in the Symbols array that
337 /// are valid.
338 unsigned NumSymbols;
339
340 /// NumAllocated - This indicates the amount of space we have in the Symbols
341 /// array. This is a private field that should not be read by external tools.
342 unsigned NumAllocated;
343};
344
345#if ENABLE_JIT_SYMBOL_TABLE
346JitSymbolTable *__jitSymbolTable;
347#endif
348
349static void AddFunctionToSymbolTable(const char *FnName,
350 void *FnStart, intptr_t FnSize) {
351 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
352 JitSymbolTable **SymTabPtrPtr = 0;
353#if !ENABLE_JIT_SYMBOL_TABLE
354 return;
355#else
356 SymTabPtrPtr = &__jitSymbolTable;
357#endif
358
359 // If this is the first entry in the symbol table, add the JitSymbolTable
360 // index.
361 if (*SymTabPtrPtr == 0) {
362 JitSymbolTable *New = new JitSymbolTable();
363 New->NextPtr = 0;
364 New->Symbols = 0;
365 New->NumSymbols = 0;
366 New->NumAllocated = 0;
367 *SymTabPtrPtr = New;
368 }
369
370 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
371
372 // If we have space in the table, reallocate the table.
373 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
374 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000375 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000376 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
377 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
378
379 // Copy the old entries over.
380 memcpy(NewSymbols, OldSymbols,
Chris Lattner3b374482008-04-13 07:04:56 +0000381 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000382
383 // Swap the new symbols in, delete the old ones.
384 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000385 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000386 delete [] OldSymbols;
387 }
388
389 // Otherwise, we have enough space, just tack it onto the end of the array.
390 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
391 Entry.FnName = strdup(FnName);
392 Entry.FnStart = FnStart;
393 Entry.FnSize = FnSize;
394 ++SymTabPtr->NumSymbols;
395}
396
397static void RemoveFunctionFromSymbolTable(void *FnStart) {
398 assert(FnStart && "Invalid function pointer");
399 JitSymbolTable **SymTabPtrPtr = 0;
400#if !ENABLE_JIT_SYMBOL_TABLE
401 return;
402#else
403 SymTabPtrPtr = &__jitSymbolTable;
404#endif
405
406 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
407 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
408
409 // Scan the table to find its index. The table is not sorted, so do a linear
410 // scan.
411 unsigned Index;
412 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
413 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
414
415 // Once we have an index, we know to nuke this entry, overwrite it with the
416 // entry at the end of the array, making the last entry redundant.
417 const char *OldName = Symbols[Index].FnName;
418 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
419 free((void*)OldName);
420
421 // Drop the number of symbols in the table.
422 --SymTabPtr->NumSymbols;
423
424 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000425 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000426 return;
427
428 *SymTabPtrPtr = 0;
429 delete [] Symbols;
430 delete SymTabPtr;
431}
Chris Lattner688506d2003-08-14 18:35:27 +0000432
Chris Lattner54266522004-11-20 23:57:07 +0000433//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000434// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000435//
Chris Lattner688506d2003-08-14 18:35:27 +0000436namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000437 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
438 /// used to output functions to memory for execution.
439 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000440 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000441
Chris Lattner6125fdd2003-05-09 03:30:07 +0000442 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000443 // save BufferBegin/BufferEnd/CurBufferPtr here.
444 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000445
Chris Lattner5be478f2004-11-20 03:46:14 +0000446 /// Relocations - These are the relocations that the function needs, as
447 /// emitted.
448 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000449
450 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
451 /// It is filled in by the StartMachineBasicBlock callback and queried by
452 /// the getMachineBasicBlockAddress callback.
453 std::vector<intptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000454
Chris Lattner239862c2006-02-09 04:49:59 +0000455 /// ConstantPool - The constant pool for the current function.
456 ///
457 MachineConstantPool *ConstantPool;
458
459 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
460 ///
461 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000462
Nate Begeman019f8512006-09-10 23:03:44 +0000463 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000464 ///
465 MachineJumpTableInfo *JumpTable;
466
467 /// JumpTableBase - A pointer to the first entry in the jump table.
468 ///
469 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000470
Chris Lattnere7484012007-02-24 02:57:03 +0000471 /// Resolver - This contains info about the currently resolved functions.
472 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000473
474 /// DE - The dwarf emitter for the jit.
475 JITDwarfEmitter *DE;
476
477 /// LabelLocations - This vector is a mapping from Label ID's to their
478 /// address.
479 std::vector<intptr_t> LabelLocations;
480
481 /// MMI - Machine module info for exception informations
482 MachineModuleInfo* MMI;
483
Dale Johannesendd947ea2008-08-07 01:30:15 +0000484 // GVSet - a set to keep track of which globals have been seen
485 std::set<const GlobalVariable*> GVSet;
486
Chris Lattnere7484012007-02-24 02:57:03 +0000487 public:
Chris Lattner9f2f1422007-12-06 01:08:09 +0000488 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
489 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000490 if (jit.getJITInfo().needsGOT()) {
491 MemMgr->AllocateGOT();
492 DOUT << "JIT is managing a GOT\n";
493 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000494
495 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000496 }
497 ~JITEmitter() {
498 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000499 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000500 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000501
502 /// classof - Methods for support type inquiry through isa, cast, and
503 /// dyn_cast:
504 ///
505 static inline bool classof(const JITEmitter*) { return true; }
506 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000507
508 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000509
510 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000511 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000512
513 void emitConstantPool(MachineConstantPool *MCP);
514 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000515 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000516
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000517 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
518 unsigned Alignment = 1);
519 virtual void* finishFunctionStub(const GlobalValue *F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000520
Chris Lattner5be478f2004-11-20 03:46:14 +0000521 virtual void addRelocation(const MachineRelocation &MR) {
522 Relocations.push_back(MR);
523 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000524
525 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
526 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
527 MBBLocations.resize((MBB->getNumber()+1)*2);
528 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
529 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000530
Chris Lattnerb4432f32006-05-03 17:10:41 +0000531 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
532 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000533
Chris Lattnerb4432f32006-05-03 17:10:41 +0000534 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
535 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
536 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
537 return MBBLocations[MBB->getNumber()];
538 }
539
Chris Lattnere993cc22006-05-11 23:08:08 +0000540 /// deallocateMemForFunction - Deallocate all memory for the specified
541 /// function body.
542 void deallocateMemForFunction(Function *F) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000543 MemMgr->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000544 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000545
546 virtual void emitLabel(uint64_t LabelID) {
547 if (LabelLocations.size() <= LabelID)
548 LabelLocations.resize((LabelID+1)*2);
549 LabelLocations[LabelID] = getCurrentPCValue();
550 }
551
552 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
553 assert(LabelLocations.size() > (unsigned)LabelID &&
554 LabelLocations[LabelID] && "Label not emitted!");
555 return LabelLocations[LabelID];
556 }
557
558 virtual void setModuleInfo(MachineModuleInfo* Info) {
559 MMI = Info;
560 if (ExceptionHandling) DE->setModuleInfo(Info);
561 }
562
Chris Lattner54266522004-11-20 23:57:07 +0000563 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000564 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000565 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
566 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000567 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
568 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
569 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
570 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000571 };
572}
573
Chris Lattner166f2262004-11-22 22:00:25 +0000574void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
575 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000576 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
577 /// FIXME: If we straightened things out, this could actually emit the
578 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000579 return TheJIT->getOrEmitGlobalVariable(GV);
580 }
Chris Lattner18e04592008-06-25 20:21:35 +0000581 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000582 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000583
584 // If we have already compiled the function, return a pointer to its body.
585 Function *F = cast<Function>(V);
586 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
587 if (ResultPtr) return ResultPtr;
588
Gabor Greifa99be512007-07-05 17:07:56 +0000589 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattner54266522004-11-20 23:57:07 +0000590 // If this is an external function pointer, we can force the JIT to
591 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000592 if (DoesntNeedStub)
593 return TheJIT->getPointerToFunction(F);
594
Chris Lattnere7484012007-02-24 02:57:03 +0000595 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000596 }
597
Chris Lattner5e225582004-11-21 03:37:42 +0000598 // Okay, the function has not been compiled yet, if the target callback
599 // mechanism is capable of rewriting the instruction directly, prefer to do
600 // that instead of emitting a stub.
601 if (DoesntNeedStub)
Chris Lattnere7484012007-02-24 02:57:03 +0000602 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000603
Chris Lattner54266522004-11-20 23:57:07 +0000604 // Otherwise, we have to emit a lazy resolving stub.
Chris Lattnere7484012007-02-24 02:57:03 +0000605 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000606}
607
Evan Chengbe8c03f2008-01-04 10:46:51 +0000608void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
609 bool DoesntNeedStub) {
610 // Make sure GV is emitted first.
611 // FIXME: For now, if the GV is an external function we force the JIT to
612 // compile it so the lazy pointer will contain the fully resolved address.
613 void *GVAddress = getPointerToGlobal(V, Reference, true);
614 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
615}
616
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000617static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
618 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
619 if (Constants.empty()) return 0;
620
621 MachineConstantPoolEntry CPE = Constants.back();
622 unsigned Size = CPE.Offset;
623 const Type *Ty = CPE.isMachineConstantPoolEntry()
624 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
625 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
626 return Size;
627}
628
629static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
630 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
631 if (JT.empty()) return 0;
632
633 unsigned NumEntries = 0;
634 for (unsigned i = 0, e = JT.size(); i != e; ++i)
635 NumEntries += JT[i].MBBs.size();
636
637 unsigned EntrySize = MJTI->getEntrySize();
638
639 return NumEntries * EntrySize;
640}
641
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000642static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000643 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000644 // Since we do not know where the buffer will be allocated, be pessimistic.
645 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000646}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000647
Dale Johannesendd947ea2008-08-07 01:30:15 +0000648/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
649/// into the running total Size.
650
651unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
652 const Type *ElTy = GV->getType()->getElementType();
653 size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
654 size_t GVAlign =
655 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
656 DOUT << "Adding in size " << GVSize << " alignment " << GVAlign;
657 DEBUG(GV->dump());
658 // Assume code section ends with worst possible alignment, so first
659 // variable needs maximal padding.
660 if (Size==0)
661 Size = 1;
662 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
663 Size += GVSize;
664 return Size;
665}
666
667/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
668/// but are referenced from the constant; put them in GVSet and add their
669/// size into the running total Size.
670
671unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
672 unsigned Size) {
673 // If its undefined, return the garbage.
674 if (isa<UndefValue>(C))
675 return Size;
676
677 // If the value is a ConstantExpr
678 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
679 Constant *Op0 = CE->getOperand(0);
680 switch (CE->getOpcode()) {
681 case Instruction::GetElementPtr:
682 case Instruction::Trunc:
683 case Instruction::ZExt:
684 case Instruction::SExt:
685 case Instruction::FPTrunc:
686 case Instruction::FPExt:
687 case Instruction::UIToFP:
688 case Instruction::SIToFP:
689 case Instruction::FPToUI:
690 case Instruction::FPToSI:
691 case Instruction::PtrToInt:
692 case Instruction::IntToPtr:
693 case Instruction::BitCast: {
694 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
695 break;
696 }
697 case Instruction::Add:
698 case Instruction::Sub:
699 case Instruction::Mul:
700 case Instruction::UDiv:
701 case Instruction::SDiv:
702 case Instruction::URem:
703 case Instruction::SRem:
704 case Instruction::And:
705 case Instruction::Or:
706 case Instruction::Xor: {
707 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
708 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
709 break;
710 }
711 default: {
712 cerr << "ConstantExpr not handled: " << *CE << "\n";
713 abort();
714 }
715 }
716 }
717
718 if (C->getType()->getTypeID() == Type::PointerTyID)
719 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
720 if (GVSet.insert(GV).second)
721 Size = addSizeOfGlobal(GV, Size);
722
723 return Size;
724}
725
726/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
727/// but are referenced from the given initializer.
728
729unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
730 unsigned Size) {
731 if (!isa<UndefValue>(Init) &&
732 !isa<ConstantVector>(Init) &&
733 !isa<ConstantAggregateZero>(Init) &&
734 !isa<ConstantArray>(Init) &&
735 !isa<ConstantStruct>(Init) &&
736 Init->getType()->isFirstClassType())
737 Size = addSizeOfGlobalsInConstantVal(Init, Size);
738 return Size;
739}
740
741/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
742/// globals; then walk the initializers of those globals looking for more.
743/// If their size has not been considered yet, add it into the running total
744/// Size.
745
746unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
747 unsigned Size = 0;
748 GVSet.clear();
749
750 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
751 MBB != E; ++MBB) {
752 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
753 I != E; ++I) {
754 const TargetInstrDesc &Desc = I->getDesc();
755 const MachineInstr &MI = *I;
756 unsigned NumOps = Desc.getNumOperands();
757 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
758 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000759 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000760 GlobalValue* V = MO.getGlobal();
761 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
762 if (!GV)
763 continue;
764 // If seen in previous function, it will have an entry here.
765 if (TheJIT->getPointerToGlobalIfAvailable(GV))
766 continue;
767 // If seen earlier in this function, it will have an entry here.
768 // FIXME: it should be possible to combine these tables, by
769 // assuming the addresses of the new globals in this module
770 // start at 0 (or something) and adjusting them after codegen
771 // complete. Another possibility is to grab a marker bit in GV.
772 if (GVSet.insert(GV).second)
773 // A variable as yet unseen. Add in its size.
774 Size = addSizeOfGlobal(GV, Size);
775 }
776 }
777 }
778 }
779 DOUT << "About to look through initializers\n";
780 // Look for more globals that are referenced only from initializers.
781 // GVSet.end is computed each time because the set can grow as we go.
782 for (std::set<const GlobalVariable *>::iterator I = GVSet.begin();
783 I != GVSet.end(); I++) {
784 const GlobalVariable* GV = *I;
785 if (GV->hasInitializer())
786 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
787 }
788
789 return Size;
790}
791
Chris Lattner166f2262004-11-22 22:00:25 +0000792void JITEmitter::startFunction(MachineFunction &F) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000793 uintptr_t ActualSize = 0;
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000794 if (MemMgr->NeedsExactSize()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000795 DOUT << "ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000796 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
797 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
798 MachineConstantPool *MCP = F.getConstantPool();
799
800 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000801 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000802
803 // Add the alignment of the constant pool
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000804 ActualSize = RoundUpToAlign(ActualSize,
805 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000806
807 // Add the constant pool size
808 ActualSize += GetConstantPoolSizeInBytes(MCP);
809
810 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000811 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000812
813 // Add the jump table size
814 ActualSize += GetJumpTableSizeInBytes(MJTI);
815
816 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000817 ActualSize = RoundUpToAlign(ActualSize,
818 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000819
820 // Add the function size
821 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000822
823 DOUT << "ActualSize before globals " << ActualSize << "\n";
824 // Add the size of the globals that will be allocated after this function.
825 // These are all the ones referenced from this function that were not
826 // previously allocated.
827 ActualSize += GetSizeOfGlobalsInBytes(F);
828 DOUT << "ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000829 }
830
Chris Lattner8907b4b2007-12-05 23:39:57 +0000831 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
832 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000833 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000834
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000835 // Ensure the constant pool/jump table info is at least 4-byte aligned.
836 emitAlignment(16);
837
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000838 emitConstantPool(F.getConstantPool());
839 initJumpTableInfo(F.getJumpTableInfo());
840
841 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000842 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000843 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000844
Chris Lattnerb4432f32006-05-03 17:10:41 +0000845 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000846}
847
Chris Lattner43b429b2006-05-02 18:27:26 +0000848bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000849 if (CurBufferPtr == BufferEnd) {
850 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000851 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000852 abort();
853 }
854
Jim Laskeyb92767a2006-12-14 22:53:42 +0000855 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000856
Chris Lattnera8279532006-06-16 18:09:26 +0000857 // FnStart is the start of the text, not the start of the constant pool and
858 // other per-function data.
859 unsigned char *FnStart =
860 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000861
Chris Lattner5be478f2004-11-20 03:46:14 +0000862 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000863 NumRelos += Relocations.size();
864
Chris Lattner5be478f2004-11-20 03:46:14 +0000865 // Resolve the relocations to concrete pointers.
866 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
867 MachineRelocation &MR = Relocations[i];
868 void *ResultPtr;
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000869 if (MR.isString()) {
Chris Lattner5be478f2004-11-20 03:46:14 +0000870 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
Misha Brukmanf976c852005-04-21 22:55:34 +0000871
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000872 // If the target REALLY wants a stub for this function, emit it now.
Evan Cheng02aabbf2008-01-03 02:56:28 +0000873 if (!MR.doesntNeedStub())
Chris Lattnere7484012007-02-24 02:57:03 +0000874 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000875 } else if (MR.isGlobalValue()) {
Chris Lattner5e225582004-11-21 03:37:42 +0000876 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
Chris Lattner43b429b2006-05-02 18:27:26 +0000877 BufferBegin+MR.getMachineCodeOffset(),
Evan Cheng02aabbf2008-01-03 02:56:28 +0000878 MR.doesntNeedStub());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000879 } else if (MR.isGlobalValueLazyPtr()) {
880 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
881 BufferBegin+MR.getMachineCodeOffset(),
882 MR.doesntNeedStub());
Evan Chengf141cc42006-07-27 18:21:10 +0000883 } else if (MR.isBasicBlock()) {
884 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
Jim Laskeyacd80ac2006-12-14 19:17:33 +0000885 } else if (MR.isConstantPoolIndex()) {
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000886 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Evan Cheng52b510b2006-06-23 01:02:37 +0000887 } else {
888 assert(MR.isJumpTableIndex());
889 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000890 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000891
Chris Lattner5be478f2004-11-20 03:46:14 +0000892 MR.setResultPointer(ResultPtr);
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000893
Andrew Lenharth6a974612005-07-28 12:44:13 +0000894 // if we are managing the GOT and the relocation wants an index,
895 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000896 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000897 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000898 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000899 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Bill Wendling832171c2006-12-07 20:04:42 +0000900 DOUT << "GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000901 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000902 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000903 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000904 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000905 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000906 }
907
Chris Lattner43b429b2006-05-02 18:27:26 +0000908 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000909 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000910 }
911
Dale Johannesendd947ea2008-08-07 01:30:15 +0000912 unsigned char *FnEnd = CurBufferPtr;
913
914 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
915 NumBytes += FnEnd-FnStart;
916
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000917 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000918 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000919 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000920 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Bill Wendling832171c2006-12-07 20:04:42 +0000921 DOUT << "GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +0000922 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
923 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000924 }
925 }
926
Evan Cheng55fc2802006-07-25 20:40:54 +0000927 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +0000928 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000929
930 // Add it to the JIT symbol table if the host wants it.
931 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
932 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +0000933
Bill Wendling832171c2006-12-07 20:04:42 +0000934 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
935 << "] Function: " << F.getFunction()->getName()
936 << ": " << (FnEnd-FnStart) << " bytes of text, "
937 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +0000938 Relocations.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +0000939
Evan Chengbc4707a2008-09-18 07:54:21 +0000940 // Mark code region readable and executable if it's not so already.
941 sys::Memory::SetRXPrivilege(FnStart, FnEnd-FnStart);
942
Chris Lattnerc5633c22007-01-20 20:51:43 +0000943#ifndef NDEBUG
Dale Johannesen50dd1d02008-08-11 23:46:25 +0000944 {
945 DOUT << std::hex;
946 int i;
947 unsigned char* q = FnStart;
948 for (i=1; q!=FnEnd; q++, i++) {
949 if (i%8==1)
950 DOUT << "0x" << (long)q << ": ";
951 DOUT<< (unsigned short)*q << " ";
952 if (i%8==0)
953 DOUT<<"\n";
954 }
955 DOUT << std::dec;
Anton Korobeynikovc6551ff2007-03-06 05:32:48 +0000956 if (sys::hasDisassembler())
957 DOUT << "Disassembled code:\n"
958 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Dale Johannesen50dd1d02008-08-11 23:46:25 +0000959 }
Chris Lattnerc5633c22007-01-20 20:51:43 +0000960#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000961 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000962 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000963 SavedBufferBegin = BufferBegin;
964 SavedBufferEnd = BufferEnd;
965 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000966
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000967 if (MemMgr->NeedsExactSize()) {
968 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000969 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000970
971 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
972 ActualSize);
973 BufferEnd = BufferBegin+ActualSize;
974 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +0000975 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
976 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000977 BufferBegin = SavedBufferBegin;
978 BufferEnd = SavedBufferEnd;
979 CurBufferPtr = SavedCurBufferPtr;
980
981 TheJIT->RegisterTable(FrameRegister);
982 }
Evan Cheng252ddfb2008-09-02 08:14:01 +0000983
984 if (MMI)
985 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000986
Chris Lattner43b429b2006-05-02 18:27:26 +0000987 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000988}
989
Chris Lattner166f2262004-11-22 22:00:25 +0000990void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Chris Lattnerfa77d432006-02-09 04:22:52 +0000991 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000992 if (Constants.empty()) return;
993
Evan Chengcd5731d2006-09-12 20:59:59 +0000994 MachineConstantPoolEntry CPE = Constants.back();
995 unsigned Size = CPE.Offset;
996 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +0000997 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +0000998 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000999
Evan Cheng97b8c402008-04-12 00:22:01 +00001000 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1001 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001002 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001003
1004 if (ConstantPoolBase == 0) return; // Buffer overflow.
1005
Evan Cheng97b8c402008-04-12 00:22:01 +00001006 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1007 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1008
Chris Lattner239862c2006-02-09 04:49:59 +00001009 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +00001010 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +00001011 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +00001012 if (Constants[i].isMachineConstantPoolEntry()) {
1013 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001014 cerr << "Initialize memory with machine specific constant pool entry"
1015 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001016 abort();
1017 }
1018 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng97b8c402008-04-12 00:22:01 +00001019 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Chris Lattner1cc08382003-01-13 01:00:12 +00001020 }
1021}
1022
Nate Begeman37efe672006-04-22 18:53:45 +00001023void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1024 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1025 if (JT.empty()) return;
1026
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001027 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001028 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001029 NumEntries += JT[i].MBBs.size();
1030
1031 unsigned EntrySize = MJTI->getEntrySize();
1032
Nate Begeman37efe672006-04-22 18:53:45 +00001033 // Just allocate space for all the jump tables now. We will fix up the actual
1034 // MBB entries in the tables after we emit the code for each block, since then
1035 // we will know the final locations of the MBBs in memory.
1036 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001037 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001038}
1039
Jim Laskeyb92767a2006-12-14 22:53:42 +00001040void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Nate Begeman37efe672006-04-22 18:53:45 +00001041 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001042 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001043
Jim Laskeyb92767a2006-12-14 22:53:42 +00001044 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001045 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1046 // For each jump table, place the offset from the beginning of the table
1047 // to the target address.
1048 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001049
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001050 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1051 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1052 // Store the offset of the basic block for this jump table slot in the
1053 // memory we allocated for the jump table in 'initJumpTableInfo'
1054 intptr_t Base = (intptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001055 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1056 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1057 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1058 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001059 }
1060 } else {
1061 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1062
1063 // For each jump table, map each target in the jump table to the address of
1064 // an emitted MachineBasicBlock.
1065 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1066
1067 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1068 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1069 // Store the address of the basic block for this jump table slot in the
1070 // memory we allocated for the jump table in 'initJumpTableInfo'
1071 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1072 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1073 }
Nate Begeman37efe672006-04-22 18:53:45 +00001074 }
1075}
1076
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +00001077void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
1078 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001079 SavedBufferBegin = BufferBegin;
1080 SavedBufferEnd = BufferEnd;
1081 SavedCurBufferPtr = CurBufferPtr;
1082
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +00001083 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001084 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001085}
1086
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +00001087void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001088 NumBytes += getCurrentPCOffset();
1089 std::swap(SavedBufferBegin, BufferBegin);
1090 BufferEnd = SavedBufferEnd;
1091 CurBufferPtr = SavedCurBufferPtr;
1092 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001093}
1094
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001095// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1096// in the constant pool that was last emitted with the 'emitConstantPool'
1097// method.
1098//
Chris Lattnerb4432f32006-05-03 17:10:41 +00001099intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001100 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001101 "Invalid ConstantPoolIndex!");
Chris Lattner239862c2006-02-09 04:49:59 +00001102 return (intptr_t)ConstantPoolBase +
1103 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001104}
1105
Nate Begeman37efe672006-04-22 18:53:45 +00001106// getJumpTableEntryAddress - Return the address of the JumpTable with index
1107// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1108//
Chris Lattnerb4432f32006-05-03 17:10:41 +00001109intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001110 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1111 assert(Index < JT.size() && "Invalid jump table index!");
1112
1113 unsigned Offset = 0;
1114 unsigned EntrySize = JumpTable->getEntrySize();
1115
1116 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001117 Offset += JT[i].MBBs.size();
1118
1119 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001120
Nate Begemanc34b2272006-04-25 17:46:32 +00001121 return (intptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001122}
1123
Chris Lattnere993cc22006-05-11 23:08:08 +00001124//===----------------------------------------------------------------------===//
1125// Public interface to this file
1126//===----------------------------------------------------------------------===//
1127
Chris Lattner9f2f1422007-12-06 01:08:09 +00001128MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1129 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001130}
1131
Misha Brukmand69c1e62003-07-28 19:09:06 +00001132// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001133// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001134// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1135// need to resolve function(s) that are being mis-codegenerated, so we need to
1136// resolve their addresses at runtime, and this is the way to do it.
1137extern "C" {
1138 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001139 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001140 return TheJIT->getPointerToFunction(F);
1141 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001142 }
1143}
Chris Lattnere993cc22006-05-11 23:08:08 +00001144
1145// getPointerToFunctionOrStub - If the specified function has been
1146// code-gen'd, return a pointer to the function. If not, compile it, or use
1147// a stub to implement lazy compilation if available.
1148//
1149void *JIT::getPointerToFunctionOrStub(Function *F) {
1150 // If we have already code generated the function, just return the address.
1151 if (void *Addr = getPointerToGlobalIfAvailable(F))
1152 return Addr;
1153
Chris Lattnere7484012007-02-24 02:57:03 +00001154 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001155 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1156 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001157 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001158}
1159
1160/// freeMachineCodeForFunction - release machine code memory for given Function.
1161///
1162void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001163
Chris Lattnere993cc22006-05-11 23:08:08 +00001164 // Delete translation for this from the ExecutionEngine, so it will get
1165 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001166 void *OldPtr = updateGlobalMapping(F, 0);
1167
1168 if (OldPtr)
1169 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001170
1171 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001172 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1173 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001174}
1175