blob: e8314a1d86606a2f4265b730603db2cb5975a185 [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"
Reid Kleckner738b4f22009-09-20 23:52:43 +000017#include "JITDebugRegisterer.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000018#include "JITDwarfEmitter.h"
Reid Kleckner738b4f22009-09-20 23:52:43 +000019#include "llvm/ADT/OwningPtr.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000020#include "llvm/Constants.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Module.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000022#include "llvm/DerivedTypes.h"
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +000023#include "llvm/CodeGen/JITCodeEmitter.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/CodeGen/MachineRelocation.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000029#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskinf8d55342009-06-25 02:04:04 +000030#include "llvm/ExecutionEngine/JITEventListener.h"
31#include "llvm/ExecutionEngine/JITMemoryManager.h"
Argiris Kirtzidis6841c1a2009-05-18 21:06:40 +000032#include "llvm/CodeGen/MachineCodeInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetJITInfo.h"
35#include "llvm/Target/TargetMachine.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000036#include "llvm/Target/TargetOptions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/Support/MutexGuard.h"
Nick Lewyckyaaffd142009-04-19 18:32:03 +000040#include "llvm/Support/ValueHandle.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000041#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042#include "llvm/System/Disassembler.h"
Chris Lattner88f51632008-06-25 17:18:44 +000043#include "llvm/System/Memory.h"
Nicolas Geoffray68847972008-04-18 20:59:31 +000044#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng68e5fc32008-11-07 09:02:17 +000045#include "llvm/ADT/SmallPtrSet.h"
Nate Begeman7b1a8472009-02-18 08:31:02 +000046#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include <algorithm>
Evan Cheng23dbb902008-11-05 23:44:08 +000049#ifndef NDEBUG
50#include <iomanip>
51#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052using namespace llvm;
53
54STATISTIC(NumBytes, "Number of bytes of machine code compiled");
55STATISTIC(NumRelos, "Number of relocations applied");
Reid Klecknercc492292009-07-23 21:46:56 +000056STATISTIC(NumRetries, "Number of retries with more memory");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057static JIT *TheJIT = 0;
58
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059
60//===----------------------------------------------------------------------===//
61// JIT lazy compilation code.
62//
63namespace {
64 class JITResolverState {
Nick Lewycky924fc912009-04-27 05:09:44 +000065 public:
66 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
67 typedef std::map<void*, Function*> StubToFunctionMapTy;
68 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069 private:
70 /// FunctionToStubMap - Keep track of the stub created for a particular
71 /// function so that we can reuse them if necessary.
Nick Lewycky924fc912009-04-27 05:09:44 +000072 FunctionToStubMapTy FunctionToStubMap;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073
74 /// StubToFunctionMap - Keep track of the function that each stub
75 /// corresponds to.
Nick Lewycky924fc912009-04-27 05:09:44 +000076 StubToFunctionMapTy StubToFunctionMap;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077
Evan Chengb0ebcb42008-11-10 01:52:24 +000078 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Cheng28e7e162008-01-04 10:46:51 +000079 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewycky924fc912009-04-27 05:09:44 +000080 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Cheng28e7e162008-01-04 10:46:51 +000081
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 public:
Nick Lewycky924fc912009-04-27 05:09:44 +000083 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 assert(locked.holds(TheJIT->lock));
85 return FunctionToStubMap;
86 }
87
Nick Lewycky924fc912009-04-27 05:09:44 +000088 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 assert(locked.holds(TheJIT->lock));
90 return StubToFunctionMap;
91 }
Evan Cheng28e7e162008-01-04 10:46:51 +000092
Nick Lewycky924fc912009-04-27 05:09:44 +000093 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Cheng28e7e162008-01-04 10:46:51 +000094 assert(locked.holds(TheJIT->lock));
Evan Chengb0ebcb42008-11-10 01:52:24 +000095 return GlobalToIndirectSymMap;
Evan Cheng28e7e162008-01-04 10:46:51 +000096 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097 };
98
99 /// JITResolver - Keep track of, and resolve, call sites for functions that
100 /// have not yet been compiled.
101 class JITResolver {
Nick Lewycky924fc912009-04-27 05:09:44 +0000102 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
103 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
104 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
105
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 /// LazyResolverFn - The target lazy resolver function that we actually
107 /// rewrite instructions to use.
108 TargetJITInfo::LazyResolverFn LazyResolverFn;
109
110 JITResolverState state;
111
112 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
113 /// external functions.
114 std::map<void*, void*> ExternalFnToStubMap;
115
Evan Cheng68c18682009-03-13 07:51:59 +0000116 /// revGOTMap - map addresses to indexes in the GOT
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 std::map<void*, unsigned> revGOTMap;
118 unsigned nextGOTIndex;
119
120 static JITResolver *TheJITResolver;
121 public:
Dan Gohman40bd38e2008-03-25 22:06:05 +0000122 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 TheJIT = &jit;
124
125 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
126 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
127 TheJITResolver = this;
128 }
129
130 ~JITResolver() {
131 TheJITResolver = 0;
132 }
133
Evan Cheng6e4b7632008-11-13 21:50:50 +0000134 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
135 /// if it has already been created.
136 void *getFunctionStubIfAvailable(Function *F);
137
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begeman7b1a8472009-02-18 08:31:02 +0000139 /// one on demand as needed. If empty is true, create a function stub
140 /// pointing at address 0, to be filled in later.
Nate Begeman165818c2009-03-07 06:41:19 +0000141 void *getFunctionStub(Function *F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142
143 /// getExternalFunctionStub - Return a stub for the function at the
144 /// specified address, created lazily on demand.
145 void *getExternalFunctionStub(void *FnAddr);
146
Evan Chengb0ebcb42008-11-10 01:52:24 +0000147 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Cheng23c6b642008-11-05 01:50:32 +0000148 /// specified GV address.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000149 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Cheng28e7e162008-01-04 10:46:51 +0000150
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 /// AddCallbackAtLocation - If the target is capable of rewriting an
152 /// instruction without the use of a stub, record the location of the use so
153 /// we know which function is being used at the location.
154 void *AddCallbackAtLocation(Function *F, void *Location) {
155 MutexGuard locked(TheJIT->lock);
156 /// Get the target-specific JIT resolver function.
157 state.getStubToFunctionMap(locked)[Location] = F;
158 return (void*)(intptr_t)LazyResolverFn;
159 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000160
161 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begemana5645962009-03-05 06:34:37 +0000162 SmallVectorImpl<void*> &Ptrs);
163
164 GlobalValue *invalidateStub(void *Stub);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165
166 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000167 /// an address. This function only manages slots, it does not manage the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168 /// contents of the slots or the memory associated with the GOT.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000169 unsigned getGOTIndexForAddr(void *addr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171 /// JITCompilerFn - This function is called to resolve a stub to a compiled
172 /// address. If the LLVM Function corresponding to the stub has not yet
173 /// been compiled, this function compiles it first.
174 static void *JITCompilerFn(void *Stub);
175 };
176}
177
178JITResolver *JITResolver::TheJITResolver = 0;
179
Evan Cheng6e4b7632008-11-13 21:50:50 +0000180/// getFunctionStubIfAvailable - This returns a pointer to a function stub
181/// if it has already been created.
182void *JITResolver::getFunctionStubIfAvailable(Function *F) {
183 MutexGuard locked(TheJIT->lock);
184
185 // If we already have a stub for this function, recycle it.
186 void *&Stub = state.getFunctionToStubMap(locked)[F];
187 return Stub;
188}
189
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190/// getFunctionStub - This returns a pointer to a function stub, creating
191/// one on demand as needed.
Nate Begeman165818c2009-03-07 06:41:19 +0000192void *JITResolver::getFunctionStub(Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 MutexGuard locked(TheJIT->lock);
194
195 // If we already have a stub for this function, recycle it.
196 void *&Stub = state.getFunctionToStubMap(locked)[F];
197 if (Stub) return Stub;
198
Nate Begeman165818c2009-03-07 06:41:19 +0000199 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
200 // case we must resolve the symbol now.
201 void *Actual = TheJIT->isLazyCompilationDisabled()
202 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
203
204 // If this is an external declaration, attempt to resolve the address now
205 // to place in the stub.
Dan Gohman0ae39622009-01-05 05:32:42 +0000206 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 Actual = TheJIT->getPointerToFunction(F);
208
Dan Gohman0ae39622009-01-05 05:32:42 +0000209 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begeman165818c2009-03-07 06:41:19 +0000210 // don't emit a stub. Return a null pointer to the application. If dlsym
211 // stubs are enabled, not being able to resolve the address is not
212 // meaningful.
213 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman0ae39622009-01-05 05:32:42 +0000214 }
215
Nate Begeman165818c2009-03-07 06:41:19 +0000216 // Codegen a new stub, calling the lazy resolver or the actual address of the
217 // external function, if it was resolved.
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000218 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 *TheJIT->getCodeEmitter());
220
221 if (Actual != (void*)(intptr_t)LazyResolverFn) {
222 // If we are getting the stub for an external function, we really want the
223 // address of the stub in the GlobalAddressMap for the JIT, not the address
224 // of the external function.
225 TheJIT->updateGlobalMapping(F, Stub);
226 }
227
Daniel Dunbar005975c2009-07-25 00:23:56 +0000228 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
229 << F->getName() << "'\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230
231 // Finally, keep track of the stub-to-Function mapping so that the
232 // JITCompilerFn knows which function to compile!
233 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begeman7b1a8472009-02-18 08:31:02 +0000234
Nate Begeman165818c2009-03-07 06:41:19 +0000235 // If we are JIT'ing non-lazily but need to call a function that does not
236 // exist yet, add it to the JIT's work list so that we can fill in the stub
237 // address later.
238 if (!Actual && TheJIT->isLazyCompilationDisabled())
239 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
240 TheJIT->addPendingFunction(F);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000241
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 return Stub;
243}
244
Evan Chengb0ebcb42008-11-10 01:52:24 +0000245/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Cheng28e7e162008-01-04 10:46:51 +0000246/// GV address.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000247void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Cheng28e7e162008-01-04 10:46:51 +0000248 MutexGuard locked(TheJIT->lock);
249
250 // If we already have a stub for this global variable, recycle it.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000251 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
252 if (IndirectSym) return IndirectSym;
Evan Cheng28e7e162008-01-04 10:46:51 +0000253
Evan Cheng221548c2008-11-10 23:26:16 +0000254 // Otherwise, codegen a new indirect symbol.
Evan Chengb0ebcb42008-11-10 01:52:24 +0000255 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Cheng23c6b642008-11-05 01:50:32 +0000256 *TheJIT->getCodeEmitter());
Evan Cheng28e7e162008-01-04 10:46:51 +0000257
Daniel Dunbar005975c2009-07-25 00:23:56 +0000258 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
259 << "] for GV '" << GV->getName() << "'\n");
Evan Cheng28e7e162008-01-04 10:46:51 +0000260
Evan Chengb0ebcb42008-11-10 01:52:24 +0000261 return IndirectSym;
Evan Cheng28e7e162008-01-04 10:46:51 +0000262}
263
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264/// getExternalFunctionStub - Return a stub for the function at the
265/// specified address, created lazily on demand.
266void *JITResolver::getExternalFunctionStub(void *FnAddr) {
267 // If we already have a stub for this function, recycle it.
268 void *&Stub = ExternalFnToStubMap[FnAddr];
269 if (Stub) return Stub;
270
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000271 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 *TheJIT->getCodeEmitter());
273
Chris Lattner2b40c562009-08-23 06:35:02 +0000274 DEBUG(errs() << "JIT: Stub emitted at [" << Stub
275 << "] for external function at '" << FnAddr << "'\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 return Stub;
277}
278
279unsigned JITResolver::getGOTIndexForAddr(void* addr) {
280 unsigned idx = revGOTMap[addr];
281 if (!idx) {
282 idx = ++nextGOTIndex;
283 revGOTMap[addr] = idx;
Chris Lattner2b40c562009-08-23 06:35:02 +0000284 DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
285 << addr << "]\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 }
287 return idx;
288}
289
Nate Begeman7b1a8472009-02-18 08:31:02 +0000290void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
291 SmallVectorImpl<void*> &Ptrs) {
292 MutexGuard locked(TheJIT->lock);
293
Nick Lewycky924fc912009-04-27 05:09:44 +0000294 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
295 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000296
Nick Lewycky924fc912009-04-27 05:09:44 +0000297 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
Nate Begeman7b1a8472009-02-18 08:31:02 +0000298 Function *F = i->first;
299 if (F->isDeclaration() && F->hasExternalLinkage()) {
300 GVs.push_back(i->first);
301 Ptrs.push_back(i->second);
302 }
303 }
Nick Lewycky924fc912009-04-27 05:09:44 +0000304 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman7b1a8472009-02-18 08:31:02 +0000305 i != e; ++i) {
306 GVs.push_back(i->first);
307 Ptrs.push_back(i->second);
308 }
309}
310
Nate Begemana5645962009-03-05 06:34:37 +0000311GlobalValue *JITResolver::invalidateStub(void *Stub) {
312 MutexGuard locked(TheJIT->lock);
313
Nick Lewycky924fc912009-04-27 05:09:44 +0000314 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
315 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
316 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemana5645962009-03-05 06:34:37 +0000317
318 // Look up the cheap way first, to see if it's a function stub we are
319 // invalidating. If so, remove it from both the forward and reverse maps.
320 if (SM.find(Stub) != SM.end()) {
321 Function *F = SM[Stub];
322 SM.erase(Stub);
323 FM.erase(F);
324 return F;
325 }
326
Nate Begemand1718c42009-03-11 07:03:43 +0000327 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewycky924fc912009-04-27 05:09:44 +0000328 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemana5645962009-03-05 06:34:37 +0000329 i != e; ++i) {
330 if (i->second != Stub)
331 continue;
332 GlobalValue *GV = i->first;
333 GM.erase(i);
334 return GV;
335 }
336
Nate Begemand1718c42009-03-11 07:03:43 +0000337 // Lastly, check to see if it's in the ExternalFnToStubMap.
338 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
339 e = ExternalFnToStubMap.end(); i != e; ++i) {
340 if (i->second != Stub)
341 continue;
342 ExternalFnToStubMap.erase(i);
343 break;
344 }
345
Nate Begemana5645962009-03-05 06:34:37 +0000346 return 0;
347}
348
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349/// JITCompilerFn - This function is called when a lazy compilation stub has
350/// been entered. It looks up which function this stub corresponds to, compiles
351/// it if necessary, then returns the resultant function pointer.
352void *JITResolver::JITCompilerFn(void *Stub) {
353 JITResolver &JR = *TheJITResolver;
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000354
355 Function* F = 0;
356 void* ActualPtr = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000358 {
359 // Only lock for getting the Function. The call getPointerToFunction made
360 // in this function might trigger function materializing, which requires
361 // JIT lock to be unlocked.
362 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000364 // The address given to us for the stub may not be exactly right, it might be
365 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewycky924fc912009-04-27 05:09:44 +0000366 StubToFunctionMapTy::iterator I =
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000367 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
368 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
369 "This is not a known stub!");
370 F = (--I)->second;
371 ActualPtr = I->first;
372 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373
374 // If we have already code generated the function, just return the address.
375 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
376
377 if (!Result) {
378 // Otherwise we don't have it, do lazy compilation now.
379
380 // If lazy compilation is disabled, emit a useful error message and abort.
381 if (TheJIT->isLazyCompilationDisabled()) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000382 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
383 + F->getName() + "' when lazy compiles are disabled!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 }
385
386 // We might like to remove the stub from the StubToFunction map.
387 // We can't do that! Multiple threads could be stuck, waiting to acquire the
388 // lock above. As soon as the 1st function finishes compiling the function,
389 // the next one will be released, and needs to be able to find the function
390 // it needs to call.
391 //JR.state.getStubToFunctionMap(locked).erase(I);
392
Daniel Dunbar005975c2009-07-25 00:23:56 +0000393 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
394 << "' In stub ptr = " << Stub << " actual ptr = "
395 << ActualPtr << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396
397 Result = TheJIT->getPointerToFunction(F);
398 }
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000399
400 // Reacquire the lock to erase the stub in the map.
401 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402
403 // We don't need to reuse this stub in the future, as F is now compiled.
404 JR.state.getFunctionToStubMap(locked).erase(F);
405
406 // FIXME: We could rewrite all references to this stub if we knew them.
407
408 // What we will do is set the compiled function address to map to the
409 // same GOT entry as the stub so that later clients may update the GOT
410 // if they see it still using the stub address.
411 // Note: this is done so the Resolver doesn't have to manage GOT memory
412 // Do this without allocating map space if the target isn't using a GOT
413 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
414 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
415
416 return Result;
417}
418
Chris Lattnerf50e3572008-04-04 05:51:42 +0000419//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420// JITEmitter code.
421//
422namespace {
423 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
424 /// used to output functions to memory for execution.
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +0000425 class JITEmitter : public JITCodeEmitter {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000426 JITMemoryManager *MemMgr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427
428 // When outputting a function stub in the context of some other function, we
429 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes214ae972009-06-04 00:15:51 +0000430 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431
Reid Klecknercc492292009-07-23 21:46:56 +0000432 // When reattempting to JIT a function after running out of space, we store
433 // the estimated size of the function we're trying to JIT here, so we can
434 // ask the memory manager for at least this much space. When we
435 // successfully emit the function, we reset this back to zero.
436 uintptr_t SizeEstimate;
437
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 /// Relocations - These are the relocations that the function needs, as
439 /// emitted.
440 std::vector<MachineRelocation> Relocations;
441
442 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
443 /// It is filled in by the StartMachineBasicBlock callback and queried by
444 /// the getMachineBasicBlockAddress callback.
Evan Cheng6e561c72008-12-10 02:32:19 +0000445 std::vector<uintptr_t> MBBLocations;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446
447 /// ConstantPool - The constant pool for the current function.
448 ///
449 MachineConstantPool *ConstantPool;
450
451 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
452 ///
453 void *ConstantPoolBase;
454
Evan Cheng68c18682009-03-13 07:51:59 +0000455 /// ConstPoolAddresses - Addresses of individual constant pool entries.
456 ///
457 SmallVector<uintptr_t, 8> ConstPoolAddresses;
458
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459 /// JumpTable - The jump tables for the current function.
460 ///
461 MachineJumpTableInfo *JumpTable;
462
463 /// JumpTableBase - A pointer to the first entry in the jump table.
464 ///
465 void *JumpTableBase;
Evan Chengaf743252008-01-05 02:26:58 +0000466
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 /// Resolver - This contains info about the currently resolved functions.
468 JITResolver Resolver;
Reid Kleckner738b4f22009-09-20 23:52:43 +0000469
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000470 /// DE - The dwarf emitter for the jit.
Reid Kleckner738b4f22009-09-20 23:52:43 +0000471 OwningPtr<JITDwarfEmitter> DE;
472
473 /// DR - The debug registerer for the jit.
474 OwningPtr<JITDebugRegisterer> DR;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000475
476 /// LabelLocations - This vector is a mapping from Label ID's to their
477 /// address.
Evan Cheng6e561c72008-12-10 02:32:19 +0000478 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000479
480 /// MMI - Machine module info for exception informations
481 MachineModuleInfo* MMI;
482
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000483 // GVSet - a set to keep track of which globals have been seen
Evan Cheng68e5fc32008-11-07 09:02:17 +0000484 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000485
Nate Begemana5645962009-03-05 06:34:37 +0000486 // CurFn - The llvm function being emitted. Only valid during
487 // finishFunction().
488 const Function *CurFn;
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +0000489
490 /// Information about emitted code, which is passed to the
491 /// JITEventListeners. This is reset in startFunction and used in
492 /// finishFunction.
493 JITEvent_EmittedFunctionDetails EmissionDetails;
494
Nate Begemana5645962009-03-05 06:34:37 +0000495 // CurFnStubUses - For a given Function, a vector of stubs that it
496 // references. This facilitates the JIT detecting that a stub is no
497 // longer used, so that it may be deallocated.
498 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
499
500 // StubFnRefs - For a given pointer to a stub, a set of Functions which
501 // reference the stub. When the count of a stub's references drops to zero,
502 // the stub is unused.
503 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
504
Nate Begemand1718c42009-03-11 07:03:43 +0000505 // ExtFnStubs - A map of external function names to stubs which have entries
506 // in the JITResolver's ExternalFnToStubMap.
507 StringMap<void *> ExtFnStubs;
Argiris Kirtzidis6841c1a2009-05-18 21:06:40 +0000508
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +0000509 DebugLocTuple PrevDLT;
510
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 public:
Reid Kleckner738b4f22009-09-20 23:52:43 +0000512 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
Xerxes Ranby9112f5f2009-08-25 10:12:55 +0000513 : SizeEstimate(0), Resolver(jit), MMI(0), CurFn(0) {
Chris Lattnere44be002007-12-06 01:08:09 +0000514 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000515 if (jit.getJITInfo().needsGOT()) {
516 MemMgr->AllocateGOT();
Chris Lattner2b40c562009-08-23 06:35:02 +0000517 DEBUG(errs() << "JIT is managing a GOT\n");
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000518 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000519
Reid Kleckner738b4f22009-09-20 23:52:43 +0000520 if (DwarfExceptionHandling || JITEmitDebugInfo) {
521 DE.reset(new JITDwarfEmitter(jit));
522 }
523 if (JITEmitDebugInfo) {
524 DR.reset(new JITDebugRegisterer(TM));
525 }
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000526 }
527 ~JITEmitter() {
528 delete MemMgr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529 }
Evan Cheng89b29a12008-08-20 00:28:12 +0000530
531 /// classof - Methods for support type inquiry through isa, cast, and
532 /// dyn_cast:
533 ///
534 static inline bool classof(const JITEmitter*) { return true; }
535 static inline bool classof(const MachineCodeEmitter*) { return true; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536
537 JITResolver &getJITResolver() { return Resolver; }
538
539 virtual void startFunction(MachineFunction &F);
540 virtual bool finishFunction(MachineFunction &F);
541
542 void emitConstantPool(MachineConstantPool *MCP);
543 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
544 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
545
Evan Cheng2c3267a2008-11-08 08:02:53 +0000546 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000547 unsigned Alignment = 1);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000548 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
549 unsigned StubSize);
Evan Cheng2c3267a2008-11-08 08:02:53 +0000550 virtual void* finishGVStub(const GlobalValue *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551
Nuno Lopes1ab7adc2008-10-21 11:42:16 +0000552 /// allocateSpace - Reserves space in the current block if any, or
553 /// allocate a new one of the given size.
Evan Cheng6e561c72008-12-10 02:32:19 +0000554 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopes1ab7adc2008-10-21 11:42:16 +0000555
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000556 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
557 /// this method does not allocate memory in the current output buffer,
558 /// because a global may live longer than the current function.
559 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
560
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 virtual void addRelocation(const MachineRelocation &MR) {
562 Relocations.push_back(MR);
563 }
564
565 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
566 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
567 MBBLocations.resize((MBB->getNumber()+1)*2);
568 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Chris Lattner2b40c562009-08-23 06:35:02 +0000569 DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
570 << (void*) getCurrentPCValue() << "]\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 }
572
Evan Cheng6e561c72008-12-10 02:32:19 +0000573 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
574 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Chengaf743252008-01-05 02:26:58 +0000575
Evan Cheng6e561c72008-12-10 02:32:19 +0000576 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
578 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
579 return MBBLocations[MBB->getNumber()];
580 }
581
Reid Klecknercc492292009-07-23 21:46:56 +0000582 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
583 /// given function. Increase the minimum allocation size so that we get
584 /// more memory next time.
585 void retryWithMoreMemory(MachineFunction &F);
586
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587 /// deallocateMemForFunction - Deallocate all memory for the specified
588 /// function body.
Reid Klecknercc492292009-07-23 21:46:56 +0000589 void deallocateMemForFunction(const Function *F);
Nate Begemand1718c42009-03-11 07:03:43 +0000590
591 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
592 /// using the stub at the specified address. Allows
593 /// deallocateMemForFunction to also remove stubs no longer referenced.
594 void AddStubToCurrentFunction(void *Stub);
595
596 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
597 /// MachineRelocations that reference external functions by name.
598 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000599
Devang Patelde8d48b2009-10-06 03:04:58 +0000600 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +0000601
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000602 virtual void emitLabel(uint64_t LabelID) {
603 if (LabelLocations.size() <= LabelID)
604 LabelLocations.resize((LabelID+1)*2);
605 LabelLocations[LabelID] = getCurrentPCValue();
606 }
607
Evan Cheng6e561c72008-12-10 02:32:19 +0000608 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000609 assert(LabelLocations.size() > (unsigned)LabelID &&
610 LabelLocations[LabelID] && "Label not emitted!");
611 return LabelLocations[LabelID];
612 }
613
614 virtual void setModuleInfo(MachineModuleInfo* Info) {
615 MMI = Info;
Reid Kleckner738b4f22009-09-20 23:52:43 +0000616 if (DE.get()) DE->setModuleInfo(Info);
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000617 }
618
Dan Gohman3dbe9442009-08-12 22:10:57 +0000619 void setMemoryExecutable() {
Jim Grosbach724b1812008-10-03 16:17:20 +0000620 MemMgr->setMemoryExecutable();
621 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000622
Dan Gohman3dbe9442009-08-12 22:10:57 +0000623 JITMemoryManager *getMemMgr() const { return MemMgr; }
Jim Grosbach724b1812008-10-03 16:17:20 +0000624
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 private:
626 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Chengb0ebcb42008-11-10 01:52:24 +0000627 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Cheng221548c2008-11-10 23:26:16 +0000628 bool NoNeedStub);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000629 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
630 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
631 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
632 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 };
634}
635
636void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
637 bool DoesntNeedStub) {
Nate Begeman7b1a8472009-02-18 08:31:02 +0000638 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000640
Chris Lattner44d8ea72008-06-25 20:21:35 +0000641 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikovc7b90912008-09-09 20:05:04 +0000642 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643
644 // If we have already compiled the function, return a pointer to its body.
645 Function *F = cast<Function>(V);
Evan Cheng6e4b7632008-11-13 21:50:50 +0000646 void *ResultPtr;
Jeffrey Yasskin5d3b7ca2009-10-06 00:35:55 +0000647 if (!DoesntNeedStub) {
Evan Cheng6e4b7632008-11-13 21:50:50 +0000648 // Return the function stub if it's already created.
649 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begemana5645962009-03-05 06:34:37 +0000650 if (ResultPtr)
651 AddStubToCurrentFunction(ResultPtr);
652 } else {
Evan Cheng6e4b7632008-11-13 21:50:50 +0000653 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begemana5645962009-03-05 06:34:37 +0000654 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 if (ResultPtr) return ResultPtr;
656
Nate Begeman7b1a8472009-02-18 08:31:02 +0000657 // If this is an external function pointer, we can force the JIT to
Nate Begeman165818c2009-03-07 06:41:19 +0000658 // 'compile' it, which really just adds it to the map. In dlsym mode,
659 // external functions are forced through a stub, regardless of reloc type.
660 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
661 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begeman7b1a8472009-02-18 08:31:02 +0000662 return TheJIT->getPointerToFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 // Okay, the function has not been compiled yet, if the target callback
665 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begeman165818c2009-03-07 06:41:19 +0000666 // that instead of emitting a stub. This uses the lazy resolver, so is not
667 // legal if lazy compilation is disabled.
668 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 return Resolver.AddCallbackAtLocation(F, Reference);
670
Nate Begeman165818c2009-03-07 06:41:19 +0000671 // Otherwise, we have to emit a stub.
Nate Begemana5645962009-03-05 06:34:37 +0000672 void *StubAddr = Resolver.getFunctionStub(F);
673
674 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begeman165818c2009-03-07 06:41:19 +0000675 // deallocate them if the current function is ever freed. It's possible to
676 // return null from getFunctionStub in the case of a weak extern that fails
677 // to resolve.
678 if (StubAddr)
679 AddStubToCurrentFunction(StubAddr);
680
Nate Begemana5645962009-03-05 06:34:37 +0000681 return StubAddr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682}
683
Evan Chengb0ebcb42008-11-10 01:52:24 +0000684void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Cheng221548c2008-11-10 23:26:16 +0000685 bool NoNeedStub) {
Nate Begemana5645962009-03-05 06:34:37 +0000686 // Make sure GV is emitted first, and create a stub containing the fully
687 // resolved address.
Evan Cheng28e7e162008-01-04 10:46:51 +0000688 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begemana5645962009-03-05 06:34:37 +0000689 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
690
691 // Add the stub to the current function's list of referenced stubs, so we can
692 // deallocate them if the current function is ever freed.
693 AddStubToCurrentFunction(StubAddr);
694
695 return StubAddr;
696}
697
698void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
699 if (!TheJIT->areDlsymStubsEnabled())
700 return;
701
702 assert(CurFn && "Stub added to current function, but current function is 0!");
703
704 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
705 StubsUsed.push_back(StubAddr);
706
707 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
708 FnRefs.insert(CurFn);
Evan Cheng28e7e162008-01-04 10:46:51 +0000709}
710
Devang Patelde8d48b2009-10-06 03:04:58 +0000711void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +0000712 if (!DL.isUnknown()) {
713 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
714
Devang Patelde8d48b2009-10-06 03:04:58 +0000715 if (BeforePrintingInsn) {
716 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
717 JITEvent_EmittedFunctionDetails::LineStart NextLine;
718 NextLine.Address = getCurrentPCValue();
719 NextLine.Loc = DL;
720 EmissionDetails.LineStarts.push_back(NextLine);
721 }
722
723 PrevDLT = CurDLT;
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +0000724 }
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +0000725 }
726}
727
Evan Cheng68c18682009-03-13 07:51:59 +0000728static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
729 const TargetData *TD) {
Nicolas Geoffray68847972008-04-18 20:59:31 +0000730 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
731 if (Constants.empty()) return 0;
732
Evan Cheng68c18682009-03-13 07:51:59 +0000733 unsigned Size = 0;
734 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
735 MachineConstantPoolEntry CPE = Constants[i];
736 unsigned AlignMask = CPE.getAlignment() - 1;
737 Size = (Size + AlignMask) & ~AlignMask;
738 const Type *Ty = CPE.getType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000739 Size += TD->getTypeAllocSize(Ty);
Evan Cheng68c18682009-03-13 07:51:59 +0000740 }
Nicolas Geoffray68847972008-04-18 20:59:31 +0000741 return Size;
742}
743
744static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
745 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
746 if (JT.empty()) return 0;
747
748 unsigned NumEntries = 0;
749 for (unsigned i = 0, e = JT.size(); i != e; ++i)
750 NumEntries += JT[i].MBBs.size();
751
752 unsigned EntrySize = MJTI->getEntrySize();
753
754 return NumEntries * EntrySize;
755}
756
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000757static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffray68847972008-04-18 20:59:31 +0000758 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000759 // Since we do not know where the buffer will be allocated, be pessimistic.
760 return Size + Alignment;
Nicolas Geoffray68847972008-04-18 20:59:31 +0000761}
Evan Cheng28e7e162008-01-04 10:46:51 +0000762
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000763/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
764/// into the running total Size.
765
766unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
767 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000768 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000769 size_t GVAlign =
770 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Chris Lattner2b40c562009-08-23 06:35:02 +0000771 DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000772 DEBUG(GV->dump());
773 // Assume code section ends with worst possible alignment, so first
774 // variable needs maximal padding.
775 if (Size==0)
776 Size = 1;
777 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
778 Size += GVSize;
779 return Size;
780}
781
782/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
783/// but are referenced from the constant; put them in GVSet and add their
784/// size into the running total Size.
785
786unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
787 unsigned Size) {
788 // If its undefined, return the garbage.
789 if (isa<UndefValue>(C))
790 return Size;
791
792 // If the value is a ConstantExpr
793 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
794 Constant *Op0 = CE->getOperand(0);
795 switch (CE->getOpcode()) {
796 case Instruction::GetElementPtr:
797 case Instruction::Trunc:
798 case Instruction::ZExt:
799 case Instruction::SExt:
800 case Instruction::FPTrunc:
801 case Instruction::FPExt:
802 case Instruction::UIToFP:
803 case Instruction::SIToFP:
804 case Instruction::FPToUI:
805 case Instruction::FPToSI:
806 case Instruction::PtrToInt:
807 case Instruction::IntToPtr:
808 case Instruction::BitCast: {
809 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
810 break;
811 }
812 case Instruction::Add:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000813 case Instruction::FAdd:
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000814 case Instruction::Sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000815 case Instruction::FSub:
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000816 case Instruction::Mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000817 case Instruction::FMul:
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000818 case Instruction::UDiv:
819 case Instruction::SDiv:
820 case Instruction::URem:
821 case Instruction::SRem:
822 case Instruction::And:
823 case Instruction::Or:
824 case Instruction::Xor: {
825 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
826 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
827 break;
828 }
829 default: {
Edwin Törökced9ff82009-07-11 13:10:19 +0000830 std::string msg;
831 raw_string_ostream Msg(msg);
832 Msg << "ConstantExpr not handled: " << *CE;
833 llvm_report_error(Msg.str());
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000834 }
835 }
836 }
837
838 if (C->getType()->getTypeID() == Type::PointerTyID)
839 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng68e5fc32008-11-07 09:02:17 +0000840 if (GVSet.insert(GV))
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000841 Size = addSizeOfGlobal(GV, Size);
842
843 return Size;
844}
845
846/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
847/// but are referenced from the given initializer.
848
849unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
850 unsigned Size) {
851 if (!isa<UndefValue>(Init) &&
852 !isa<ConstantVector>(Init) &&
853 !isa<ConstantAggregateZero>(Init) &&
854 !isa<ConstantArray>(Init) &&
855 !isa<ConstantStruct>(Init) &&
856 Init->getType()->isFirstClassType())
857 Size = addSizeOfGlobalsInConstantVal(Init, Size);
858 return Size;
859}
860
861/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
862/// globals; then walk the initializers of those globals looking for more.
863/// If their size has not been considered yet, add it into the running total
864/// Size.
865
866unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
867 unsigned Size = 0;
868 GVSet.clear();
869
870 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
871 MBB != E; ++MBB) {
872 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
873 I != E; ++I) {
874 const TargetInstrDesc &Desc = I->getDesc();
875 const MachineInstr &MI = *I;
876 unsigned NumOps = Desc.getNumOperands();
877 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
878 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000879 if (MO.isGlobal()) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000880 GlobalValue* V = MO.getGlobal();
881 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
882 if (!GV)
883 continue;
884 // If seen in previous function, it will have an entry here.
885 if (TheJIT->getPointerToGlobalIfAvailable(GV))
886 continue;
887 // If seen earlier in this function, it will have an entry here.
888 // FIXME: it should be possible to combine these tables, by
889 // assuming the addresses of the new globals in this module
890 // start at 0 (or something) and adjusting them after codegen
891 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng68e5fc32008-11-07 09:02:17 +0000892 if (GVSet.insert(GV))
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000893 // A variable as yet unseen. Add in its size.
894 Size = addSizeOfGlobal(GV, Size);
895 }
896 }
897 }
898 }
Chris Lattner2b40c562009-08-23 06:35:02 +0000899 DEBUG(errs() << "JIT: About to look through initializers\n");
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000900 // Look for more globals that are referenced only from initializers.
901 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng68e5fc32008-11-07 09:02:17 +0000902 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000903 I != GVSet.end(); I++) {
904 const GlobalVariable* GV = *I;
905 if (GV->hasInitializer())
906 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
907 }
908
909 return Size;
910}
911
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912void JITEmitter::startFunction(MachineFunction &F) {
Daniel Dunbar005975c2009-07-25 00:23:56 +0000913 DEBUG(errs() << "JIT: Starting CodeGen of Function "
914 << F.getFunction()->getName() << "\n");
Evan Chengd6599362008-11-06 17:46:04 +0000915
Nicolas Geoffray68847972008-04-18 20:59:31 +0000916 uintptr_t ActualSize = 0;
Jim Grosbach724b1812008-10-03 16:17:20 +0000917 // Set the memory writable, if it's not already
918 MemMgr->setMemoryWritable();
Nicolas Geoffrayf748af22008-04-20 17:44:19 +0000919 if (MemMgr->NeedsExactSize()) {
Chris Lattner2b40c562009-08-23 06:35:02 +0000920 DEBUG(errs() << "JIT: ExactSize\n");
Nicolas Geoffray68847972008-04-18 20:59:31 +0000921 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
922 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
923 MachineConstantPool *MCP = F.getConstantPool();
924
925 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000926 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffray68847972008-04-18 20:59:31 +0000927
928 // Add the alignment of the constant pool
Evan Cheng68c18682009-03-13 07:51:59 +0000929 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000930
931 // Add the constant pool size
Evan Cheng68c18682009-03-13 07:51:59 +0000932 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000933
934 // Add the aligment of the jump table info
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000935 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000936
937 // Add the jump table size
938 ActualSize += GetJumpTableSizeInBytes(MJTI);
939
940 // Add the alignment for the function
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000941 ActualSize = RoundUpToAlign(ActualSize,
942 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffray68847972008-04-18 20:59:31 +0000943
944 // Add the function size
945 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000946
Chris Lattner2b40c562009-08-23 06:35:02 +0000947 DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000948 // Add the size of the globals that will be allocated after this function.
949 // These are all the ones referenced from this function that were not
950 // previously allocated.
951 ActualSize += GetSizeOfGlobalsInBytes(F);
Chris Lattner2b40c562009-08-23 06:35:02 +0000952 DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
Reid Klecknercc492292009-07-23 21:46:56 +0000953 } else if (SizeEstimate > 0) {
954 // SizeEstimate will be non-zero on reallocation attempts.
955 ActualSize = SizeEstimate;
Nicolas Geoffray68847972008-04-18 20:59:31 +0000956 }
957
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000958 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
959 ActualSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 BufferEnd = BufferBegin+ActualSize;
961
962 // Ensure the constant pool/jump table info is at least 4-byte aligned.
963 emitAlignment(16);
964
965 emitConstantPool(F.getConstantPool());
966 initJumpTableInfo(F.getJumpTableInfo());
967
968 // About to start emitting the machine code for the function.
969 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
970 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
971
972 MBBLocations.clear();
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +0000973
974 EmissionDetails.MF = &F;
975 EmissionDetails.LineStarts.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976}
977
978bool JITEmitter::finishFunction(MachineFunction &F) {
979 if (CurBufferPtr == BufferEnd) {
Reid Klecknercc492292009-07-23 21:46:56 +0000980 // We must call endFunctionBody before retrying, because
981 // deallocateMemForFunction requires it.
982 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
983 retryWithMoreMemory(F);
984 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 }
Reid Klecknercc492292009-07-23 21:46:56 +0000986
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 emitJumpTableInfo(F.getJumpTableInfo());
Reid Klecknercc492292009-07-23 21:46:56 +0000988
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 // FnStart is the start of the text, not the start of the constant pool and
990 // other per-function data.
Bruno Cardoso Lopes214ae972009-06-04 00:15:51 +0000991 uint8_t *FnStart =
992 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
Argiris Kirtzidisb9e97bc2009-04-30 23:01:58 +0000994 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes214ae972009-06-04 00:15:51 +0000995 uint8_t *FnEnd = CurBufferPtr;
Argiris Kirtzidisb9e97bc2009-04-30 23:01:58 +0000996
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 if (!Relocations.empty()) {
Nate Begemana5645962009-03-05 06:34:37 +0000998 CurFn = F.getFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 NumRelos += Relocations.size();
1000
1001 // Resolve the relocations to concrete pointers.
1002 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1003 MachineRelocation &MR = Relocations[i];
Evan Cheng1cf55bb2008-11-03 07:14:02 +00001004 void *ResultPtr = 0;
Evan Chengc5fe01b2008-10-29 23:54:46 +00001005 if (!MR.letTargetResolve()) {
Evan Cheng2976cd12008-11-08 07:37:34 +00001006 if (MR.isExternalSymbol()) {
Dan Gohman0ae39622009-01-05 05:32:42 +00001007 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1008 false);
Chris Lattner2b40c562009-08-23 06:35:02 +00001009 DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1010 << ResultPtr << "]\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011
Evan Chengc5fe01b2008-10-29 23:54:46 +00001012 // If the target REALLY wants a stub for this function, emit it now.
Nate Begemand1718c42009-03-11 07:03:43 +00001013 if (!MR.doesntNeedStub()) {
1014 if (!TheJIT->areDlsymStubsEnabled()) {
1015 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1016 } else {
1017 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1018 if (!Stub) {
1019 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1020 AddStubToCurrentFunction(Stub);
1021 }
1022 ResultPtr = Stub;
1023 }
1024 }
Evan Chengc5fe01b2008-10-29 23:54:46 +00001025 } else if (MR.isGlobalValue()) {
1026 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1027 BufferBegin+MR.getMachineCodeOffset(),
1028 MR.doesntNeedStub());
Evan Chengb0ebcb42008-11-10 01:52:24 +00001029 } else if (MR.isIndirectSymbol()) {
1030 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Cheng28e7e162008-01-04 10:46:51 +00001031 BufferBegin+MR.getMachineCodeOffset(),
1032 MR.doesntNeedStub());
Evan Chengc5fe01b2008-10-29 23:54:46 +00001033 } else if (MR.isBasicBlock()) {
1034 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1035 } else if (MR.isConstantPoolIndex()) {
1036 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1037 } else {
1038 assert(MR.isJumpTableIndex());
1039 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1040 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041
Evan Chengc5fe01b2008-10-29 23:54:46 +00001042 MR.setResultPointer(ResultPtr);
1043 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044
1045 // if we are managing the GOT and the relocation wants an index,
1046 // give it one
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001047 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1049 MR.setGOTIndex(idx);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001050 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Chris Lattner2b40c562009-08-23 06:35:02 +00001051 DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1052 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1053 << "\n");
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001054 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 }
1056 }
1057 }
1058
Nate Begemana5645962009-03-05 06:34:37 +00001059 CurFn = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001061 Relocations.size(), MemMgr->getGOTBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 }
1063
1064 // Update the GOT entry for F to point to the new code.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001065 if (MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001067 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Chris Lattner2b40c562009-08-23 06:35:02 +00001068 DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1069 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1070 << "\n");
Chris Lattnerc8ad39c2007-12-05 23:39:57 +00001071 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 }
1073 }
1074
Argiris Kirtzidisb9e97bc2009-04-30 23:01:58 +00001075 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1076 // global variables that were referenced in the relocations.
1077 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng6e561c72008-12-10 02:32:19 +00001078
1079 if (CurBufferPtr == BufferEnd) {
Reid Klecknercc492292009-07-23 21:46:56 +00001080 retryWithMoreMemory(F);
1081 return true;
1082 } else {
1083 // Now that we've succeeded in emitting the function, reset the
1084 // SizeEstimate back down to zero.
1085 SizeEstimate = 0;
Evan Cheng6e561c72008-12-10 02:32:19 +00001086 }
1087
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001088 BufferBegin = CurBufferPtr = 0;
1089 NumBytes += FnEnd-FnStart;
1090
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091 // Invalidate the icache if necessary.
Chris Lattner88f51632008-06-25 17:18:44 +00001092 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskinf8d55342009-06-25 02:04:04 +00001093
Jeffrey Yasskinf8d55342009-06-25 02:04:04 +00001094 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
Jeffrey Yasskin8ad296e2009-07-16 21:07:26 +00001095 EmissionDetails);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096
Daniel Dunbar005975c2009-07-25 00:23:56 +00001097 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1098 << "] Function: " << F.getFunction()->getName()
1099 << ": " << (FnEnd-FnStart) << " bytes of text, "
1100 << Relocations.size() << " relocations\n");
Argiris Kirtzidis6841c1a2009-05-18 21:06:40 +00001101
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 Relocations.clear();
Evan Cheng68c18682009-03-13 07:51:59 +00001103 ConstPoolAddresses.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104
Evan Chengb83f6972008-09-18 07:54:21 +00001105 // Mark code region readable and executable if it's not so already.
Jim Grosbach724b1812008-10-03 16:17:20 +00001106 MemMgr->setMemoryExecutable();
Evan Chengb83f6972008-09-18 07:54:21 +00001107
Chris Lattner2b40c562009-08-23 06:35:02 +00001108 DEBUG(
Evan Chengb81ef082008-11-12 08:22:43 +00001109 if (sys::hasDisassembler()) {
Chris Lattner2b40c562009-08-23 06:35:02 +00001110 errs() << "JIT: Disassembled code:\n";
1111 errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1112 (uintptr_t)FnStart);
Evan Chengb81ef082008-11-12 08:22:43 +00001113 } else {
Chris Lattner2b40c562009-08-23 06:35:02 +00001114 errs() << "JIT: Binary code:\n";
Bruno Cardoso Lopes214ae972009-06-04 00:15:51 +00001115 uint8_t* q = FnStart;
Evan Chengb81ef082008-11-12 08:22:43 +00001116 for (int i = 0; q < FnEnd; q += 4, ++i) {
1117 if (i == 4)
1118 i = 0;
1119 if (i == 0)
Chris Lattner2b40c562009-08-23 06:35:02 +00001120 errs() << "JIT: " << (long)(q - FnStart) << ": ";
Evan Chengb81ef082008-11-12 08:22:43 +00001121 bool Done = false;
1122 for (int j = 3; j >= 0; --j) {
1123 if (q + j >= FnEnd)
1124 Done = true;
1125 else
Chris Lattner2b40c562009-08-23 06:35:02 +00001126 errs() << (unsigned short)q[j];
Evan Chengb81ef082008-11-12 08:22:43 +00001127 }
1128 if (Done)
1129 break;
Chris Lattner2b40c562009-08-23 06:35:02 +00001130 errs() << ' ';
Evan Chengb81ef082008-11-12 08:22:43 +00001131 if (i == 3)
Chris Lattner2b40c562009-08-23 06:35:02 +00001132 errs() << '\n';
Evan Cheng23dbb902008-11-05 23:44:08 +00001133 }
Chris Lattner2b40c562009-08-23 06:35:02 +00001134 errs()<< '\n';
Evan Cheng23dbb902008-11-05 23:44:08 +00001135 }
Chris Lattner2b40c562009-08-23 06:35:02 +00001136 );
1137
Reid Kleckner738b4f22009-09-20 23:52:43 +00001138 if (DwarfExceptionHandling || JITEmitDebugInfo) {
Nicolas Geoffray68847972008-04-18 20:59:31 +00001139 uintptr_t ActualSize = 0;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001140 SavedBufferBegin = BufferBegin;
1141 SavedBufferEnd = BufferEnd;
1142 SavedCurBufferPtr = CurBufferPtr;
Reid Kleckner738b4f22009-09-20 23:52:43 +00001143
Nicolas Geoffrayf748af22008-04-20 17:44:19 +00001144 if (MemMgr->NeedsExactSize()) {
1145 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffray68847972008-04-18 20:59:31 +00001146 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001147
1148 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1149 ActualSize);
1150 BufferEnd = BufferBegin+ActualSize;
Reid Kleckner738b4f22009-09-20 23:52:43 +00001151 uint8_t *EhStart;
1152 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1153 EhStart);
Chris Lattner3d46fe02008-03-07 20:05:43 +00001154 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1155 FrameRegister);
Reid Kleckner738b4f22009-09-20 23:52:43 +00001156 uint8_t *EhEnd = CurBufferPtr;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001157 BufferBegin = SavedBufferBegin;
1158 BufferEnd = SavedBufferEnd;
1159 CurBufferPtr = SavedCurBufferPtr;
1160
Reid Kleckner738b4f22009-09-20 23:52:43 +00001161 if (DwarfExceptionHandling) {
1162 TheJIT->RegisterTable(FrameRegister);
1163 }
1164
1165 if (JITEmitDebugInfo) {
1166 DebugInfo I;
1167 I.FnStart = FnStart;
1168 I.FnEnd = FnEnd;
1169 I.EhStart = EhStart;
1170 I.EhEnd = EhEnd;
1171 DR->RegisterFunction(F.getFunction(), I);
1172 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001173 }
Evan Chengca346e62008-09-02 08:14:01 +00001174
1175 if (MMI)
1176 MMI->EndFunction();
Nicolas Geoffray0e757e12008-02-13 18:39:37 +00001177
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178 return false;
1179}
1180
Reid Klecknercc492292009-07-23 21:46:56 +00001181void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
Chris Lattner2b40c562009-08-23 06:35:02 +00001182 DEBUG(errs() << "JIT: Ran out of space for native code. Reattempting.\n");
Reid Klecknercc492292009-07-23 21:46:56 +00001183 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1184 ConstPoolAddresses.clear();
1185 ++NumRetries;
1186 deallocateMemForFunction(F.getFunction());
1187 // Try again with at least twice as much free space.
1188 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1189}
1190
Nate Begemana5645962009-03-05 06:34:37 +00001191/// deallocateMemForFunction - Deallocate all memory for the specified
1192/// function body. Also drop any references the function has to stubs.
Reid Klecknercc492292009-07-23 21:46:56 +00001193void JITEmitter::deallocateMemForFunction(const Function *F) {
Nate Begemana5645962009-03-05 06:34:37 +00001194 MemMgr->deallocateMemForFunction(F);
1195
Reid Kleckner738b4f22009-09-20 23:52:43 +00001196 // TODO: Do we need to unregister exception handling information from libgcc
1197 // here?
1198
1199 if (JITEmitDebugInfo) {
1200 DR->UnregisterFunction(F);
1201 }
1202
Nate Begemana5645962009-03-05 06:34:37 +00001203 // If the function did not reference any stubs, return.
1204 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1205 return;
1206
1207 // For each referenced stub, erase the reference to this function, and then
1208 // erase the list of referenced stubs.
1209 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1210 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1211 void *Stub = StubList[i];
Nate Begemand1718c42009-03-11 07:03:43 +00001212
1213 // If we already invalidated this stub for this function, continue.
1214 if (StubFnRefs.count(Stub) == 0)
1215 continue;
1216
Nate Begemana5645962009-03-05 06:34:37 +00001217 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1218 FnRefs.erase(F);
1219
1220 // If this function was the last reference to the stub, invalidate the stub
1221 // in the JITResolver. Were there a memory manager deallocateStub routine,
1222 // we could call that at this point too.
1223 if (FnRefs.empty()) {
Chris Lattner2b40c562009-08-23 06:35:02 +00001224 DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
Nate Begemand1718c42009-03-11 07:03:43 +00001225 StubFnRefs.erase(Stub);
1226
1227 // Invalidate the stub. If it is a GV stub, update the JIT's global
1228 // mapping for that GV to zero, otherwise, search the string map of
1229 // external function names to stubs and remove the entry for this stub.
Nate Begeman165818c2009-03-07 06:41:19 +00001230 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begemand1718c42009-03-11 07:03:43 +00001231 if (GV) {
1232 TheJIT->updateGlobalMapping(GV, 0);
1233 } else {
1234 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1235 e = ExtFnStubs.end(); i != e; ++i) {
1236 if (i->second == Stub) {
1237 ExtFnStubs.erase(i);
1238 break;
1239 }
1240 }
1241 }
Nate Begemana5645962009-03-05 06:34:37 +00001242 }
1243 }
1244 CurFnStubUses.erase(F);
1245}
1246
1247
Evan Cheng6e561c72008-12-10 02:32:19 +00001248void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001249 if (BufferBegin)
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001250 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopes1ab7adc2008-10-21 11:42:16 +00001251
1252 // create a new memory block if there is no active one.
1253 // care must be taken so that BufferBegin is invalidated when a
1254 // block is trimmed
1255 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1256 BufferEnd = BufferBegin+Size;
1257 return CurBufferPtr;
1258}
1259
Jeffrey Yasskin892956a2009-07-08 21:59:57 +00001260void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1261 // Delegate this call through the memory manager.
1262 return MemMgr->allocateGlobal(Size, Alignment);
1263}
1264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001266 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbachbad01432008-10-30 23:44:39 +00001267 return;
Evan Cheng68e5fc32008-11-07 09:02:17 +00001268
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1270 if (Constants.empty()) return;
1271
Evan Cheng68c18682009-03-13 07:51:59 +00001272 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1273 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng71c58872008-04-12 00:22:01 +00001274 ConstantPoolBase = allocateSpace(Size, Align);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 ConstantPool = MCP;
1276
1277 if (ConstantPoolBase == 0) return; // Buffer overflow.
1278
Chris Lattner2b40c562009-08-23 06:35:02 +00001279 DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1280 << "] (size: " << Size << ", alignment: " << Align << ")\n");
Evan Cheng71c58872008-04-12 00:22:01 +00001281
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 // Initialize the memory for all of the constant pool entries.
Evan Cheng68c18682009-03-13 07:51:59 +00001283 unsigned Offset = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng68c18682009-03-13 07:51:59 +00001285 MachineConstantPoolEntry CPE = Constants[i];
1286 unsigned AlignMask = CPE.getAlignment() - 1;
1287 Offset = (Offset + AlignMask) & ~AlignMask;
1288
1289 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1290 ConstPoolAddresses.push_back(CAddr);
1291 if (CPE.isMachineConstantPoolEntry()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 // FIXME: add support to lower machine constant pool values into bytes!
Edwin Törökced9ff82009-07-11 13:10:19 +00001293 llvm_report_error("Initialize memory with machine specific constant pool"
1294 "entry has not been implemented!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 }
Evan Cheng68c18682009-03-13 07:51:59 +00001296 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
Chris Lattner2b40c562009-08-23 06:35:02 +00001297 DEBUG(errs() << "JIT: CP" << i << " at [0x";
1298 errs().write_hex(CAddr) << "]\n");
Evan Cheng68c18682009-03-13 07:51:59 +00001299
1300 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001301 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 }
1303}
1304
1305void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001306 if (TheJIT->getJITInfo().hasCustomJumpTables())
1307 return;
1308
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1310 if (JT.empty()) return;
1311
1312 unsigned NumEntries = 0;
1313 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1314 NumEntries += JT[i].MBBs.size();
1315
1316 unsigned EntrySize = MJTI->getEntrySize();
1317
1318 // Just allocate space for all the jump tables now. We will fix up the actual
1319 // MBB entries in the tables after we emit the code for each block, since then
1320 // we will know the final locations of the MBBs in memory.
1321 JumpTable = MJTI;
1322 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1323}
1324
1325void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng68e5fc32008-11-07 09:02:17 +00001326 if (TheJIT->getJITInfo().hasCustomJumpTables())
1327 return;
1328
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1330 if (JT.empty() || JumpTableBase == 0) return;
1331
1332 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1333 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1334 // For each jump table, place the offset from the beginning of the table
1335 // to the target address.
1336 int *SlotPtr = (int*)JumpTableBase;
1337
1338 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1339 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1340 // Store the offset of the basic block for this jump table slot in the
1341 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng6e561c72008-12-10 02:32:19 +00001342 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Chengaf743252008-01-05 02:26:58 +00001343 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng6e561c72008-12-10 02:32:19 +00001344 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Chengaf743252008-01-05 02:26:58 +00001345 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1346 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 }
1348 } else {
1349 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1350
1351 // For each jump table, map each target in the jump table to the address of
1352 // an emitted MachineBasicBlock.
1353 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1354
1355 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1356 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1357 // Store the address of the basic block for this jump table slot in the
1358 // memory we allocated for the jump table in 'initJumpTableInfo'
1359 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1360 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1361 }
1362 }
1363}
1364
Evan Cheng2c3267a2008-11-08 08:02:53 +00001365void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1366 unsigned Alignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 SavedBufferBegin = BufferBegin;
1368 SavedBufferEnd = BufferEnd;
1369 SavedCurBufferPtr = CurBufferPtr;
1370
Evan Cheng2c3267a2008-11-08 08:02:53 +00001371 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372 BufferEnd = BufferBegin+StubSize+1;
1373}
1374
Nate Begeman7b1a8472009-02-18 08:31:02 +00001375void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1376 unsigned StubSize) {
1377 SavedBufferBegin = BufferBegin;
1378 SavedBufferEnd = BufferEnd;
1379 SavedCurBufferPtr = CurBufferPtr;
1380
Bruno Cardoso Lopes214ae972009-06-04 00:15:51 +00001381 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begeman7b1a8472009-02-18 08:31:02 +00001382 BufferEnd = BufferBegin+StubSize+1;
1383}
1384
Evan Cheng2c3267a2008-11-08 08:02:53 +00001385void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 NumBytes += getCurrentPCOffset();
1387 std::swap(SavedBufferBegin, BufferBegin);
1388 BufferEnd = SavedBufferEnd;
1389 CurBufferPtr = SavedCurBufferPtr;
1390 return SavedBufferBegin;
1391}
1392
1393// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1394// in the constant pool that was last emitted with the 'emitConstantPool'
1395// method.
1396//
Evan Cheng6e561c72008-12-10 02:32:19 +00001397uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398 assert(ConstantNum < ConstantPool->getConstants().size() &&
1399 "Invalid ConstantPoolIndex!");
Evan Cheng68c18682009-03-13 07:51:59 +00001400 return ConstPoolAddresses[ConstantNum];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001401}
1402
1403// getJumpTableEntryAddress - Return the address of the JumpTable with index
1404// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1405//
Evan Cheng6e561c72008-12-10 02:32:19 +00001406uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001407 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1408 assert(Index < JT.size() && "Invalid jump table index!");
1409
1410 unsigned Offset = 0;
1411 unsigned EntrySize = JumpTable->getEntrySize();
1412
1413 for (unsigned i = 0; i < Index; ++i)
1414 Offset += JT[i].MBBs.size();
1415
1416 Offset *= EntrySize;
1417
Evan Cheng6e561c72008-12-10 02:32:19 +00001418 return (uintptr_t)((char *)JumpTableBase + Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419}
1420
1421//===----------------------------------------------------------------------===//
1422// Public interface to this file
1423//===----------------------------------------------------------------------===//
1424
Reid Kleckner738b4f22009-09-20 23:52:43 +00001425JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1426 TargetMachine &tm) {
1427 return new JITEmitter(jit, JMM, tm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428}
1429
1430// getPointerToNamedFunction - This function is used as a global wrapper to
1431// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1432// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1433// need to resolve function(s) that are being mis-codegenerated, so we need to
1434// resolve their addresses at runtime, and this is the way to do it.
1435extern "C" {
1436 void *getPointerToNamedFunction(const char *Name) {
1437 if (Function *F = TheJIT->FindFunctionNamed(Name))
1438 return TheJIT->getPointerToFunction(F);
1439 return TheJIT->getPointerToNamedFunction(Name);
1440 }
1441}
1442
1443// getPointerToFunctionOrStub - If the specified function has been
1444// code-gen'd, return a pointer to the function. If not, compile it, or use
1445// a stub to implement lazy compilation if available.
1446//
1447void *JIT::getPointerToFunctionOrStub(Function *F) {
1448 // If we have already code generated the function, just return the address.
1449 if (void *Addr = getPointerToGlobalIfAvailable(F))
1450 return Addr;
1451
1452 // Get a stub if the target supports it.
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001453 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Cheng89b29a12008-08-20 00:28:12 +00001454 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 return JE->getJITResolver().getFunctionStub(F);
1456}
1457
Nate Begeman7b1a8472009-02-18 08:31:02 +00001458void JIT::updateFunctionStub(Function *F) {
1459 // Get the empty stub we generated earlier.
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001460 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begeman7b1a8472009-02-18 08:31:02 +00001461 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1462 void *Stub = JE->getJITResolver().getFunctionStub(F);
1463
1464 // Tell the target jit info to rewrite the stub at the specified address,
1465 // rather than creating a new one.
1466 void *Addr = getPointerToGlobalIfAvailable(F);
1467 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1468}
1469
1470/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1471/// that were emitted during code generation.
1472///
1473void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001474 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begeman7b1a8472009-02-18 08:31:02 +00001475 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1476
1477 SmallVector<GlobalValue*, 8> GVs;
1478 SmallVector<void*, 8> Ptrs;
Nate Begemand1718c42009-03-11 07:03:43 +00001479 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begeman7b1a8472009-02-18 08:31:02 +00001480
1481 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1482
Nate Begemand1718c42009-03-11 07:03:43 +00001483 unsigned nStubs = GVs.size() + ExtFns.size();
1484
Nate Begeman7b1a8472009-02-18 08:31:02 +00001485 // If there are no relocatable stubs, return.
Nate Begemand1718c42009-03-11 07:03:43 +00001486 if (nStubs == 0)
Nate Begeman7b1a8472009-02-18 08:31:02 +00001487 return;
1488
1489 // If there are no new relocatable stubs, return.
1490 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begemand1718c42009-03-11 07:03:43 +00001491 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begeman7b1a8472009-02-18 08:31:02 +00001492 return;
1493
1494 // Calculate the size of the stub info
Nate Begemand1718c42009-03-11 07:03:43 +00001495 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begeman7b1a8472009-02-18 08:31:02 +00001496
1497 SmallVector<unsigned, 8> Offsets;
1498 for (unsigned i = 0; i != GVs.size(); ++i) {
1499 Offsets.push_back(offset);
Daniel Dunbar9198e932009-07-21 08:54:24 +00001500 offset += GVs[i]->getName().size() + 1;
Nate Begeman7b1a8472009-02-18 08:31:02 +00001501 }
Nate Begemand1718c42009-03-11 07:03:43 +00001502 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1503 i != e; ++i) {
1504 Offsets.push_back(offset);
1505 offset += strlen(i->first()) + 1;
1506 }
Nate Begeman7b1a8472009-02-18 08:31:02 +00001507
Nate Begemana5645962009-03-05 06:34:37 +00001508 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begeman7b1a8472009-02-18 08:31:02 +00001509 JE->startGVStub(0, offset, 4);
1510
1511 // Emit the number of records
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001512 JE->emitInt32(nStubs);
Nate Begeman7b1a8472009-02-18 08:31:02 +00001513
1514 // Emit the string offsets
Nate Begemand1718c42009-03-11 07:03:43 +00001515 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001516 JE->emitInt32(Offsets[i]);
Nate Begeman7b1a8472009-02-18 08:31:02 +00001517
Nate Begemane1ba87f2009-03-04 19:10:38 +00001518 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1519 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1520 // relocation can write the relocated pointer at the appropriate place in
1521 // the stub.
1522 for (unsigned i = 0; i != GVs.size(); ++i) {
1523 intptr_t Ptr = (intptr_t)Ptrs[i];
1524 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1525
1526 if (isa<Function>(GVs[i]))
1527 Ptr |= (intptr_t)1;
1528
Nate Begemand1718c42009-03-11 07:03:43 +00001529 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001530 JE->emitInt64(Ptr);
Nate Begemand1718c42009-03-11 07:03:43 +00001531 else
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001532 JE->emitInt32(Ptr);
Nate Begemand1718c42009-03-11 07:03:43 +00001533 }
1534 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1535 i != e; ++i) {
1536 intptr_t Ptr = (intptr_t)i->second | 1;
1537
1538 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001539 JE->emitInt64(Ptr);
Nate Begeman7b1a8472009-02-18 08:31:02 +00001540 else
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001541 JE->emitInt32(Ptr);
Nate Begemane1ba87f2009-03-04 19:10:38 +00001542 }
Nate Begeman7b1a8472009-02-18 08:31:02 +00001543
Nate Begemana5645962009-03-05 06:34:37 +00001544 // Emit the strings.
Nate Begeman7b1a8472009-02-18 08:31:02 +00001545 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001546 JE->emitString(GVs[i]->getName());
Nate Begemand1718c42009-03-11 07:03:43 +00001547 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1548 i != e; ++i)
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001549 JE->emitString(i->first());
Nate Begeman7b1a8472009-02-18 08:31:02 +00001550
Nate Begemana5645962009-03-05 06:34:37 +00001551 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1552 // deallocate space for the old one, if one existed.
Nate Begeman7b1a8472009-02-18 08:31:02 +00001553 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1554}
1555
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556/// freeMachineCodeForFunction - release machine code memory for given Function.
1557///
1558void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +00001559
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 // Delete translation for this from the ExecutionEngine, so it will get
1561 // retranslated next time it is used.
Chris Lattnerf50e3572008-04-04 05:51:42 +00001562 void *OldPtr = updateGlobalMapping(F, 0);
1563
1564 if (OldPtr)
Jeffrey Yasskinf8d55342009-06-25 02:04:04 +00001565 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566
1567 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopes1ea31ff2009-05-30 20:51:52 +00001568 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1569 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001570}