blob: 22515f3a82c18b55cb127f35dc1d869fac566828 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// 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.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "jit"
16#include "JIT.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000017#include "JITDwarfEmitter.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000018#include "llvm/Constants.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Module.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000020#include "llvm/DerivedTypes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattnerc8ad39c2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetJITInfo.h"
31#include "llvm/Target/TargetMachine.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000032#include "llvm/Target/TargetOptions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/MutexGuard.h"
35#include "llvm/System/Disassembler.h"
Chris Lattner88f51632008-06-25 17:18:44 +000036#include "llvm/System/Memory.h"
Nicolas Geoffray68847972008-04-18 20:59:31 +000037#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng68e5fc32008-11-07 09:02:17 +000038#include "llvm/ADT/SmallPtrSet.h"
Nate Begeman7b1a8472009-02-18 08:31:02 +000039#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include <algorithm>
Evan Cheng23dbb902008-11-05 23:44:08 +000042#ifndef NDEBUG
43#include <iomanip>
44#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045using namespace llvm;
46
47STATISTIC(NumBytes, "Number of bytes of machine code compiled");
48STATISTIC(NumRelos, "Number of relocations applied");
49static JIT *TheJIT = 0;
50
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051
52//===----------------------------------------------------------------------===//
53// JIT lazy compilation code.
54//
55namespace {
56 class JITResolverState {
57 private:
58 /// FunctionToStubMap - Keep track of the stub created for a particular
59 /// function so that we can reuse them if necessary.
60 std::map<Function*, void*> FunctionToStubMap;
61
62 /// StubToFunctionMap - Keep track of the function that each stub
63 /// corresponds to.
64 std::map<void*, Function*> StubToFunctionMap;
65
Evan Chengb0ebcb42008-11-10 01:52:24 +000066 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Cheng28e7e162008-01-04 10:46:51 +000067 /// particular GlobalVariable so that we can reuse them if necessary.
Evan Chengb0ebcb42008-11-10 01:52:24 +000068 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
Evan Cheng28e7e162008-01-04 10:46:51 +000069
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 public:
71 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return FunctionToStubMap;
74 }
75
76 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return StubToFunctionMap;
79 }
Evan Cheng28e7e162008-01-04 10:46:51 +000080
81 std::map<GlobalValue*, void*>&
Evan Chengb0ebcb42008-11-10 01:52:24 +000082 getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Cheng28e7e162008-01-04 10:46:51 +000083 assert(locked.holds(TheJIT->lock));
Evan Chengb0ebcb42008-11-10 01:52:24 +000084 return GlobalToIndirectSymMap;
Evan Cheng28e7e162008-01-04 10:46:51 +000085 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 };
87
88 /// JITResolver - Keep track of, and resolve, call sites for functions that
89 /// have not yet been compiled.
90 class JITResolver {
91 /// LazyResolverFn - The target lazy resolver function that we actually
92 /// rewrite instructions to use.
93 TargetJITInfo::LazyResolverFn LazyResolverFn;
94
95 JITResolverState state;
96
97 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
98 /// external functions.
99 std::map<void*, void*> ExternalFnToStubMap;
100
101 //map addresses to indexes in the GOT
102 std::map<void*, unsigned> revGOTMap;
103 unsigned nextGOTIndex;
104
105 static JITResolver *TheJITResolver;
106 public:
Dan Gohman40bd38e2008-03-25 22:06:05 +0000107 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 TheJIT = &jit;
109
110 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
111 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
112 TheJITResolver = this;
113 }
114
115 ~JITResolver() {
116 TheJITResolver = 0;
117 }
118
Evan Cheng6e4b7632008-11-13 21:50:50 +0000119 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
120 /// if it has already been created.
121 void *getFunctionStubIfAvailable(Function *F);
122
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begeman7b1a8472009-02-18 08:31:02 +0000124 /// one on demand as needed. If empty is true, create a function stub
125 /// pointing at address 0, to be filled in later.
126 void *getFunctionStub(Function *F, bool empty = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127
128 /// getExternalFunctionStub - Return a stub for the function at the
129 /// specified address, created lazily on demand.
130 void *getExternalFunctionStub(void *FnAddr);
131
Evan Chengb0ebcb42008-11-10 01:52:24 +0000132 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Cheng23c6b642008-11-05 01:50:32 +0000133 /// specified GV address.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000134 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Cheng28e7e162008-01-04 10:46:51 +0000135
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 /// AddCallbackAtLocation - If the target is capable of rewriting an
137 /// instruction without the use of a stub, record the location of the use so
138 /// we know which function is being used at the location.
139 void *AddCallbackAtLocation(Function *F, void *Location) {
140 MutexGuard locked(TheJIT->lock);
141 /// Get the target-specific JIT resolver function.
142 state.getStubToFunctionMap(locked)[Location] = F;
143 return (void*)(intptr_t)LazyResolverFn;
144 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000145
146 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
147 SmallVectorImpl<void*> &Ptrs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148
149 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000150 /// an address. This function only manages slots, it does not manage the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 /// contents of the slots or the memory associated with the GOT.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000152 unsigned getGOTIndexForAddr(void *addr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153
154 /// JITCompilerFn - This function is called to resolve a stub to a compiled
155 /// address. If the LLVM Function corresponding to the stub has not yet
156 /// been compiled, this function compiles it first.
157 static void *JITCompilerFn(void *Stub);
158 };
159}
160
161JITResolver *JITResolver::TheJITResolver = 0;
162
Evan Cheng6e4b7632008-11-13 21:50:50 +0000163/// getFunctionStubIfAvailable - This returns a pointer to a function stub
164/// if it has already been created.
165void *JITResolver::getFunctionStubIfAvailable(Function *F) {
166 MutexGuard locked(TheJIT->lock);
167
168 // If we already have a stub for this function, recycle it.
169 void *&Stub = state.getFunctionToStubMap(locked)[F];
170 return Stub;
171}
172
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173/// getFunctionStub - This returns a pointer to a function stub, creating
174/// one on demand as needed.
Nate Begeman7b1a8472009-02-18 08:31:02 +0000175void *JITResolver::getFunctionStub(Function *F, bool empty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 MutexGuard locked(TheJIT->lock);
177
178 // If we already have a stub for this function, recycle it.
179 void *&Stub = state.getFunctionToStubMap(locked)[F];
180 if (Stub) return Stub;
181
182 // Call the lazy resolver function unless we already KNOW it is an external
183 // function, in which case we just skip the lazy resolution step.
Nate Begeman7b1a8472009-02-18 08:31:02 +0000184 void *Actual = empty ? (void*)0 : (void*)(intptr_t)LazyResolverFn;
Dan Gohman0ae39622009-01-05 05:32:42 +0000185 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186 Actual = TheJIT->getPointerToFunction(F);
187
Dan Gohman0ae39622009-01-05 05:32:42 +0000188 // If we resolved the symbol to a null address (eg. a weak external)
189 // don't emit a stub. Return a null pointer to the application.
190 if (!Actual) return 0;
191 }
192
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 // Otherwise, codegen a new stub. For now, the stub will call the lazy
194 // resolver function.
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000195 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 *TheJIT->getCodeEmitter());
197
198 if (Actual != (void*)(intptr_t)LazyResolverFn) {
199 // If we are getting the stub for an external function, we really want the
200 // address of the stub in the GlobalAddressMap for the JIT, not the address
201 // of the external function.
202 TheJIT->updateGlobalMapping(F, Stub);
203 }
204
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
206 << F->getName() << "'\n";
207
208 // Finally, keep track of the stub-to-Function mapping so that the
209 // JITCompilerFn knows which function to compile!
210 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begeman7b1a8472009-02-18 08:31:02 +0000211
212 // If this is an "empty" stub, then inform the JIT that it will need to
213 // JIT the function so an address can be provided.
214 if (empty)
215 TheJIT->addPendingFunction(F);
216
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 return Stub;
218}
219
Evan Chengb0ebcb42008-11-10 01:52:24 +0000220/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Cheng28e7e162008-01-04 10:46:51 +0000221/// GV address.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000222void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Cheng28e7e162008-01-04 10:46:51 +0000223 MutexGuard locked(TheJIT->lock);
224
225 // If we already have a stub for this global variable, recycle it.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000226 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
227 if (IndirectSym) return IndirectSym;
Evan Cheng28e7e162008-01-04 10:46:51 +0000228
Evan Cheng221548c2008-11-10 23:26:16 +0000229 // Otherwise, codegen a new indirect symbol.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000230 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Cheng23c6b642008-11-05 01:50:32 +0000231 *TheJIT->getCodeEmitter());
Evan Cheng28e7e162008-01-04 10:46:51 +0000232
Evan Chengb0ebcb42008-11-10 01:52:24 +0000233 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Cheng28e7e162008-01-04 10:46:51 +0000234 << GV->getName() << "'\n";
235
Evan Chengb0ebcb42008-11-10 01:52:24 +0000236 return IndirectSym;
Evan Cheng28e7e162008-01-04 10:46:51 +0000237}
238
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239/// getExternalFunctionStub - Return a stub for the function at the
240/// specified address, created lazily on demand.
241void *JITResolver::getExternalFunctionStub(void *FnAddr) {
242 // If we already have a stub for this function, recycle it.
243 void *&Stub = ExternalFnToStubMap[FnAddr];
244 if (Stub) return Stub;
245
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000246 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 *TheJIT->getCodeEmitter());
248
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 DOUT << "JIT: Stub emitted at [" << Stub
250 << "] for external function at '" << FnAddr << "'\n";
251 return Stub;
252}
253
254unsigned JITResolver::getGOTIndexForAddr(void* addr) {
255 unsigned idx = revGOTMap[addr];
256 if (!idx) {
257 idx = ++nextGOTIndex;
258 revGOTMap[addr] = idx;
Evan Cheng7323eb52008-11-07 22:30:29 +0000259 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 }
261 return idx;
262}
263
Nate Begeman7b1a8472009-02-18 08:31:02 +0000264void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
265 SmallVectorImpl<void*> &Ptrs) {
266 MutexGuard locked(TheJIT->lock);
267
268 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
269 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
270
271 for (std::map<Function*,void*>::iterator i = FM.begin(), e = FM.end();
272 i != e; ++i) {
273 Function *F = i->first;
274 if (F->isDeclaration() && F->hasExternalLinkage()) {
275 GVs.push_back(i->first);
276 Ptrs.push_back(i->second);
277 }
278 }
279 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
280 i != e; ++i) {
281 GVs.push_back(i->first);
282 Ptrs.push_back(i->second);
283 }
284}
285
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286/// JITCompilerFn - This function is called when a lazy compilation stub has
287/// been entered. It looks up which function this stub corresponds to, compiles
288/// it if necessary, then returns the resultant function pointer.
289void *JITResolver::JITCompilerFn(void *Stub) {
290 JITResolver &JR = *TheJITResolver;
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000291
292 Function* F = 0;
293 void* ActualPtr = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000295 {
296 // Only lock for getting the Function. The call getPointerToFunction made
297 // in this function might trigger function materializing, which requires
298 // JIT lock to be unlocked.
299 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000301 // The address given to us for the stub may not be exactly right, it might be
302 // a little bit after the stub. As such, use upper_bound to find it.
303 std::map<void*, Function*>::iterator I =
304 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
305 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
306 "This is not a known stub!");
307 F = (--I)->second;
308 ActualPtr = I->first;
309 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310
311 // If we have already code generated the function, just return the address.
312 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
313
314 if (!Result) {
315 // Otherwise we don't have it, do lazy compilation now.
316
317 // If lazy compilation is disabled, emit a useful error message and abort.
318 if (TheJIT->isLazyCompilationDisabled()) {
319 cerr << "LLVM JIT requested to do lazy compilation of function '"
320 << F->getName() << "' when lazy compiles are disabled!\n";
321 abort();
322 }
323
324 // We might like to remove the stub from the StubToFunction map.
325 // We can't do that! Multiple threads could be stuck, waiting to acquire the
326 // lock above. As soon as the 1st function finishes compiling the function,
327 // the next one will be released, and needs to be able to find the function
328 // it needs to call.
329 //JR.state.getStubToFunctionMap(locked).erase(I);
330
331 DOUT << "JIT: Lazily resolving function '" << F->getName()
332 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000333 << ActualPtr << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
335 Result = TheJIT->getPointerToFunction(F);
336 }
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000337
338 // Reacquire the lock to erase the stub in the map.
339 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340
341 // We don't need to reuse this stub in the future, as F is now compiled.
342 JR.state.getFunctionToStubMap(locked).erase(F);
343
344 // FIXME: We could rewrite all references to this stub if we knew them.
345
346 // What we will do is set the compiled function address to map to the
347 // same GOT entry as the stub so that later clients may update the GOT
348 // if they see it still using the stub address.
349 // Note: this is done so the Resolver doesn't have to manage GOT memory
350 // Do this without allocating map space if the target isn't using a GOT
351 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
352 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
353
354 return Result;
355}
356
Chris Lattnerf50e3572008-04-04 05:51:42 +0000357//===----------------------------------------------------------------------===//
358// Function Index Support
359
360// On MacOS we generate an index of currently JIT'd functions so that
361// performance tools can determine a symbol name and accurate code range for a
362// PC value. Because performance tools are generally asynchronous, the code
363// below is written with the hope that it could be interrupted at any time and
364// have useful answers. However, we don't go crazy with atomic operations, we
365// just do a "reasonable effort".
366#ifdef __APPLE__
Evan Cheng4481f762008-05-15 17:31:35 +0000367#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattnerf50e3572008-04-04 05:51:42 +0000368#endif
369
370/// JitSymbolEntry - Each function that is JIT compiled results in one of these
371/// being added to an array of symbols. This indicates the name of the function
372/// as well as the address range it occupies. This allows the client to map
373/// from a PC value to the name of the function.
374struct JitSymbolEntry {
375 const char *FnName; // FnName - a strdup'd string.
376 void *FnStart;
377 intptr_t FnSize;
378};
379
380
381struct JitSymbolTable {
382 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
383 /// pointer is not used right now, but might be used in the future. Consider
384 /// it reserved for future use.
385 JitSymbolTable *NextPtr;
386
387 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
388 /// 'NumSymbols' symbols are valid.
389 JitSymbolEntry *Symbols;
390
391 /// NumSymbols - This indicates the number entries in the Symbols array that
392 /// are valid.
393 unsigned NumSymbols;
394
395 /// NumAllocated - This indicates the amount of space we have in the Symbols
396 /// array. This is a private field that should not be read by external tools.
397 unsigned NumAllocated;
398};
399
400#if ENABLE_JIT_SYMBOL_TABLE
401JitSymbolTable *__jitSymbolTable;
402#endif
403
404static void AddFunctionToSymbolTable(const char *FnName,
405 void *FnStart, intptr_t FnSize) {
406 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
407 JitSymbolTable **SymTabPtrPtr = 0;
408#if !ENABLE_JIT_SYMBOL_TABLE
409 return;
410#else
411 SymTabPtrPtr = &__jitSymbolTable;
412#endif
413
414 // If this is the first entry in the symbol table, add the JitSymbolTable
415 // index.
416 if (*SymTabPtrPtr == 0) {
417 JitSymbolTable *New = new JitSymbolTable();
418 New->NextPtr = 0;
419 New->Symbols = 0;
420 New->NumSymbols = 0;
421 New->NumAllocated = 0;
422 *SymTabPtrPtr = New;
423 }
424
425 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
426
427 // If we have space in the table, reallocate the table.
428 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
429 // If we don't have space, reallocate the table.
Chris Lattnerea0cb7c2008-04-13 07:04:56 +0000430 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattnerf50e3572008-04-04 05:51:42 +0000431 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
432 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
433
434 // Copy the old entries over.
Nate Begeman7b1a8472009-02-18 08:31:02 +0000435 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattnerf50e3572008-04-04 05:51:42 +0000436
437 // Swap the new symbols in, delete the old ones.
438 SymTabPtr->Symbols = NewSymbols;
Chris Lattnerea0cb7c2008-04-13 07:04:56 +0000439 SymTabPtr->NumAllocated = NewSize;
Chris Lattnerf50e3572008-04-04 05:51:42 +0000440 delete [] OldSymbols;
441 }
442
443 // Otherwise, we have enough space, just tack it onto the end of the array.
444 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
445 Entry.FnName = strdup(FnName);
446 Entry.FnStart = FnStart;
447 Entry.FnSize = FnSize;
448 ++SymTabPtr->NumSymbols;
449}
450
451static void RemoveFunctionFromSymbolTable(void *FnStart) {
452 assert(FnStart && "Invalid function pointer");
453 JitSymbolTable **SymTabPtrPtr = 0;
454#if !ENABLE_JIT_SYMBOL_TABLE
455 return;
456#else
457 SymTabPtrPtr = &__jitSymbolTable;
458#endif
459
460 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
461 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
462
463 // Scan the table to find its index. The table is not sorted, so do a linear
464 // scan.
465 unsigned Index;
466 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
467 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
468
469 // Once we have an index, we know to nuke this entry, overwrite it with the
470 // entry at the end of the array, making the last entry redundant.
471 const char *OldName = Symbols[Index].FnName;
472 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
473 free((void*)OldName);
474
475 // Drop the number of symbols in the table.
476 --SymTabPtr->NumSymbols;
477
478 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begeman0751db22008-05-18 19:09:10 +0000479 if (SymTabPtr->NumSymbols != 0)
Chris Lattnerf50e3572008-04-04 05:51:42 +0000480 return;
481
482 *SymTabPtrPtr = 0;
483 delete [] Symbols;
484 delete SymTabPtr;
485}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486
487//===----------------------------------------------------------------------===//
488// JITEmitter code.
489//
490namespace {
491 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
492 /// used to output functions to memory for execution.
493 class JITEmitter : public MachineCodeEmitter {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000494 JITMemoryManager *MemMgr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495
496 // When outputting a function stub in the context of some other function, we
497 // save BufferBegin/BufferEnd/CurBufferPtr here.
498 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
499
500 /// Relocations - These are the relocations that the function needs, as
501 /// emitted.
502 std::vector<MachineRelocation> Relocations;
503
504 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
505 /// It is filled in by the StartMachineBasicBlock callback and queried by
506 /// the getMachineBasicBlockAddress callback.
Evan Cheng6e561c72008-12-10 02:32:19 +0000507 std::vector<uintptr_t> MBBLocations;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508
509 /// ConstantPool - The constant pool for the current function.
510 ///
511 MachineConstantPool *ConstantPool;
512
513 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
514 ///
515 void *ConstantPoolBase;
516
517 /// JumpTable - The jump tables for the current function.
518 ///
519 MachineJumpTableInfo *JumpTable;
520
521 /// JumpTableBase - A pointer to the first entry in the jump table.
522 ///
523 void *JumpTableBase;
Evan Chengaf743252008-01-05 02:26:58 +0000524
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 /// Resolver - This contains info about the currently resolved functions.
526 JITResolver Resolver;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000527
528 /// DE - The dwarf emitter for the jit.
529 JITDwarfEmitter *DE;
530
531 /// LabelLocations - This vector is a mapping from Label ID's to their
532 /// address.
Evan Cheng6e561c72008-12-10 02:32:19 +0000533 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000534
535 /// MMI - Machine module info for exception informations
536 MachineModuleInfo* MMI;
537
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000538 // GVSet - a set to keep track of which globals have been seen
Evan Cheng68e5fc32008-11-07 09:02:17 +0000539 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000540
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 public:
Chris Lattnere44be002007-12-06 01:08:09 +0000542 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
543 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000544 if (jit.getJITInfo().needsGOT()) {
545 MemMgr->AllocateGOT();
546 DOUT << "JIT is managing a GOT\n";
547 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000548
549 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000550 }
551 ~JITEmitter() {
552 delete MemMgr;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000553 if (ExceptionHandling) delete DE;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 }
Evan Cheng89b29a12008-08-20 00:28:12 +0000555
556 /// classof - Methods for support type inquiry through isa, cast, and
557 /// dyn_cast:
558 ///
559 static inline bool classof(const JITEmitter*) { return true; }
560 static inline bool classof(const MachineCodeEmitter*) { return true; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561
562 JITResolver &getJITResolver() { return Resolver; }
563
564 virtual void startFunction(MachineFunction &F);
565 virtual bool finishFunction(MachineFunction &F);
566
567 void emitConstantPool(MachineConstantPool *MCP);
568 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
569 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
570
Evan Cheng2c3267a2008-11-08 08:02:53 +0000571 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000572 unsigned Alignment = 1);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000573 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
574 unsigned StubSize);
Evan Cheng2c3267a2008-11-08 08:02:53 +0000575 virtual void* finishGVStub(const GlobalValue *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576
Nuno Lopes1ab7adc2008-10-21 11:42:16 +0000577 /// allocateSpace - Reserves space in the current block if any, or
578 /// allocate a new one of the given size.
Evan Cheng6e561c72008-12-10 02:32:19 +0000579 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopes1ab7adc2008-10-21 11:42:16 +0000580
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 virtual void addRelocation(const MachineRelocation &MR) {
582 Relocations.push_back(MR);
583 }
584
585 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
586 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
587 MBBLocations.resize((MBB->getNumber()+1)*2);
588 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng7323eb52008-11-07 22:30:29 +0000589 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
590 << (void*) getCurrentPCValue() << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 }
592
Evan Cheng6e561c72008-12-10 02:32:19 +0000593 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
594 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Chengaf743252008-01-05 02:26:58 +0000595
Evan Cheng6e561c72008-12-10 02:32:19 +0000596 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
598 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
599 return MBBLocations[MBB->getNumber()];
600 }
601
602 /// deallocateMemForFunction - Deallocate all memory for the specified
603 /// function body.
604 void deallocateMemForFunction(Function *F) {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000605 MemMgr->deallocateMemForFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000607
608 virtual void emitLabel(uint64_t LabelID) {
609 if (LabelLocations.size() <= LabelID)
610 LabelLocations.resize((LabelID+1)*2);
611 LabelLocations[LabelID] = getCurrentPCValue();
612 }
613
Evan Cheng6e561c72008-12-10 02:32:19 +0000614 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000615 assert(LabelLocations.size() > (unsigned)LabelID &&
616 LabelLocations[LabelID] && "Label not emitted!");
617 return LabelLocations[LabelID];
618 }
619
620 virtual void setModuleInfo(MachineModuleInfo* Info) {
621 MMI = Info;
622 if (ExceptionHandling) DE->setModuleInfo(Info);
623 }
624
Jim Grosbach724b1812008-10-03 16:17:20 +0000625 void setMemoryExecutable(void) {
626 MemMgr->setMemoryExecutable();
627 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000628
629 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbach724b1812008-10-03 16:17:20 +0000630
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 private:
632 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Chengb0ebcb42008-11-10 01:52:24 +0000633 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Cheng221548c2008-11-10 23:26:16 +0000634 bool NoNeedStub);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000635 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
636 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
637 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
638 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 };
640}
641
642void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
643 bool DoesntNeedStub) {
Nate Begeman7b1a8472009-02-18 08:31:02 +0000644 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000646
Chris Lattner44d8ea72008-06-25 20:21:35 +0000647 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikovc7b90912008-09-09 20:05:04 +0000648 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649
650 // If we have already compiled the function, return a pointer to its body.
651 Function *F = cast<Function>(V);
Evan Cheng6e4b7632008-11-13 21:50:50 +0000652 void *ResultPtr;
Evan Cheng45b57b12008-12-10 01:33:59 +0000653 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Evan Cheng6e4b7632008-11-13 21:50:50 +0000654 // Return the function stub if it's already created.
655 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
656 else
657 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 if (ResultPtr) return ResultPtr;
659
Nate Begeman7b1a8472009-02-18 08:31:02 +0000660 // If this is an external function pointer, we can force the JIT to
661 // 'compile' it, which really just adds it to the map.
662 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() && DoesntNeedStub)
663 return TheJIT->getPointerToFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664
Nate Begeman7b1a8472009-02-18 08:31:02 +0000665 // If we are jitting non-lazily but encounter a function that has not been
666 // jitted yet, we need to allocate a blank stub to call the function
667 // once we JIT it and its address is known.
668 if (TheJIT->isLazyCompilationDisabled())
669 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
670 return Resolver.getFunctionStub(F, true);
671
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 // Okay, the function has not been compiled yet, if the target callback
673 // mechanism is capable of rewriting the instruction directly, prefer to do
674 // that instead of emitting a stub.
675 if (DoesntNeedStub)
676 return Resolver.AddCallbackAtLocation(F, Reference);
677
678 // Otherwise, we have to emit a lazy resolving stub.
679 return Resolver.getFunctionStub(F);
680}
681
Evan Chengb0ebcb42008-11-10 01:52:24 +0000682void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Cheng221548c2008-11-10 23:26:16 +0000683 bool NoNeedStub) {
Evan Cheng28e7e162008-01-04 10:46:51 +0000684 // Make sure GV is emitted first.
685 // FIXME: For now, if the GV is an external function we force the JIT to
Evan Chengb0ebcb42008-11-10 01:52:24 +0000686 // compile it so the indirect symbol will contain the fully resolved address.
Evan Cheng28e7e162008-01-04 10:46:51 +0000687 void *GVAddress = getPointerToGlobal(V, Reference, true);
Evan Chengb0ebcb42008-11-10 01:52:24 +0000688 return Resolver.getGlobalValueIndirectSym(V, GVAddress);
Evan Cheng28e7e162008-01-04 10:46:51 +0000689}
690
Nicolas Geoffray68847972008-04-18 20:59:31 +0000691static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
692 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
693 if (Constants.empty()) return 0;
694
695 MachineConstantPoolEntry CPE = Constants.back();
696 unsigned Size = CPE.Offset;
697 const Type *Ty = CPE.isMachineConstantPoolEntry()
698 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000699 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Nicolas Geoffray68847972008-04-18 20:59:31 +0000700 return Size;
701}
702
703static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
704 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
705 if (JT.empty()) return 0;
706
707 unsigned NumEntries = 0;
708 for (unsigned i = 0, e = JT.size(); i != e; ++i)
709 NumEntries += JT[i].MBBs.size();
710
711 unsigned EntrySize = MJTI->getEntrySize();
712
713 return NumEntries * EntrySize;
714}
715
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000716static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffray68847972008-04-18 20:59:31 +0000717 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000718 // Since we do not know where the buffer will be allocated, be pessimistic.
719 return Size + Alignment;
Nicolas Geoffray68847972008-04-18 20:59:31 +0000720}
Evan Cheng28e7e162008-01-04 10:46:51 +0000721
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000722/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
723/// into the running total Size.
724
725unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
726 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000727 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000728 size_t GVAlign =
729 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengd6599362008-11-06 17:46:04 +0000730 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000731 DEBUG(GV->dump());
732 // Assume code section ends with worst possible alignment, so first
733 // variable needs maximal padding.
734 if (Size==0)
735 Size = 1;
736 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
737 Size += GVSize;
738 return Size;
739}
740
741/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
742/// but are referenced from the constant; put them in GVSet and add their
743/// size into the running total Size.
744
745unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
746 unsigned Size) {
747 // If its undefined, return the garbage.
748 if (isa<UndefValue>(C))
749 return Size;
750
751 // If the value is a ConstantExpr
752 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
753 Constant *Op0 = CE->getOperand(0);
754 switch (CE->getOpcode()) {
755 case Instruction::GetElementPtr:
756 case Instruction::Trunc:
757 case Instruction::ZExt:
758 case Instruction::SExt:
759 case Instruction::FPTrunc:
760 case Instruction::FPExt:
761 case Instruction::UIToFP:
762 case Instruction::SIToFP:
763 case Instruction::FPToUI:
764 case Instruction::FPToSI:
765 case Instruction::PtrToInt:
766 case Instruction::IntToPtr:
767 case Instruction::BitCast: {
768 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
769 break;
770 }
771 case Instruction::Add:
772 case Instruction::Sub:
773 case Instruction::Mul:
774 case Instruction::UDiv:
775 case Instruction::SDiv:
776 case Instruction::URem:
777 case Instruction::SRem:
778 case Instruction::And:
779 case Instruction::Or:
780 case Instruction::Xor: {
781 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
782 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
783 break;
784 }
785 default: {
786 cerr << "ConstantExpr not handled: " << *CE << "\n";
787 abort();
788 }
789 }
790 }
791
792 if (C->getType()->getTypeID() == Type::PointerTyID)
793 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng68e5fc32008-11-07 09:02:17 +0000794 if (GVSet.insert(GV))
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000795 Size = addSizeOfGlobal(GV, Size);
796
797 return Size;
798}
799
800/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
801/// but are referenced from the given initializer.
802
803unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
804 unsigned Size) {
805 if (!isa<UndefValue>(Init) &&
806 !isa<ConstantVector>(Init) &&
807 !isa<ConstantAggregateZero>(Init) &&
808 !isa<ConstantArray>(Init) &&
809 !isa<ConstantStruct>(Init) &&
810 Init->getType()->isFirstClassType())
811 Size = addSizeOfGlobalsInConstantVal(Init, Size);
812 return Size;
813}
814
815/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
816/// globals; then walk the initializers of those globals looking for more.
817/// If their size has not been considered yet, add it into the running total
818/// Size.
819
820unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
821 unsigned Size = 0;
822 GVSet.clear();
823
824 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
825 MBB != E; ++MBB) {
826 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
827 I != E; ++I) {
828 const TargetInstrDesc &Desc = I->getDesc();
829 const MachineInstr &MI = *I;
830 unsigned NumOps = Desc.getNumOperands();
831 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
832 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000833 if (MO.isGlobal()) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000834 GlobalValue* V = MO.getGlobal();
835 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
836 if (!GV)
837 continue;
838 // If seen in previous function, it will have an entry here.
839 if (TheJIT->getPointerToGlobalIfAvailable(GV))
840 continue;
841 // If seen earlier in this function, it will have an entry here.
842 // FIXME: it should be possible to combine these tables, by
843 // assuming the addresses of the new globals in this module
844 // start at 0 (or something) and adjusting them after codegen
845 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng68e5fc32008-11-07 09:02:17 +0000846 if (GVSet.insert(GV))
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000847 // A variable as yet unseen. Add in its size.
848 Size = addSizeOfGlobal(GV, Size);
849 }
850 }
851 }
852 }
Evan Chengd6599362008-11-06 17:46:04 +0000853 DOUT << "JIT: About to look through initializers\n";
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000854 // Look for more globals that are referenced only from initializers.
855 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng68e5fc32008-11-07 09:02:17 +0000856 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000857 I != GVSet.end(); I++) {
858 const GlobalVariable* GV = *I;
859 if (GV->hasInitializer())
860 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
861 }
862
863 return Size;
864}
865
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengd6599362008-11-06 17:46:04 +0000867 DOUT << "JIT: Starting CodeGen of Function "
868 << F.getFunction()->getName() << "\n";
869
Nicolas Geoffray68847972008-04-18 20:59:31 +0000870 uintptr_t ActualSize = 0;
Jim Grosbach724b1812008-10-03 16:17:20 +0000871 // Set the memory writable, if it's not already
872 MemMgr->setMemoryWritable();
Nicolas Geoffrayf748af22008-04-20 17:44:19 +0000873 if (MemMgr->NeedsExactSize()) {
Evan Chengd6599362008-11-06 17:46:04 +0000874 DOUT << "JIT: ExactSize\n";
Nicolas Geoffray68847972008-04-18 20:59:31 +0000875 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
876 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
877 MachineConstantPool *MCP = F.getConstantPool();
878
879 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000880 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffray68847972008-04-18 20:59:31 +0000881
882 // Add the alignment of the constant pool
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000883 ActualSize = RoundUpToAlign(ActualSize,
884 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000885
886 // Add the constant pool size
887 ActualSize += GetConstantPoolSizeInBytes(MCP);
888
889 // Add the aligment of the jump table info
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000890 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000891
892 // Add the jump table size
893 ActualSize += GetJumpTableSizeInBytes(MJTI);
894
895 // Add the alignment for the function
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000896 ActualSize = RoundUpToAlign(ActualSize,
897 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffray68847972008-04-18 20:59:31 +0000898
899 // Add the function size
900 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000901
Evan Chengd6599362008-11-06 17:46:04 +0000902 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000903 // Add the size of the globals that will be allocated after this function.
904 // These are all the ones referenced from this function that were not
905 // previously allocated.
906 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengd6599362008-11-06 17:46:04 +0000907 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffray68847972008-04-18 20:59:31 +0000908 }
909
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000910 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
911 ActualSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 BufferEnd = BufferBegin+ActualSize;
913
914 // Ensure the constant pool/jump table info is at least 4-byte aligned.
915 emitAlignment(16);
916
917 emitConstantPool(F.getConstantPool());
918 initJumpTableInfo(F.getJumpTableInfo());
919
920 // About to start emitting the machine code for the function.
921 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
922 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
923
924 MBBLocations.clear();
925}
926
927bool JITEmitter::finishFunction(MachineFunction &F) {
928 if (CurBufferPtr == BufferEnd) {
929 // FIXME: Allocate more space, then try again.
930 cerr << "JIT: Ran out of space for generated machine code!\n";
931 abort();
932 }
933
934 emitJumpTableInfo(F.getJumpTableInfo());
935
936 // FnStart is the start of the text, not the start of the constant pool and
937 // other per-function data.
938 unsigned char *FnStart =
939 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940
941 if (!Relocations.empty()) {
942 NumRelos += Relocations.size();
943
944 // Resolve the relocations to concrete pointers.
945 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
946 MachineRelocation &MR = Relocations[i];
Evan Cheng1cf55bb2008-11-03 07:14:02 +0000947 void *ResultPtr = 0;
Evan Chengc5fe01b2008-10-29 23:54:46 +0000948 if (!MR.letTargetResolve()) {
Evan Cheng2976cd12008-11-08 07:37:34 +0000949 if (MR.isExternalSymbol()) {
Dan Gohman0ae39622009-01-05 05:32:42 +0000950 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
951 false);
Evan Cheng2976cd12008-11-08 07:37:34 +0000952 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Cheng56d1b582008-11-08 07:22:53 +0000953 << ResultPtr << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954
Evan Chengc5fe01b2008-10-29 23:54:46 +0000955 // If the target REALLY wants a stub for this function, emit it now.
956 if (!MR.doesntNeedStub())
957 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
958 } else if (MR.isGlobalValue()) {
959 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
960 BufferBegin+MR.getMachineCodeOffset(),
961 MR.doesntNeedStub());
Evan Chengb0ebcb42008-11-10 01:52:24 +0000962 } else if (MR.isIndirectSymbol()) {
963 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Cheng28e7e162008-01-04 10:46:51 +0000964 BufferBegin+MR.getMachineCodeOffset(),
965 MR.doesntNeedStub());
Evan Chengc5fe01b2008-10-29 23:54:46 +0000966 } else if (MR.isBasicBlock()) {
967 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
968 } else if (MR.isConstantPoolIndex()) {
969 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
970 } else {
971 assert(MR.isJumpTableIndex());
972 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
973 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974
Evan Chengc5fe01b2008-10-29 23:54:46 +0000975 MR.setResultPointer(ResultPtr);
976 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977
978 // if we are managing the GOT and the relocation wants an index,
979 // give it one
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000980 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
982 MR.setGOTIndex(idx);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000983 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengd6599362008-11-06 17:46:04 +0000984 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000985 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 << "\n";
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000987 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 }
989 }
990 }
991
992 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000993 Relocations.size(), MemMgr->getGOTBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 }
995
996 // Update the GOT entry for F to point to the new code.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000997 if (MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000999 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengd6599362008-11-06 17:46:04 +00001000 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001001 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1002 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 }
1004 }
1005
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001006 unsigned char *FnEnd = CurBufferPtr;
1007
1008 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Evan Cheng6e561c72008-12-10 02:32:19 +00001009
1010 if (CurBufferPtr == BufferEnd) {
1011 // FIXME: Allocate more space, then try again.
1012 cerr << "JIT: Ran out of space for generated machine code!\n";
1013 abort();
1014 }
1015
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001016 BufferBegin = CurBufferPtr = 0;
1017 NumBytes += FnEnd-FnStart;
1018
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 // Invalidate the icache if necessary.
Chris Lattner88f51632008-06-25 17:18:44 +00001020 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattnerf50e3572008-04-04 05:51:42 +00001021
1022 // Add it to the JIT symbol table if the host wants it.
1023 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1024 FnStart, FnEnd-FnStart);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025
1026 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1027 << "] Function: " << F.getFunction()->getName()
1028 << ": " << (FnEnd-FnStart) << " bytes of text, "
1029 << Relocations.size() << " relocations\n";
1030 Relocations.clear();
1031
Evan Chengb83f6972008-09-18 07:54:21 +00001032 // Mark code region readable and executable if it's not so already.
Jim Grosbach724b1812008-10-03 16:17:20 +00001033 MemMgr->setMemoryExecutable();
Evan Chengb83f6972008-09-18 07:54:21 +00001034
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035#ifndef NDEBUG
Evan Cheng23dbb902008-11-05 23:44:08 +00001036 {
Evan Chengb81ef082008-11-12 08:22:43 +00001037 if (sys::hasDisassembler()) {
1038 DOUT << "JIT: Disassembled code:\n";
Evan Chengd6599362008-11-06 17:46:04 +00001039 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chengb81ef082008-11-12 08:22:43 +00001040 } else {
1041 DOUT << "JIT: Binary code:\n";
Evan Cheng23dbb902008-11-05 23:44:08 +00001042 DOUT << std::hex;
Evan Cheng23dbb902008-11-05 23:44:08 +00001043 unsigned char* q = FnStart;
Evan Chengb81ef082008-11-12 08:22:43 +00001044 for (int i = 0; q < FnEnd; q += 4, ++i) {
1045 if (i == 4)
1046 i = 0;
1047 if (i == 0)
1048 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1049 << (long)(q - FnStart) << ": ";
1050 bool Done = false;
1051 for (int j = 3; j >= 0; --j) {
1052 if (q + j >= FnEnd)
1053 Done = true;
1054 else
1055 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1056 }
1057 if (Done)
1058 break;
1059 DOUT << ' ';
1060 if (i == 3)
Evan Chengca323d72008-11-06 01:18:29 +00001061 DOUT << '\n';
Evan Cheng23dbb902008-11-05 23:44:08 +00001062 }
1063 DOUT << std::dec;
Evan Chengca323d72008-11-06 01:18:29 +00001064 DOUT<< '\n';
Evan Cheng23dbb902008-11-05 23:44:08 +00001065 }
1066 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067#endif
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001068 if (ExceptionHandling) {
Nicolas Geoffray68847972008-04-18 20:59:31 +00001069 uintptr_t ActualSize = 0;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001070 SavedBufferBegin = BufferBegin;
1071 SavedBufferEnd = BufferEnd;
1072 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffray68847972008-04-18 20:59:31 +00001073
Nicolas Geoffrayf748af22008-04-20 17:44:19 +00001074 if (MemMgr->NeedsExactSize()) {
1075 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffray68847972008-04-18 20:59:31 +00001076 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001077
1078 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1079 ActualSize);
1080 BufferEnd = BufferBegin+ActualSize;
1081 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner3d46fe02008-03-07 20:05:43 +00001082 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1083 FrameRegister);
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001084 BufferBegin = SavedBufferBegin;
1085 BufferEnd = SavedBufferEnd;
1086 CurBufferPtr = SavedCurBufferPtr;
1087
1088 TheJIT->RegisterTable(FrameRegister);
1089 }
Evan Chengca346e62008-09-02 08:14:01 +00001090
1091 if (MMI)
1092 MMI->EndFunction();
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001093
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 return false;
1095}
1096
Evan Cheng6e561c72008-12-10 02:32:19 +00001097void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001098 if (BufferBegin)
1099 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1100
1101 // create a new memory block if there is no active one.
1102 // care must be taken so that BufferBegin is invalidated when a
1103 // block is trimmed
1104 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1105 BufferEnd = BufferBegin+Size;
1106 return CurBufferPtr;
1107}
1108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001110 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbachbad01432008-10-30 23:44:39 +00001111 return;
Evan Cheng68e5fc32008-11-07 09:02:17 +00001112
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1114 if (Constants.empty()) return;
1115
1116 MachineConstantPoolEntry CPE = Constants.back();
1117 unsigned Size = CPE.Offset;
1118 const Type *Ty = CPE.isMachineConstantPoolEntry()
1119 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001120 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121
Evan Cheng71c58872008-04-12 00:22:01 +00001122 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1123 ConstantPoolBase = allocateSpace(Size, Align);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 ConstantPool = MCP;
1125
1126 if (ConstantPoolBase == 0) return; // Buffer overflow.
1127
Evan Cheng71c58872008-04-12 00:22:01 +00001128 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1129 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1130
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 // Initialize the memory for all of the constant pool entries.
1132 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1133 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1134 if (Constants[i].isMachineConstantPoolEntry()) {
1135 // FIXME: add support to lower machine constant pool values into bytes!
1136 cerr << "Initialize memory with machine specific constant pool entry"
1137 << " has not been implemented!\n";
1138 abort();
1139 }
1140 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng71c58872008-04-12 00:22:01 +00001141 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 }
1143}
1144
1145void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001146 if (TheJIT->getJITInfo().hasCustomJumpTables())
1147 return;
1148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1150 if (JT.empty()) return;
1151
1152 unsigned NumEntries = 0;
1153 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1154 NumEntries += JT[i].MBBs.size();
1155
1156 unsigned EntrySize = MJTI->getEntrySize();
1157
1158 // Just allocate space for all the jump tables now. We will fix up the actual
1159 // MBB entries in the tables after we emit the code for each block, since then
1160 // we will know the final locations of the MBBs in memory.
1161 JumpTable = MJTI;
1162 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1163}
1164
1165void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001166 if (TheJIT->getJITInfo().hasCustomJumpTables())
1167 return;
1168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1170 if (JT.empty() || JumpTableBase == 0) return;
1171
1172 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1173 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1174 // For each jump table, place the offset from the beginning of the table
1175 // to the target address.
1176 int *SlotPtr = (int*)JumpTableBase;
1177
1178 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1179 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1180 // Store the offset of the basic block for this jump table slot in the
1181 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng6e561c72008-12-10 02:32:19 +00001182 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Chengaf743252008-01-05 02:26:58 +00001183 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng6e561c72008-12-10 02:32:19 +00001184 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Chengaf743252008-01-05 02:26:58 +00001185 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1186 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 }
1188 } else {
1189 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1190
1191 // For each jump table, map each target in the jump table to the address of
1192 // an emitted MachineBasicBlock.
1193 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1194
1195 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1196 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1197 // Store the address of the basic block for this jump table slot in the
1198 // memory we allocated for the jump table in 'initJumpTableInfo'
1199 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1200 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1201 }
1202 }
1203}
1204
Evan Cheng2c3267a2008-11-08 08:02:53 +00001205void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1206 unsigned Alignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 SavedBufferBegin = BufferBegin;
1208 SavedBufferEnd = BufferEnd;
1209 SavedCurBufferPtr = CurBufferPtr;
1210
Evan Cheng2c3267a2008-11-08 08:02:53 +00001211 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212 BufferEnd = BufferBegin+StubSize+1;
1213}
1214
Nate Begeman7b1a8472009-02-18 08:31:02 +00001215void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1216 unsigned StubSize) {
1217 SavedBufferBegin = BufferBegin;
1218 SavedBufferEnd = BufferEnd;
1219 SavedCurBufferPtr = CurBufferPtr;
1220
1221 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1222 BufferEnd = BufferBegin+StubSize+1;
1223}
1224
Evan Cheng2c3267a2008-11-08 08:02:53 +00001225void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 NumBytes += getCurrentPCOffset();
1227 std::swap(SavedBufferBegin, BufferBegin);
1228 BufferEnd = SavedBufferEnd;
1229 CurBufferPtr = SavedCurBufferPtr;
1230 return SavedBufferBegin;
1231}
1232
1233// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1234// in the constant pool that was last emitted with the 'emitConstantPool'
1235// method.
1236//
Evan Cheng6e561c72008-12-10 02:32:19 +00001237uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 assert(ConstantNum < ConstantPool->getConstants().size() &&
1239 "Invalid ConstantPoolIndex!");
Evan Cheng6e561c72008-12-10 02:32:19 +00001240 return (uintptr_t)ConstantPoolBase +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 ConstantPool->getConstants()[ConstantNum].Offset;
1242}
1243
1244// getJumpTableEntryAddress - Return the address of the JumpTable with index
1245// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1246//
Evan Cheng6e561c72008-12-10 02:32:19 +00001247uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1249 assert(Index < JT.size() && "Invalid jump table index!");
1250
1251 unsigned Offset = 0;
1252 unsigned EntrySize = JumpTable->getEntrySize();
1253
1254 for (unsigned i = 0; i < Index; ++i)
1255 Offset += JT[i].MBBs.size();
1256
1257 Offset *= EntrySize;
1258
Evan Cheng6e561c72008-12-10 02:32:19 +00001259 return (uintptr_t)((char *)JumpTableBase + Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260}
1261
1262//===----------------------------------------------------------------------===//
1263// Public interface to this file
1264//===----------------------------------------------------------------------===//
1265
Chris Lattnere44be002007-12-06 01:08:09 +00001266MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1267 return new JITEmitter(jit, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268}
1269
1270// getPointerToNamedFunction - This function is used as a global wrapper to
1271// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1272// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1273// need to resolve function(s) that are being mis-codegenerated, so we need to
1274// resolve their addresses at runtime, and this is the way to do it.
1275extern "C" {
1276 void *getPointerToNamedFunction(const char *Name) {
1277 if (Function *F = TheJIT->FindFunctionNamed(Name))
1278 return TheJIT->getPointerToFunction(F);
1279 return TheJIT->getPointerToNamedFunction(Name);
1280 }
1281}
1282
1283// getPointerToFunctionOrStub - If the specified function has been
1284// code-gen'd, return a pointer to the function. If not, compile it, or use
1285// a stub to implement lazy compilation if available.
1286//
1287void *JIT::getPointerToFunctionOrStub(Function *F) {
1288 // If we have already code generated the function, just return the address.
1289 if (void *Addr = getPointerToGlobalIfAvailable(F))
1290 return Addr;
1291
1292 // Get a stub if the target supports it.
Evan Cheng89b29a12008-08-20 00:28:12 +00001293 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1294 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 return JE->getJITResolver().getFunctionStub(F);
1296}
1297
Nate Begeman7b1a8472009-02-18 08:31:02 +00001298void JIT::updateFunctionStub(Function *F) {
1299 // Get the empty stub we generated earlier.
1300 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1301 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1302 void *Stub = JE->getJITResolver().getFunctionStub(F);
1303
1304 // Tell the target jit info to rewrite the stub at the specified address,
1305 // rather than creating a new one.
1306 void *Addr = getPointerToGlobalIfAvailable(F);
1307 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1308}
1309
1310/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1311/// that were emitted during code generation.
1312///
1313void JIT::updateDlsymStubTable() {
1314 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1315 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1316
1317 SmallVector<GlobalValue*, 8> GVs;
1318 SmallVector<void*, 8> Ptrs;
1319
1320 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1321
1322 // If there are no relocatable stubs, return.
1323 if (GVs.empty())
1324 return;
1325
1326 // If there are no new relocatable stubs, return.
1327 void *CurTable = JE->getMemMgr()->getDlsymTable();
1328 if (CurTable && (*(unsigned *)CurTable == GVs.size()))
1329 return;
1330
1331 // Calculate the size of the stub info
Nate Begeman2fd66162009-03-02 23:10:14 +00001332 unsigned offset = 4 + 4 * GVs.size() + sizeof(intptr_t) * GVs.size();
Nate Begeman7b1a8472009-02-18 08:31:02 +00001333
1334 SmallVector<unsigned, 8> Offsets;
1335 for (unsigned i = 0; i != GVs.size(); ++i) {
1336 Offsets.push_back(offset);
1337 offset += GVs[i]->getName().length() + 1;
1338 }
1339
1340 // FIXME: This currently allocates new space every time it's called. A
1341 // different data structure could be used to make this unnecessary.
1342 JE->startGVStub(0, offset, 4);
1343
1344 // Emit the number of records
1345 MCE->emitInt32(GVs.size());
1346
1347 // Emit the string offsets
1348 for (unsigned i = 0; i != GVs.size(); ++i)
1349 MCE->emitInt32(Offsets[i]);
1350
Nate Begemane1ba87f2009-03-04 19:10:38 +00001351 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1352 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1353 // relocation can write the relocated pointer at the appropriate place in
1354 // the stub.
1355 for (unsigned i = 0; i != GVs.size(); ++i) {
1356 intptr_t Ptr = (intptr_t)Ptrs[i];
1357 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1358
1359 if (isa<Function>(GVs[i]))
1360 Ptr |= (intptr_t)1;
1361
Nate Begeman7b1a8472009-02-18 08:31:02 +00001362 if (sizeof(void *) == 8)
Nate Begemane1ba87f2009-03-04 19:10:38 +00001363 MCE->emitInt64(Ptr);
Nate Begeman7b1a8472009-02-18 08:31:02 +00001364 else
Nate Begemane1ba87f2009-03-04 19:10:38 +00001365 MCE->emitInt32(Ptr);
1366 }
Nate Begeman7b1a8472009-02-18 08:31:02 +00001367
1368 // Emit the strings
1369 for (unsigned i = 0; i != GVs.size(); ++i)
1370 MCE->emitString(GVs[i]->getName());
1371
1372 // Tell the JIT memory manager where it is.
1373 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1374}
1375
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376/// freeMachineCodeForFunction - release machine code memory for given Function.
1377///
1378void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +00001379
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 // Delete translation for this from the ExecutionEngine, so it will get
1381 // retranslated next time it is used.
Chris Lattnerf50e3572008-04-04 05:51:42 +00001382 void *OldPtr = updateGlobalMapping(F, 0);
1383
1384 if (OldPtr)
1385 RemoveFunctionFromSymbolTable(OldPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386
1387 // Free the actual memory for the function body and related stuff.
Evan Cheng89b29a12008-08-20 00:28:12 +00001388 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1389 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390}
1391