blob: 394fd8ff2ad243db4289b3a892bd1f59ecbbb9c3 [file] [log] [blame]
Chris Lattner166f2262004-11-22 22:00:25 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
Chris Lattner5be478f2004-11-20 03:46:14 +000010// This file defines a MachineCodeEmitter object that is used by the JIT to
11// write machine code to memory and remember where relocatable values are.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Chris Lattner4d326fa2003-12-20 01:46:27 +000016#include "JIT.h"
Reid Kleckner27632172009-09-20 23:52:43 +000017#include "JITDebugRegisterer.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000018#include "JITDwarfEmitter.h"
Reid Kleckner27632172009-09-20 23:52:43 +000019#include "llvm/ADT/OwningPtr.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000020#include "llvm/Constants.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000021#include "llvm/Module.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000022#include "llvm/DerivedTypes.h"
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +000023#include "llvm/CodeGen/JITCodeEmitter.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000024#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000025#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000026#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000028#include "llvm/CodeGen/MachineRelocation.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000029#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000030#include "llvm/ExecutionEngine/JITEventListener.h"
31#include "llvm/ExecutionEngine/JITMemoryManager.h"
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +000032#include "llvm/CodeGen/MachineCodeInfo.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000033#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000034#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000035#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000036#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000039#include "llvm/Support/MutexGuard.h"
Nick Lewycky848b3142009-04-19 18:32:03 +000040#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000041#include "llvm/Support/raw_ostream.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000042#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000043#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000044#include "llvm/Target/TargetInstrInfo.h"
Jeffrey Yasskin1e861322009-10-20 18:13:21 +000045#include "llvm/ADT/DenseMap.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000046#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000047#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000048#include "llvm/ADT/Statistic.h"
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000049#include "llvm/ADT/ValueMap.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000050#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000051#ifndef NDEBUG
52#include <iomanip>
53#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000054using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000055
Chris Lattner36343732006-12-19 22:43:32 +000056STATISTIC(NumBytes, "Number of bytes of machine code compiled");
57STATISTIC(NumRelos, "Number of relocations applied");
Reid Kleckner10b4fc52009-07-23 21:46:56 +000058STATISTIC(NumRetries, "Number of retries with more memory");
Chris Lattner36343732006-12-19 22:43:32 +000059static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000060
Andrew Lenhartha00269b2005-07-29 23:40:16 +000061
Chris Lattner54266522004-11-20 23:57:07 +000062//===----------------------------------------------------------------------===//
63// JIT lazy compilation code.
64//
65namespace {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000066 class JITResolverState;
67
68 template<typename ValueTy>
69 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
70 typedef JITResolverState *ExtraData;
71 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
72 assert(false && "The JIT doesn't know how to handle a"
73 " RAUW on a value it has emitted.");
74 }
75 };
76
77 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
78 typedef JITResolverState *ExtraData;
79 static void onDelete(JITResolverState *JRS, Function *F);
80 };
81
Reid Spenceree448632005-07-12 15:51:55 +000082 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000083 public:
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000084 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
85 FunctionToStubMapTy;
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +000086 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000087 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
88 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
Nick Lewyckye2bcf132009-04-27 05:09:44 +000089 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000090 private:
91 /// FunctionToStubMap - Keep track of the stub created for a particular
92 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000093 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000094
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +000095 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
96 /// site corresponds to, and vice versa.
97 CallSiteToFunctionMapTy CallSiteToFunctionMap;
98 FunctionToCallSitesMapTy FunctionToCallSitesMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000099
Evan Cheng5594f122008-11-10 01:52:24 +0000100 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +0000101 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000102 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000103
Reid Spenceree448632005-07-12 15:51:55 +0000104 public:
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000105 JITResolverState() : FunctionToStubMap(this),
106 FunctionToCallSitesMap(this) {}
107
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000108 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +0000109 assert(locked.holds(TheJIT->lock));
110 return FunctionToStubMap;
111 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000112
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000113 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000114 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +0000115 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000116 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000117
118 pair<void *, Function *> LookupFunctionFromCallSite(
119 const MutexGuard &locked, void *CallSite) const {
120 assert(locked.holds(TheJIT->lock));
121
122 // The address given to us for the stub may not be exactly right, it might be
123 // a little bit after the stub. As such, use upper_bound to find it.
124 CallSiteToFunctionMapTy::const_iterator I =
125 CallSiteToFunctionMap.upper_bound(CallSite);
126 assert(I != CallSiteToFunctionMap.begin() &&
127 "This is not a known call site!");
128 --I;
129 return *I;
130 }
131
132 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
133 assert(locked.holds(TheJIT->lock));
134
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000135 bool Inserted = CallSiteToFunctionMap.insert(
136 std::make_pair(CallSite, F)).second;
137 (void)Inserted;
138 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000139 FunctionToCallSitesMap[F].insert(CallSite);
140 }
141
142 // Returns the Function of the stub if a stub was erased, or NULL if there
143 // was no stub. This function uses the call-site->function map to find a
144 // relevant function, but asserts that only stubs and not other call sites
145 // will be passed in.
146 Function *EraseStub(const MutexGuard &locked, void *Stub) {
147 CallSiteToFunctionMapTy::iterator C2F_I =
148 CallSiteToFunctionMap.find(Stub);
149 if (C2F_I == CallSiteToFunctionMap.end()) {
150 // Not a stub.
151 return NULL;
152 }
153
154 Function *const F = C2F_I->second;
155#ifndef NDEBUG
156 void *RealStub = FunctionToStubMap.lookup(F);
157 assert(RealStub == Stub &&
158 "Call-site that wasn't a stub pass in to EraseStub");
159#endif
160 FunctionToStubMap.erase(F);
161 CallSiteToFunctionMap.erase(C2F_I);
162
163 // Remove the stub from the function->call-sites map, and remove the whole
164 // entry from the map if that was the last call site.
165 FunctionToCallSitesMapTy::iterator F2C_I = FunctionToCallSitesMap.find(F);
166 assert(F2C_I != FunctionToCallSitesMap.end() &&
167 "FunctionToCallSitesMap broken");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000168 bool Erased = F2C_I->second.erase(Stub);
169 (void)Erased;
170 assert(Erased && "FunctionToCallSitesMap broken");
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000171 if (F2C_I->second.empty())
172 FunctionToCallSitesMap.erase(F2C_I);
173
174 return F;
175 }
176
177 void EraseAllCallSites(const MutexGuard &locked, Function *F) {
178 assert(locked.holds(TheJIT->lock));
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000179 EraseAllCallSitesPrelocked(F);
180 }
181 void EraseAllCallSitesPrelocked(Function *F) {
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000182 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
183 if (F2C == FunctionToCallSitesMap.end())
184 return;
185 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
186 E = F2C->second.end(); I != E; ++I) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000187 bool Erased = CallSiteToFunctionMap.erase(*I);
188 (void)Erased;
189 assert(Erased && "Missing call site->function mapping");
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000190 }
191 FunctionToCallSitesMap.erase(F2C);
192 }
Reid Spenceree448632005-07-12 15:51:55 +0000193 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000194
Chris Lattner54266522004-11-20 23:57:07 +0000195 /// JITResolver - Keep track of, and resolve, call sites for functions that
196 /// have not yet been compiled.
197 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000198 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000199 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000200 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
201
Chris Lattner5e225582004-11-21 03:37:42 +0000202 /// LazyResolverFn - The target lazy resolver function that we actually
203 /// rewrite instructions to use.
204 TargetJITInfo::LazyResolverFn LazyResolverFn;
205
Reid Spenceree448632005-07-12 15:51:55 +0000206 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000207
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000208 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
209 /// external functions.
210 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000211
Evan Cheng1606e8e2009-03-13 07:51:59 +0000212 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000213 std::map<void*, unsigned> revGOTMap;
214 unsigned nextGOTIndex;
215
Chris Lattnere7484012007-02-24 02:57:03 +0000216 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000217 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000218 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000219 TheJIT = &jit;
220
221 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
222 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
223 TheJITResolver = this;
224 }
225
226 ~JITResolver() {
227 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000228 }
Chris Lattner54266522004-11-20 23:57:07 +0000229
Evan Cheng704bff92008-11-13 21:50:50 +0000230 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
231 /// if it has already been created.
232 void *getFunctionStubIfAvailable(Function *F);
233
Chris Lattner54266522004-11-20 23:57:07 +0000234 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000235 /// one on demand as needed. If empty is true, create a function stub
236 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000237 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000238
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000239 /// getExternalFunctionStub - Return a stub for the function at the
240 /// specified address, created lazily on demand.
241 void *getExternalFunctionStub(void *FnAddr);
242
Evan Cheng5594f122008-11-10 01:52:24 +0000243 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000244 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000245 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000246
Chris Lattner5e225582004-11-21 03:37:42 +0000247 /// AddCallbackAtLocation - If the target is capable of rewriting an
248 /// instruction without the use of a stub, record the location of the use so
249 /// we know which function is being used at the location.
250 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000251 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000252 /// Get the target-specific JIT resolver function.
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000253 state.AddCallSite(locked, Location, F);
Chris Lattner870286a2006-06-01 17:29:22 +0000254 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000255 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000256
257 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000258 SmallVectorImpl<void*> &Ptrs);
259
260 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000261
Andrew Lenharth6a974612005-07-28 12:44:13 +0000262 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000263 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000264 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000265 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000266
Chris Lattner54266522004-11-20 23:57:07 +0000267 /// JITCompilerFn - This function is called to resolve a stub to a compiled
268 /// address. If the LLVM Function corresponding to the stub has not yet
269 /// been compiled, this function compiles it first.
270 static void *JITCompilerFn(void *Stub);
271 };
272}
273
Chris Lattnere7484012007-02-24 02:57:03 +0000274JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000275
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000276void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
277 JRS->EraseAllCallSitesPrelocked(F);
278}
279
Evan Cheng704bff92008-11-13 21:50:50 +0000280/// getFunctionStubIfAvailable - This returns a pointer to a function stub
281/// if it has already been created.
282void *JITResolver::getFunctionStubIfAvailable(Function *F) {
283 MutexGuard locked(TheJIT->lock);
284
285 // If we already have a stub for this function, recycle it.
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000286 return state.getFunctionToStubMap(locked).lookup(F);
Evan Cheng704bff92008-11-13 21:50:50 +0000287}
288
Chris Lattner54266522004-11-20 23:57:07 +0000289/// getFunctionStub - This returns a pointer to a function stub, creating
290/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000291void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000292 MutexGuard locked(TheJIT->lock);
293
Chris Lattner54266522004-11-20 23:57:07 +0000294 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000295 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000296 if (Stub) return Stub;
297
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000298 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
299 // case we must resolve the symbol now.
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000300 void *Actual = TheJIT->isLazyCompilationDisabled()
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000301 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000302
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000303 // If this is an external declaration, attempt to resolve the address now
304 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000305 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000306 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000307
Dan Gohman69f93782009-01-05 05:32:42 +0000308 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000309 // don't emit a stub. Return a null pointer to the application. If dlsym
310 // stubs are enabled, not being able to resolve the address is not
311 // meaningful.
312 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000313 }
314
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000315 // Codegen a new stub, calling the lazy resolver or the actual address of the
316 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000317 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000318 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000319
Chris Lattner870286a2006-06-01 17:29:22 +0000320 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000321 // If we are getting the stub for an external function, we really want the
322 // address of the stub in the GlobalAddressMap for the JIT, not the address
323 // of the external function.
324 TheJIT->updateGlobalMapping(F, Stub);
325 }
Chris Lattner54266522004-11-20 23:57:07 +0000326
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000327 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
328 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000329
Chris Lattner54266522004-11-20 23:57:07 +0000330 // Finally, keep track of the stub-to-Function mapping so that the
331 // JITCompilerFn knows which function to compile!
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000332 state.AddCallSite(locked, Stub, F);
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000333
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000334 // If we are JIT'ing non-lazily but need to call a function that does not
335 // exist yet, add it to the JIT's work list so that we can fill in the stub
336 // address later.
337 if (!Actual && TheJIT->isLazyCompilationDisabled())
338 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
339 TheJIT->addPendingFunction(F);
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000340
Chris Lattner54266522004-11-20 23:57:07 +0000341 return Stub;
342}
343
Evan Cheng5594f122008-11-10 01:52:24 +0000344/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000345/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000346void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000347 MutexGuard locked(TheJIT->lock);
348
349 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000350 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
351 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000352
Evan Chenge4d783d2008-11-10 23:26:16 +0000353 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000354 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000355 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000356
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000357 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
358 << "] for GV '" << GV->getName() << "'\n");
Evan Chengbe8c03f2008-01-04 10:46:51 +0000359
Evan Cheng5594f122008-11-10 01:52:24 +0000360 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000361}
362
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000363/// getExternalFunctionStub - Return a stub for the function at the
364/// specified address, created lazily on demand.
365void *JITResolver::getExternalFunctionStub(void *FnAddr) {
366 // If we already have a stub for this function, recycle it.
367 void *&Stub = ExternalFnToStubMap[FnAddr];
368 if (Stub) return Stub;
369
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000370 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000371 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000372
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000373 DEBUG(errs() << "JIT: Stub emitted at [" << Stub
374 << "] for external function at '" << FnAddr << "'\n");
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000375 return Stub;
376}
377
Andrew Lenharth6a974612005-07-28 12:44:13 +0000378unsigned JITResolver::getGOTIndexForAddr(void* addr) {
379 unsigned idx = revGOTMap[addr];
380 if (!idx) {
381 idx = ++nextGOTIndex;
382 revGOTMap[addr] = idx;
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000383 DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
384 << addr << "]\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000385 }
386 return idx;
387}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000388
Nate Begemand6b7a242009-02-18 08:31:02 +0000389void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
390 SmallVectorImpl<void*> &Ptrs) {
391 MutexGuard locked(TheJIT->lock);
392
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000393 const FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000394 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000395
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000396 for (FunctionToStubMapTy::const_iterator i = FM.begin(), e = FM.end();
397 i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000398 Function *F = i->first;
399 if (F->isDeclaration() && F->hasExternalLinkage()) {
400 GVs.push_back(i->first);
401 Ptrs.push_back(i->second);
402 }
403 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000404 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000405 i != e; ++i) {
406 GVs.push_back(i->first);
407 Ptrs.push_back(i->second);
408 }
409}
410
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000411GlobalValue *JITResolver::invalidateStub(void *Stub) {
412 MutexGuard locked(TheJIT->lock);
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000413
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000414 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000415
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000416 // Look up the cheap way first, to see if it's a function stub we are
417 // invalidating. If so, remove it from both the forward and reverse maps.
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000418 if (Function *F = state.EraseStub(locked, Stub)) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000419 return F;
420 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000421
Nate Begeman841c6a42009-03-11 07:03:43 +0000422 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000423 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000424 i != e; ++i) {
425 if (i->second != Stub)
426 continue;
427 GlobalValue *GV = i->first;
428 GM.erase(i);
429 return GV;
430 }
431
Nate Begeman841c6a42009-03-11 07:03:43 +0000432 // Lastly, check to see if it's in the ExternalFnToStubMap.
433 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
434 e = ExternalFnToStubMap.end(); i != e; ++i) {
435 if (i->second != Stub)
436 continue;
437 ExternalFnToStubMap.erase(i);
438 break;
439 }
440
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000441 return 0;
442}
443
Chris Lattner54266522004-11-20 23:57:07 +0000444/// JITCompilerFn - This function is called when a lazy compilation stub has
445/// been entered. It looks up which function this stub corresponds to, compiles
446/// it if necessary, then returns the resultant function pointer.
447void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000448 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000449
450 Function* F = 0;
451 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000452
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000453 {
454 // Only lock for getting the Function. The call getPointerToFunction made
455 // in this function might trigger function materializing, which requires
456 // JIT lock to be unlocked.
457 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000458
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000459 // The address given to us for the stub may not be exactly right, it might
460 // be a little bit after the stub. As such, use upper_bound to find it.
461 pair<void*, Function*> I =
462 JR.state.LookupFunctionFromCallSite(locked, Stub);
463 F = I.second;
464 ActualPtr = I.first;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000465 }
Chris Lattner54266522004-11-20 23:57:07 +0000466
Evan Cheng9da60f92007-06-30 00:10:37 +0000467 // If we have already code generated the function, just return the address.
468 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000469
Evan Cheng9da60f92007-06-30 00:10:37 +0000470 if (!Result) {
471 // Otherwise we don't have it, do lazy compilation now.
472
473 // If lazy compilation is disabled, emit a useful error message and abort.
474 if (TheJIT->isLazyCompilationDisabled()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000475 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
476 + F->getName() + "' when lazy compiles are disabled!");
Evan Cheng9da60f92007-06-30 00:10:37 +0000477 }
478
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000479 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
480 << "' In stub ptr = " << Stub << " actual ptr = "
481 << ActualPtr << "\n");
Chris Lattner54266522004-11-20 23:57:07 +0000482
Evan Cheng9da60f92007-06-30 00:10:37 +0000483 Result = TheJIT->getPointerToFunction(F);
484 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000485
486 // Reacquire the lock to update the GOT map.
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000487 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000488
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000489 // We might like to remove the call site from the CallSiteToFunction map, but
490 // we can't do that! Multiple threads could be stuck, waiting to acquire the
491 // lock above. As soon as the 1st function finishes compiling the function,
492 // the next one will be released, and needs to be able to find the function it
493 // needs to call.
Chris Lattner54266522004-11-20 23:57:07 +0000494
495 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000496
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000497 // What we will do is set the compiled function address to map to the
498 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000499 // if they see it still using the stub address.
500 // Note: this is done so the Resolver doesn't have to manage GOT memory
501 // Do this without allocating map space if the target isn't using a GOT
502 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
503 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
504
Chris Lattner54266522004-11-20 23:57:07 +0000505 return Result;
506}
Chris Lattner688506d2003-08-14 18:35:27 +0000507
Chris Lattner8ac66c12008-04-04 05:51:42 +0000508//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000509// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000510//
Chris Lattner688506d2003-08-14 18:35:27 +0000511namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000512 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
513 /// used to output functions to memory for execution.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000514 class JITEmitter : public JITCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000515 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000516
Chris Lattner6125fdd2003-05-09 03:30:07 +0000517 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000518 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000519 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000520
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000521 // When reattempting to JIT a function after running out of space, we store
522 // the estimated size of the function we're trying to JIT here, so we can
523 // ask the memory manager for at least this much space. When we
524 // successfully emit the function, we reset this back to zero.
525 uintptr_t SizeEstimate;
526
Chris Lattner5be478f2004-11-20 03:46:14 +0000527 /// Relocations - These are the relocations that the function needs, as
528 /// emitted.
529 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000530
531 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
532 /// It is filled in by the StartMachineBasicBlock callback and queried by
533 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000534 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000535
Chris Lattner239862c2006-02-09 04:49:59 +0000536 /// ConstantPool - The constant pool for the current function.
537 ///
538 MachineConstantPool *ConstantPool;
539
540 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
541 ///
542 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000543
Evan Cheng1606e8e2009-03-13 07:51:59 +0000544 /// ConstPoolAddresses - Addresses of individual constant pool entries.
545 ///
546 SmallVector<uintptr_t, 8> ConstPoolAddresses;
547
Nate Begeman019f8512006-09-10 23:03:44 +0000548 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000549 ///
550 MachineJumpTableInfo *JumpTable;
551
552 /// JumpTableBase - A pointer to the first entry in the jump table.
553 ///
554 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000555
Chris Lattnere7484012007-02-24 02:57:03 +0000556 /// Resolver - This contains info about the currently resolved functions.
557 JITResolver Resolver;
Reid Kleckner27632172009-09-20 23:52:43 +0000558
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000559 /// DE - The dwarf emitter for the jit.
Reid Kleckner27632172009-09-20 23:52:43 +0000560 OwningPtr<JITDwarfEmitter> DE;
561
562 /// DR - The debug registerer for the jit.
563 OwningPtr<JITDebugRegisterer> DR;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000564
565 /// LabelLocations - This vector is a mapping from Label ID's to their
566 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000567 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000568
569 /// MMI - Machine module info for exception informations
570 MachineModuleInfo* MMI;
571
Dale Johannesendd947ea2008-08-07 01:30:15 +0000572 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000573 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000574
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000575 // CurFn - The llvm function being emitted. Only valid during
576 // finishFunction().
577 const Function *CurFn;
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000578
579 /// Information about emitted code, which is passed to the
580 /// JITEventListeners. This is reset in startFunction and used in
581 /// finishFunction.
582 JITEvent_EmittedFunctionDetails EmissionDetails;
583
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000584 struct EmittedCode {
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000585 void *FunctionBody; // Beginning of the function's allocation.
586 void *Code; // The address the function's code actually starts at.
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000587 void *ExceptionTable;
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000588 EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000589 };
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000590 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
591 typedef JITEmitter *ExtraData;
592 static void onDelete(JITEmitter *, const Function*);
593 static void onRAUW(JITEmitter *, const Function*, const Function*);
594 };
595 ValueMap<const Function *, EmittedCode,
596 EmittedFunctionConfig> EmittedFunctions;
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000597
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000598 // CurFnStubUses - For a given Function, a vector of stubs that it
599 // references. This facilitates the JIT detecting that a stub is no
600 // longer used, so that it may be deallocated.
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000601 DenseMap<AssertingVH<const Function>, SmallVector<void*, 1> > CurFnStubUses;
602
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000603 // StubFnRefs - For a given pointer to a stub, a set of Functions which
604 // reference the stub. When the count of a stub's references drops to zero,
605 // the stub is unused.
606 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
607
Nate Begeman841c6a42009-03-11 07:03:43 +0000608 // ExtFnStubs - A map of external function names to stubs which have entries
609 // in the JITResolver's ExternalFnToStubMap.
610 StringMap<void *> ExtFnStubs;
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000611
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000612 DebugLocTuple PrevDLT;
613
Chris Lattnere7484012007-02-24 02:57:03 +0000614 public:
Reid Kleckner27632172009-09-20 23:52:43 +0000615 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000616 : SizeEstimate(0), Resolver(jit), MMI(0), CurFn(0),
617 EmittedFunctions(this) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000618 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000619 if (jit.getJITInfo().needsGOT()) {
620 MemMgr->AllocateGOT();
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000621 DEBUG(errs() << "JIT is managing a GOT\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000622 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000623
Reid Kleckner27632172009-09-20 23:52:43 +0000624 if (DwarfExceptionHandling || JITEmitDebugInfo) {
625 DE.reset(new JITDwarfEmitter(jit));
626 }
627 if (JITEmitDebugInfo) {
628 DR.reset(new JITDebugRegisterer(TM));
629 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000630 }
631 ~JITEmitter() {
632 delete MemMgr;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000633 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000634
635 /// classof - Methods for support type inquiry through isa, cast, and
636 /// dyn_cast:
637 ///
638 static inline bool classof(const JITEmitter*) { return true; }
639 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000640
641 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000642
643 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000644 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000645
646 void emitConstantPool(MachineConstantPool *MCP);
647 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000648 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000649
Evan Chengce4a70b2008-11-08 08:02:53 +0000650 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000651 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000652 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
653 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000654 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000655
Nuno Lopescef75272008-10-21 11:42:16 +0000656 /// allocateSpace - Reserves space in the current block if any, or
657 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000658 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000659
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000660 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
661 /// this method does not allocate memory in the current output buffer,
662 /// because a global may live longer than the current function.
663 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
664
Chris Lattner5be478f2004-11-20 03:46:14 +0000665 virtual void addRelocation(const MachineRelocation &MR) {
666 Relocations.push_back(MR);
667 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000668
669 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
670 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
671 MBBLocations.resize((MBB->getNumber()+1)*2);
672 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000673 DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
674 << (void*) getCurrentPCValue() << "]\n");
Chris Lattnerb4432f32006-05-03 17:10:41 +0000675 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000676
Evan Cheng5788d1a2008-12-10 02:32:19 +0000677 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
678 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000679
Evan Cheng5788d1a2008-12-10 02:32:19 +0000680 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000681 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
682 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
683 return MBBLocations[MBB->getNumber()];
684 }
685
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000686 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
687 /// given function. Increase the minimum allocation size so that we get
688 /// more memory next time.
689 void retryWithMoreMemory(MachineFunction &F);
690
Chris Lattnere993cc22006-05-11 23:08:08 +0000691 /// deallocateMemForFunction - Deallocate all memory for the specified
692 /// function body.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000693 void deallocateMemForFunction(const Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000694
695 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
696 /// using the stub at the specified address. Allows
697 /// deallocateMemForFunction to also remove stubs no longer referenced.
698 void AddStubToCurrentFunction(void *Stub);
699
700 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
701 /// MachineRelocations that reference external functions by name.
702 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000703
Devang Patel02c04232009-10-06 03:04:58 +0000704 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000705
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000706 virtual void emitLabel(uint64_t LabelID) {
707 if (LabelLocations.size() <= LabelID)
708 LabelLocations.resize((LabelID+1)*2);
709 LabelLocations[LabelID] = getCurrentPCValue();
710 }
711
Evan Cheng5788d1a2008-12-10 02:32:19 +0000712 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000713 assert(LabelLocations.size() > (unsigned)LabelID &&
714 LabelLocations[LabelID] && "Label not emitted!");
715 return LabelLocations[LabelID];
716 }
717
718 virtual void setModuleInfo(MachineModuleInfo* Info) {
719 MMI = Info;
Reid Kleckner27632172009-09-20 23:52:43 +0000720 if (DE.get()) DE->setModuleInfo(Info);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000721 }
722
Dan Gohmana9ad0412009-08-12 22:10:57 +0000723 void setMemoryExecutable() {
Jim Grosbachcce6c292008-10-03 16:17:20 +0000724 MemMgr->setMemoryExecutable();
725 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000726
Dan Gohmana9ad0412009-08-12 22:10:57 +0000727 JITMemoryManager *getMemMgr() const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000728
Chris Lattner54266522004-11-20 23:57:07 +0000729 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000730 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000731 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000732 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000733 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
734 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
735 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
736 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000737 };
738}
739
Chris Lattner166f2262004-11-22 22:00:25 +0000740void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
741 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000742 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000743 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000744
Chris Lattner18e04592008-06-25 20:21:35 +0000745 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000746 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000747
748 // If we have already compiled the function, return a pointer to its body.
749 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000750 void *ResultPtr;
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000751 if (!DoesntNeedStub) {
Evan Cheng704bff92008-11-13 21:50:50 +0000752 // Return the function stub if it's already created.
753 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000754 if (ResultPtr)
755 AddStubToCurrentFunction(ResultPtr);
756 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000757 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000758 }
Chris Lattner54266522004-11-20 23:57:07 +0000759 if (ResultPtr) return ResultPtr;
760
Nate Begemand6b7a242009-02-18 08:31:02 +0000761 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000762 // 'compile' it, which really just adds it to the map. In dlsym mode,
763 // external functions are forced through a stub, regardless of reloc type.
764 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
765 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000766 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000767
Chris Lattner5e225582004-11-21 03:37:42 +0000768 // Okay, the function has not been compiled yet, if the target callback
769 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000770 // that instead of emitting a stub. This uses the lazy resolver, so is not
771 // legal if lazy compilation is disabled.
772 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000773 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000774
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000775 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000776 void *StubAddr = Resolver.getFunctionStub(F);
777
778 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000779 // deallocate them if the current function is ever freed. It's possible to
780 // return null from getFunctionStub in the case of a weak extern that fails
781 // to resolve.
782 if (StubAddr)
783 AddStubToCurrentFunction(StubAddr);
784
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000785 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000786}
787
Evan Cheng5594f122008-11-10 01:52:24 +0000788void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000789 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000790 // Make sure GV is emitted first, and create a stub containing the fully
791 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000792 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000793 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
794
795 // Add the stub to the current function's list of referenced stubs, so we can
796 // deallocate them if the current function is ever freed.
797 AddStubToCurrentFunction(StubAddr);
798
799 return StubAddr;
800}
801
802void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000803 assert(CurFn && "Stub added to current function, but current function is 0!");
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000804
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000805 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
806 StubsUsed.push_back(StubAddr);
807
808 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
809 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000810}
811
Devang Patel02c04232009-10-06 03:04:58 +0000812void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000813 if (!DL.isUnknown()) {
814 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
815
Devang Patel02c04232009-10-06 03:04:58 +0000816 if (BeforePrintingInsn) {
Devang Patel1619dc32009-10-13 23:28:53 +0000817 if (CurDLT.Scope != 0 && PrevDLT != CurDLT) {
Devang Patel02c04232009-10-06 03:04:58 +0000818 JITEvent_EmittedFunctionDetails::LineStart NextLine;
819 NextLine.Address = getCurrentPCValue();
820 NextLine.Loc = DL;
821 EmissionDetails.LineStarts.push_back(NextLine);
822 }
823
824 PrevDLT = CurDLT;
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000825 }
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000826 }
827}
828
Evan Cheng1606e8e2009-03-13 07:51:59 +0000829static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
830 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000831 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
832 if (Constants.empty()) return 0;
833
Evan Cheng1606e8e2009-03-13 07:51:59 +0000834 unsigned Size = 0;
835 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
836 MachineConstantPoolEntry CPE = Constants[i];
837 unsigned AlignMask = CPE.getAlignment() - 1;
838 Size = (Size + AlignMask) & ~AlignMask;
839 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000840 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000841 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000842 return Size;
843}
844
845static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
846 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
847 if (JT.empty()) return 0;
848
849 unsigned NumEntries = 0;
850 for (unsigned i = 0, e = JT.size(); i != e; ++i)
851 NumEntries += JT[i].MBBs.size();
852
853 unsigned EntrySize = MJTI->getEntrySize();
854
855 return NumEntries * EntrySize;
856}
857
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000858static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000859 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000860 // Since we do not know where the buffer will be allocated, be pessimistic.
861 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000862}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000863
Dale Johannesendd947ea2008-08-07 01:30:15 +0000864/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
865/// into the running total Size.
866
867unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
868 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000869 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000870 size_t GVAlign =
871 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000872 DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000873 DEBUG(GV->dump());
874 // Assume code section ends with worst possible alignment, so first
875 // variable needs maximal padding.
876 if (Size==0)
877 Size = 1;
878 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
879 Size += GVSize;
880 return Size;
881}
882
883/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
884/// but are referenced from the constant; put them in GVSet and add their
885/// size into the running total Size.
886
887unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
888 unsigned Size) {
889 // If its undefined, return the garbage.
890 if (isa<UndefValue>(C))
891 return Size;
892
893 // If the value is a ConstantExpr
894 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
895 Constant *Op0 = CE->getOperand(0);
896 switch (CE->getOpcode()) {
897 case Instruction::GetElementPtr:
898 case Instruction::Trunc:
899 case Instruction::ZExt:
900 case Instruction::SExt:
901 case Instruction::FPTrunc:
902 case Instruction::FPExt:
903 case Instruction::UIToFP:
904 case Instruction::SIToFP:
905 case Instruction::FPToUI:
906 case Instruction::FPToSI:
907 case Instruction::PtrToInt:
908 case Instruction::IntToPtr:
909 case Instruction::BitCast: {
910 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
911 break;
912 }
913 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000914 case Instruction::FAdd:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000915 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000916 case Instruction::FSub:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000917 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000918 case Instruction::FMul:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000919 case Instruction::UDiv:
920 case Instruction::SDiv:
921 case Instruction::URem:
922 case Instruction::SRem:
923 case Instruction::And:
924 case Instruction::Or:
925 case Instruction::Xor: {
926 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
927 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
928 break;
929 }
930 default: {
Torok Edwin7d696d82009-07-11 13:10:19 +0000931 std::string msg;
932 raw_string_ostream Msg(msg);
933 Msg << "ConstantExpr not handled: " << *CE;
934 llvm_report_error(Msg.str());
Dale Johannesendd947ea2008-08-07 01:30:15 +0000935 }
936 }
937 }
938
939 if (C->getType()->getTypeID() == Type::PointerTyID)
940 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000941 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000942 Size = addSizeOfGlobal(GV, Size);
943
944 return Size;
945}
946
947/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
948/// but are referenced from the given initializer.
949
950unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
951 unsigned Size) {
952 if (!isa<UndefValue>(Init) &&
953 !isa<ConstantVector>(Init) &&
954 !isa<ConstantAggregateZero>(Init) &&
955 !isa<ConstantArray>(Init) &&
956 !isa<ConstantStruct>(Init) &&
957 Init->getType()->isFirstClassType())
958 Size = addSizeOfGlobalsInConstantVal(Init, Size);
959 return Size;
960}
961
962/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
963/// globals; then walk the initializers of those globals looking for more.
964/// If their size has not been considered yet, add it into the running total
965/// Size.
966
967unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
968 unsigned Size = 0;
969 GVSet.clear();
970
971 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
972 MBB != E; ++MBB) {
973 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
974 I != E; ++I) {
975 const TargetInstrDesc &Desc = I->getDesc();
976 const MachineInstr &MI = *I;
977 unsigned NumOps = Desc.getNumOperands();
978 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
979 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000980 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000981 GlobalValue* V = MO.getGlobal();
982 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
983 if (!GV)
984 continue;
985 // If seen in previous function, it will have an entry here.
986 if (TheJIT->getPointerToGlobalIfAvailable(GV))
987 continue;
988 // If seen earlier in this function, it will have an entry here.
989 // FIXME: it should be possible to combine these tables, by
990 // assuming the addresses of the new globals in this module
991 // start at 0 (or something) and adjusting them after codegen
992 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000993 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000994 // A variable as yet unseen. Add in its size.
995 Size = addSizeOfGlobal(GV, Size);
996 }
997 }
998 }
999 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001000 DEBUG(errs() << "JIT: About to look through initializers\n");
Dale Johannesendd947ea2008-08-07 01:30:15 +00001001 // Look for more globals that are referenced only from initializers.
1002 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +00001003 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +00001004 I != GVSet.end(); I++) {
1005 const GlobalVariable* GV = *I;
1006 if (GV->hasInitializer())
1007 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
1008 }
1009
1010 return Size;
1011}
1012
Chris Lattner166f2262004-11-22 22:00:25 +00001013void JITEmitter::startFunction(MachineFunction &F) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001014 DEBUG(errs() << "JIT: Starting CodeGen of Function "
1015 << F.getFunction()->getName() << "\n");
Evan Chengeb5d95a2008-11-06 17:46:04 +00001016
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001017 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +00001018 // Set the memory writable, if it's not already
1019 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001020 if (MemMgr->NeedsExactSize()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001021 DEBUG(errs() << "JIT: ExactSize\n");
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001022 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
1023 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
1024 MachineConstantPool *MCP = F.getConstantPool();
1025
1026 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001027 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001028
1029 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +00001030 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001031
1032 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +00001033 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001034
1035 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001036 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001037
1038 // Add the jump table size
1039 ActualSize += GetJumpTableSizeInBytes(MJTI);
1040
1041 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001042 ActualSize = RoundUpToAlign(ActualSize,
1043 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001044
1045 // Add the function size
1046 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +00001047
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001048 DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
Dale Johannesendd947ea2008-08-07 01:30:15 +00001049 // Add the size of the globals that will be allocated after this function.
1050 // These are all the ones referenced from this function that were not
1051 // previously allocated.
1052 ActualSize += GetSizeOfGlobalsInBytes(F);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001053 DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001054 } else if (SizeEstimate > 0) {
1055 // SizeEstimate will be non-zero on reallocation attempts.
1056 ActualSize = SizeEstimate;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001057 }
1058
Chris Lattner8907b4b2007-12-05 23:39:57 +00001059 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1060 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +00001061 BufferEnd = BufferBegin+ActualSize;
Jeffrey Yasskin1e861322009-10-20 18:13:21 +00001062 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
1063
Evan Cheng9a1e9b92006-11-16 20:04:54 +00001064 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1065 emitAlignment(16);
1066
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001067 emitConstantPool(F.getConstantPool());
1068 initJumpTableInfo(F.getJumpTableInfo());
1069
1070 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +00001071 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001072 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +00001073 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
Evan Cheng55fc2802006-07-25 20:40:54 +00001074
Chris Lattnerb4432f32006-05-03 17:10:41 +00001075 MBBLocations.clear();
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00001076
1077 EmissionDetails.MF = &F;
1078 EmissionDetails.LineStarts.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001079}
1080
Chris Lattner43b429b2006-05-02 18:27:26 +00001081bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +00001082 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001083 // We must call endFunctionBody before retrying, because
1084 // deallocateMemForFunction requires it.
1085 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1086 retryWithMoreMemory(F);
1087 return true;
Chris Lattnere993cc22006-05-11 23:08:08 +00001088 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001089
Jim Laskeyb92767a2006-12-14 22:53:42 +00001090 emitJumpTableInfo(F.getJumpTableInfo());
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001091
Chris Lattnera8279532006-06-16 18:09:26 +00001092 // FnStart is the start of the text, not the start of the constant pool and
1093 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001094 uint8_t *FnStart =
1095 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001096
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001097 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001098 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001099
Chris Lattner5be478f2004-11-20 03:46:14 +00001100 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001101 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +00001102 NumRelos += Relocations.size();
1103
Chris Lattner5be478f2004-11-20 03:46:14 +00001104 // Resolve the relocations to concrete pointers.
1105 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1106 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001107 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001108 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001109 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001110 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1111 false);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001112 DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1113 << ResultPtr << "]\n");
Misha Brukmanf976c852005-04-21 22:55:34 +00001114
Evan Chengef5784e2008-10-29 23:54:46 +00001115 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001116 if (!MR.doesntNeedStub()) {
1117 if (!TheJIT->areDlsymStubsEnabled()) {
1118 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1119 } else {
1120 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1121 if (!Stub) {
1122 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1123 AddStubToCurrentFunction(Stub);
1124 }
1125 ResultPtr = Stub;
1126 }
1127 }
Evan Chengef5784e2008-10-29 23:54:46 +00001128 } else if (MR.isGlobalValue()) {
1129 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1130 BufferBegin+MR.getMachineCodeOffset(),
1131 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001132 } else if (MR.isIndirectSymbol()) {
1133 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001134 BufferBegin+MR.getMachineCodeOffset(),
1135 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001136 } else if (MR.isBasicBlock()) {
1137 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1138 } else if (MR.isConstantPoolIndex()) {
1139 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1140 } else {
1141 assert(MR.isJumpTableIndex());
1142 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1143 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001144
Evan Chengef5784e2008-10-29 23:54:46 +00001145 MR.setResultPointer(ResultPtr);
1146 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001147
Andrew Lenharth6a974612005-07-28 12:44:13 +00001148 // if we are managing the GOT and the relocation wants an index,
1149 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001150 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001151 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001152 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001153 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001154 DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1155 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1156 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +00001157 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001158 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001159 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001160 }
1161
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001162 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001163 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001164 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001165 }
1166
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001167 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001168 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001169 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001170 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001171 DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1172 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1173 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +00001174 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001175 }
1176 }
1177
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001178 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1179 // global variables that were referenced in the relocations.
1180 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001181
1182 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001183 retryWithMoreMemory(F);
1184 return true;
1185 } else {
1186 // Now that we've succeeded in emitting the function, reset the
1187 // SizeEstimate back down to zero.
1188 SizeEstimate = 0;
Evan Cheng5788d1a2008-12-10 02:32:19 +00001189 }
1190
Nuno Lopescef75272008-10-21 11:42:16 +00001191 BufferBegin = CurBufferPtr = 0;
1192 NumBytes += FnEnd-FnStart;
1193
Evan Cheng55fc2802006-07-25 20:40:54 +00001194 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001195 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001196
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001197 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00001198 EmissionDetails);
Evan Cheng55fc2802006-07-25 20:40:54 +00001199
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001200 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1201 << "] Function: " << F.getFunction()->getName()
1202 << ": " << (FnEnd-FnStart) << " bytes of text, "
1203 << Relocations.size() << " relocations\n");
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001204
Chris Lattner5be478f2004-11-20 03:46:14 +00001205 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001206 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001207
Evan Chengbc4707a2008-09-18 07:54:21 +00001208 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001209 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001210
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001211 DEBUG(
Evan Chenge7c35512008-11-12 08:22:43 +00001212 if (sys::hasDisassembler()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001213 errs() << "JIT: Disassembled code:\n";
1214 errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1215 (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001216 } else {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001217 errs() << "JIT: Binary code:\n";
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001218 uint8_t* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001219 for (int i = 0; q < FnEnd; q += 4, ++i) {
1220 if (i == 4)
1221 i = 0;
1222 if (i == 0)
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001223 errs() << "JIT: " << (long)(q - FnStart) << ": ";
Evan Chenge7c35512008-11-12 08:22:43 +00001224 bool Done = false;
1225 for (int j = 3; j >= 0; --j) {
1226 if (q + j >= FnEnd)
1227 Done = true;
1228 else
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001229 errs() << (unsigned short)q[j];
Evan Chenge7c35512008-11-12 08:22:43 +00001230 }
1231 if (Done)
1232 break;
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001233 errs() << ' ';
Evan Chenge7c35512008-11-12 08:22:43 +00001234 if (i == 3)
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001235 errs() << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001236 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001237 errs()<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001238 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001239 );
1240
Reid Kleckner27632172009-09-20 23:52:43 +00001241 if (DwarfExceptionHandling || JITEmitDebugInfo) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001242 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001243 SavedBufferBegin = BufferBegin;
1244 SavedBufferEnd = BufferEnd;
1245 SavedCurBufferPtr = CurBufferPtr;
Reid Kleckner27632172009-09-20 23:52:43 +00001246
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001247 if (MemMgr->NeedsExactSize()) {
1248 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001249 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001250
1251 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1252 ActualSize);
1253 BufferEnd = BufferBegin+ActualSize;
Jeffrey Yasskin1e861322009-10-20 18:13:21 +00001254 EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
Reid Kleckner27632172009-09-20 23:52:43 +00001255 uint8_t *EhStart;
1256 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1257 EhStart);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001258 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1259 FrameRegister);
Reid Kleckner27632172009-09-20 23:52:43 +00001260 uint8_t *EhEnd = CurBufferPtr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001261 BufferBegin = SavedBufferBegin;
1262 BufferEnd = SavedBufferEnd;
1263 CurBufferPtr = SavedCurBufferPtr;
1264
Reid Kleckner27632172009-09-20 23:52:43 +00001265 if (DwarfExceptionHandling) {
1266 TheJIT->RegisterTable(FrameRegister);
1267 }
1268
1269 if (JITEmitDebugInfo) {
1270 DebugInfo I;
1271 I.FnStart = FnStart;
1272 I.FnEnd = FnEnd;
1273 I.EhStart = EhStart;
1274 I.EhEnd = EhEnd;
1275 DR->RegisterFunction(F.getFunction(), I);
1276 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001277 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001278
1279 if (MMI)
1280 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001281
Chris Lattner43b429b2006-05-02 18:27:26 +00001282 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001283}
1284
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001285void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001286 DEBUG(errs() << "JIT: Ran out of space for native code. Reattempting.\n");
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001287 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1288 ConstPoolAddresses.clear();
1289 ++NumRetries;
1290 deallocateMemForFunction(F.getFunction());
1291 // Try again with at least twice as much free space.
1292 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1293}
1294
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001295/// deallocateMemForFunction - Deallocate all memory for the specified
1296/// function body. Also drop any references the function has to stubs.
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +00001297/// May be called while the Function is being destroyed inside ~Value().
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001298void JITEmitter::deallocateMemForFunction(const Function *F) {
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +00001299 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
1300 Emitted = EmittedFunctions.find(F);
Jeffrey Yasskin1e861322009-10-20 18:13:21 +00001301 if (Emitted != EmittedFunctions.end()) {
1302 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
1303 MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +00001304 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
1305
Jeffrey Yasskin1e861322009-10-20 18:13:21 +00001306 EmittedFunctions.erase(Emitted);
1307 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001308
Reid Kleckner27632172009-09-20 23:52:43 +00001309 // TODO: Do we need to unregister exception handling information from libgcc
1310 // here?
1311
1312 if (JITEmitDebugInfo) {
1313 DR->UnregisterFunction(F);
1314 }
1315
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001316 // If the function did not reference any stubs, return.
1317 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1318 return;
1319
1320 // For each referenced stub, erase the reference to this function, and then
1321 // erase the list of referenced stubs.
1322 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1323 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1324 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001325
1326 // If we already invalidated this stub for this function, continue.
1327 if (StubFnRefs.count(Stub) == 0)
1328 continue;
1329
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001330 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1331 FnRefs.erase(F);
1332
1333 // If this function was the last reference to the stub, invalidate the stub
1334 // in the JITResolver. Were there a memory manager deallocateStub routine,
1335 // we could call that at this point too.
1336 if (FnRefs.empty()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001337 DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
Nate Begeman841c6a42009-03-11 07:03:43 +00001338 StubFnRefs.erase(Stub);
1339
1340 // Invalidate the stub. If it is a GV stub, update the JIT's global
1341 // mapping for that GV to zero, otherwise, search the string map of
1342 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001343 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001344 if (GV) {
1345 TheJIT->updateGlobalMapping(GV, 0);
1346 } else {
1347 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1348 e = ExtFnStubs.end(); i != e; ++i) {
1349 if (i->second == Stub) {
1350 ExtFnStubs.erase(i);
1351 break;
1352 }
1353 }
1354 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001355 }
1356 }
1357 CurFnStubUses.erase(F);
1358}
1359
1360
Evan Cheng5788d1a2008-12-10 02:32:19 +00001361void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001362 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001363 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +00001364
1365 // create a new memory block if there is no active one.
1366 // care must be taken so that BufferBegin is invalidated when a
1367 // block is trimmed
1368 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1369 BufferEnd = BufferBegin+Size;
1370 return CurBufferPtr;
1371}
1372
Jeffrey Yasskin489393d2009-07-08 21:59:57 +00001373void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1374 // Delegate this call through the memory manager.
1375 return MemMgr->allocateGlobal(Size, Alignment);
1376}
1377
Chris Lattner166f2262004-11-22 22:00:25 +00001378void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001379 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001380 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001381
Chris Lattnerfa77d432006-02-09 04:22:52 +00001382 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001383 if (Constants.empty()) return;
1384
Evan Cheng1606e8e2009-03-13 07:51:59 +00001385 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1386 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001387 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001388 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001389
1390 if (ConstantPoolBase == 0) return; // Buffer overflow.
1391
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001392 DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1393 << "] (size: " << Size << ", alignment: " << Align << ")\n");
Evan Cheng97b8c402008-04-12 00:22:01 +00001394
Chris Lattner239862c2006-02-09 04:49:59 +00001395 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001396 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001397 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001398 MachineConstantPoolEntry CPE = Constants[i];
1399 unsigned AlignMask = CPE.getAlignment() - 1;
1400 Offset = (Offset + AlignMask) & ~AlignMask;
1401
1402 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1403 ConstPoolAddresses.push_back(CAddr);
1404 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001405 // FIXME: add support to lower machine constant pool values into bytes!
Torok Edwin7d696d82009-07-11 13:10:19 +00001406 llvm_report_error("Initialize memory with machine specific constant pool"
1407 "entry has not been implemented!");
Evan Chengcd5731d2006-09-12 20:59:59 +00001408 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001409 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001410 DEBUG(errs() << "JIT: CP" << i << " at [0x";
1411 errs().write_hex(CAddr) << "]\n");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001412
1413 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001414 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001415 }
1416}
1417
Nate Begeman37efe672006-04-22 18:53:45 +00001418void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001419 if (TheJIT->getJITInfo().hasCustomJumpTables())
1420 return;
1421
Nate Begeman37efe672006-04-22 18:53:45 +00001422 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1423 if (JT.empty()) return;
1424
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001425 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001426 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001427 NumEntries += JT[i].MBBs.size();
1428
1429 unsigned EntrySize = MJTI->getEntrySize();
1430
Nate Begeman37efe672006-04-22 18:53:45 +00001431 // Just allocate space for all the jump tables now. We will fix up the actual
1432 // MBB entries in the tables after we emit the code for each block, since then
1433 // we will know the final locations of the MBBs in memory.
1434 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001435 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001436}
1437
Jim Laskeyb92767a2006-12-14 22:53:42 +00001438void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001439 if (TheJIT->getJITInfo().hasCustomJumpTables())
1440 return;
1441
Nate Begeman37efe672006-04-22 18:53:45 +00001442 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001443 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001444
Jim Laskeyb92767a2006-12-14 22:53:42 +00001445 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001446 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1447 // For each jump table, place the offset from the beginning of the table
1448 // to the target address.
1449 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001450
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001451 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1452 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1453 // Store the offset of the basic block for this jump table slot in the
1454 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001455 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001456 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001457 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001458 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1459 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001460 }
1461 } else {
1462 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1463
1464 // For each jump table, map each target in the jump table to the address of
1465 // an emitted MachineBasicBlock.
1466 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1467
1468 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1469 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1470 // Store the address of the basic block for this jump table slot in the
1471 // memory we allocated for the jump table in 'initJumpTableInfo'
1472 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1473 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1474 }
Nate Begeman37efe672006-04-22 18:53:45 +00001475 }
1476}
1477
Evan Chengce4a70b2008-11-08 08:02:53 +00001478void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1479 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001480 SavedBufferBegin = BufferBegin;
1481 SavedBufferEnd = BufferEnd;
1482 SavedCurBufferPtr = CurBufferPtr;
1483
Evan Chengce4a70b2008-11-08 08:02:53 +00001484 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001485 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001486}
1487
Nate Begemand6b7a242009-02-18 08:31:02 +00001488void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1489 unsigned StubSize) {
1490 SavedBufferBegin = BufferBegin;
1491 SavedBufferEnd = BufferEnd;
1492 SavedCurBufferPtr = CurBufferPtr;
1493
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001494 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001495 BufferEnd = BufferBegin+StubSize+1;
1496}
1497
Evan Chengce4a70b2008-11-08 08:02:53 +00001498void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001499 NumBytes += getCurrentPCOffset();
1500 std::swap(SavedBufferBegin, BufferBegin);
1501 BufferEnd = SavedBufferEnd;
1502 CurBufferPtr = SavedCurBufferPtr;
1503 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001504}
1505
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001506// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1507// in the constant pool that was last emitted with the 'emitConstantPool'
1508// method.
1509//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001510uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001511 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001512 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001513 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001514}
1515
Nate Begeman37efe672006-04-22 18:53:45 +00001516// getJumpTableEntryAddress - Return the address of the JumpTable with index
1517// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1518//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001519uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001520 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1521 assert(Index < JT.size() && "Invalid jump table index!");
1522
1523 unsigned Offset = 0;
1524 unsigned EntrySize = JumpTable->getEntrySize();
1525
1526 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001527 Offset += JT[i].MBBs.size();
1528
1529 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001530
Evan Cheng5788d1a2008-12-10 02:32:19 +00001531 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001532}
1533
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +00001534void JITEmitter::EmittedFunctionConfig::onDelete(
1535 JITEmitter *Emitter, const Function *F) {
1536 Emitter->deallocateMemForFunction(F);
1537}
1538void JITEmitter::EmittedFunctionConfig::onRAUW(
1539 JITEmitter *, const Function*, const Function*) {
1540 llvm_unreachable("The JIT doesn't know how to handle a"
1541 " RAUW on a value it has emitted.");
1542}
1543
1544
Chris Lattnere993cc22006-05-11 23:08:08 +00001545//===----------------------------------------------------------------------===//
1546// Public interface to this file
1547//===----------------------------------------------------------------------===//
1548
Reid Kleckner27632172009-09-20 23:52:43 +00001549JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1550 TargetMachine &tm) {
1551 return new JITEmitter(jit, JMM, tm);
Chris Lattnere993cc22006-05-11 23:08:08 +00001552}
1553
Misha Brukmand69c1e62003-07-28 19:09:06 +00001554// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001555// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001556// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1557// need to resolve function(s) that are being mis-codegenerated, so we need to
1558// resolve their addresses at runtime, and this is the way to do it.
1559extern "C" {
1560 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001561 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001562 return TheJIT->getPointerToFunction(F);
1563 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001564 }
1565}
Chris Lattnere993cc22006-05-11 23:08:08 +00001566
1567// getPointerToFunctionOrStub - If the specified function has been
1568// code-gen'd, return a pointer to the function. If not, compile it, or use
1569// a stub to implement lazy compilation if available.
1570//
1571void *JIT::getPointerToFunctionOrStub(Function *F) {
1572 // If we have already code generated the function, just return the address.
1573 if (void *Addr = getPointerToGlobalIfAvailable(F))
1574 return Addr;
1575
Chris Lattnere7484012007-02-24 02:57:03 +00001576 // Get a stub if the target supports it.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001577 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Chenga044dfc2008-08-20 00:28:12 +00001578 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001579 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001580}
1581
Nate Begemand6b7a242009-02-18 08:31:02 +00001582void JIT::updateFunctionStub(Function *F) {
1583 // Get the empty stub we generated earlier.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001584 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001585 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1586 void *Stub = JE->getJITResolver().getFunctionStub(F);
1587
1588 // Tell the target jit info to rewrite the stub at the specified address,
1589 // rather than creating a new one.
1590 void *Addr = getPointerToGlobalIfAvailable(F);
1591 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1592}
1593
1594/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1595/// that were emitted during code generation.
1596///
1597void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001598 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001599 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1600
1601 SmallVector<GlobalValue*, 8> GVs;
1602 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001603 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001604
1605 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1606
Nate Begeman841c6a42009-03-11 07:03:43 +00001607 unsigned nStubs = GVs.size() + ExtFns.size();
1608
Nate Begemand6b7a242009-02-18 08:31:02 +00001609 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001610 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001611 return;
1612
1613 // If there are no new relocatable stubs, return.
1614 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001615 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001616 return;
1617
1618 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001619 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001620
1621 SmallVector<unsigned, 8> Offsets;
1622 for (unsigned i = 0; i != GVs.size(); ++i) {
1623 Offsets.push_back(offset);
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001624 offset += GVs[i]->getName().size() + 1;
Nate Begemand6b7a242009-02-18 08:31:02 +00001625 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001626 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1627 i != e; ++i) {
1628 Offsets.push_back(offset);
1629 offset += strlen(i->first()) + 1;
1630 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001631
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001632 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001633 JE->startGVStub(0, offset, 4);
1634
1635 // Emit the number of records
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001636 JE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001637
1638 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001639 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001640 JE->emitInt32(Offsets[i]);
Nate Begemand6b7a242009-02-18 08:31:02 +00001641
Nate Begeman66941982009-03-04 19:10:38 +00001642 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1643 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1644 // relocation can write the relocated pointer at the appropriate place in
1645 // the stub.
1646 for (unsigned i = 0; i != GVs.size(); ++i) {
1647 intptr_t Ptr = (intptr_t)Ptrs[i];
1648 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1649
1650 if (isa<Function>(GVs[i]))
1651 Ptr |= (intptr_t)1;
1652
Nate Begeman841c6a42009-03-11 07:03:43 +00001653 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001654 JE->emitInt64(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001655 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001656 JE->emitInt32(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001657 }
1658 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1659 i != e; ++i) {
1660 intptr_t Ptr = (intptr_t)i->second | 1;
1661
1662 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001663 JE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001664 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001665 JE->emitInt32(Ptr);
Nate Begeman66941982009-03-04 19:10:38 +00001666 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001667
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001668 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001669 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001670 JE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001671 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1672 i != e; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001673 JE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001674
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001675 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1676 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001677 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1678}
1679
Chris Lattnere993cc22006-05-11 23:08:08 +00001680/// freeMachineCodeForFunction - release machine code memory for given Function.
1681///
1682void JIT::freeMachineCodeForFunction(Function *F) {
1683 // Delete translation for this from the ExecutionEngine, so it will get
1684 // retranslated next time it is used.
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +00001685 updateGlobalMapping(F, 0);
Chris Lattnere993cc22006-05-11 23:08:08 +00001686
1687 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001688 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1689 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001690}