blob: 073d6fbbde6a2fc7a1766ec11912403a2d1e7b22 [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"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000049#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000050#ifndef NDEBUG
51#include <iomanip>
52#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000053using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000054
Chris Lattner36343732006-12-19 22:43:32 +000055STATISTIC(NumBytes, "Number of bytes of machine code compiled");
56STATISTIC(NumRelos, "Number of relocations applied");
Reid Kleckner10b4fc52009-07-23 21:46:56 +000057STATISTIC(NumRetries, "Number of retries with more memory");
Chris Lattner36343732006-12-19 22:43:32 +000058static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000059
Andrew Lenhartha00269b2005-07-29 23:40:16 +000060
Chris Lattner54266522004-11-20 23:57:07 +000061//===----------------------------------------------------------------------===//
62// JIT lazy compilation code.
63//
64namespace {
Reid Spenceree448632005-07-12 15:51:55 +000065 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000066 public:
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +000067 typedef DenseMap<AssertingVH<Function>, void*> FunctionToStubMapTy;
68 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
69 typedef DenseMap<AssertingVH<Function>, SmallPtrSet<void*, 1> >
70 FunctionToCallSitesMapTy;
Nick Lewyckye2bcf132009-04-27 05:09:44 +000071 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000072 private:
73 /// FunctionToStubMap - Keep track of the stub created for a particular
74 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000075 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000076
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +000077 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
78 /// site corresponds to, and vice versa.
79 CallSiteToFunctionMapTy CallSiteToFunctionMap;
80 FunctionToCallSitesMapTy FunctionToCallSitesMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000081
Evan Cheng5594f122008-11-10 01:52:24 +000082 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000083 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000084 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000085
Reid Spenceree448632005-07-12 15:51:55 +000086 public:
Nick Lewyckye2bcf132009-04-27 05:09:44 +000087 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000088 assert(locked.holds(TheJIT->lock));
89 return FunctionToStubMap;
90 }
Jeff Cohen00b168892005-07-27 06:12:32 +000091
Nick Lewyckye2bcf132009-04-27 05:09:44 +000092 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000093 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000094 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000095 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +000096
97 pair<void *, Function *> LookupFunctionFromCallSite(
98 const MutexGuard &locked, void *CallSite) const {
99 assert(locked.holds(TheJIT->lock));
100
101 // The address given to us for the stub may not be exactly right, it might be
102 // a little bit after the stub. As such, use upper_bound to find it.
103 CallSiteToFunctionMapTy::const_iterator I =
104 CallSiteToFunctionMap.upper_bound(CallSite);
105 assert(I != CallSiteToFunctionMap.begin() &&
106 "This is not a known call site!");
107 --I;
108 return *I;
109 }
110
111 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
112 assert(locked.holds(TheJIT->lock));
113
114 assert(CallSiteToFunctionMap.insert(std::make_pair(CallSite, F)).second &&
115 "Pair was already in CallSiteToFunctionMap");
116 FunctionToCallSitesMap[F].insert(CallSite);
117 }
118
119 // Returns the Function of the stub if a stub was erased, or NULL if there
120 // was no stub. This function uses the call-site->function map to find a
121 // relevant function, but asserts that only stubs and not other call sites
122 // will be passed in.
123 Function *EraseStub(const MutexGuard &locked, void *Stub) {
124 CallSiteToFunctionMapTy::iterator C2F_I =
125 CallSiteToFunctionMap.find(Stub);
126 if (C2F_I == CallSiteToFunctionMap.end()) {
127 // Not a stub.
128 return NULL;
129 }
130
131 Function *const F = C2F_I->second;
132#ifndef NDEBUG
133 void *RealStub = FunctionToStubMap.lookup(F);
134 assert(RealStub == Stub &&
135 "Call-site that wasn't a stub pass in to EraseStub");
136#endif
137 FunctionToStubMap.erase(F);
138 CallSiteToFunctionMap.erase(C2F_I);
139
140 // Remove the stub from the function->call-sites map, and remove the whole
141 // entry from the map if that was the last call site.
142 FunctionToCallSitesMapTy::iterator F2C_I = FunctionToCallSitesMap.find(F);
143 assert(F2C_I != FunctionToCallSitesMap.end() &&
144 "FunctionToCallSitesMap broken");
145 assert(F2C_I->second.erase(Stub) &&
146 "FunctionToCallSitesMap broken");
147 if (F2C_I->second.empty())
148 FunctionToCallSitesMap.erase(F2C_I);
149
150 return F;
151 }
152
153 void EraseAllCallSites(const MutexGuard &locked, Function *F) {
154 assert(locked.holds(TheJIT->lock));
155 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
156 if (F2C == FunctionToCallSitesMap.end())
157 return;
158 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
159 E = F2C->second.end(); I != E; ++I) {
160 assert(CallSiteToFunctionMap.erase(*I) == 1 &&
161 "Missing call site->function mapping");
162 }
163 FunctionToCallSitesMap.erase(F2C);
164 }
Reid Spenceree448632005-07-12 15:51:55 +0000165 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000166
Chris Lattner54266522004-11-20 23:57:07 +0000167 /// JITResolver - Keep track of, and resolve, call sites for functions that
168 /// have not yet been compiled.
169 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000170 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000171 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000172 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
173
Chris Lattner5e225582004-11-21 03:37:42 +0000174 /// LazyResolverFn - The target lazy resolver function that we actually
175 /// rewrite instructions to use.
176 TargetJITInfo::LazyResolverFn LazyResolverFn;
177
Reid Spenceree448632005-07-12 15:51:55 +0000178 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000179
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000180 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
181 /// external functions.
182 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000183
Evan Cheng1606e8e2009-03-13 07:51:59 +0000184 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000185 std::map<void*, unsigned> revGOTMap;
186 unsigned nextGOTIndex;
187
Chris Lattnere7484012007-02-24 02:57:03 +0000188 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000189 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000190 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000191 TheJIT = &jit;
192
193 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
194 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
195 TheJITResolver = this;
196 }
197
198 ~JITResolver() {
199 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000200 }
Chris Lattner54266522004-11-20 23:57:07 +0000201
Evan Cheng704bff92008-11-13 21:50:50 +0000202 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
203 /// if it has already been created.
204 void *getFunctionStubIfAvailable(Function *F);
205
Chris Lattner54266522004-11-20 23:57:07 +0000206 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000207 /// one on demand as needed. If empty is true, create a function stub
208 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000209 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000210
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000211 /// getExternalFunctionStub - Return a stub for the function at the
212 /// specified address, created lazily on demand.
213 void *getExternalFunctionStub(void *FnAddr);
214
Evan Cheng5594f122008-11-10 01:52:24 +0000215 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000216 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000217 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000218
Chris Lattner5e225582004-11-21 03:37:42 +0000219 /// AddCallbackAtLocation - If the target is capable of rewriting an
220 /// instruction without the use of a stub, record the location of the use so
221 /// we know which function is being used at the location.
222 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000223 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000224 /// Get the target-specific JIT resolver function.
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000225 state.AddCallSite(locked, Location, F);
Chris Lattner870286a2006-06-01 17:29:22 +0000226 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000227 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000228
229 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000230 SmallVectorImpl<void*> &Ptrs);
231
232 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000233
Andrew Lenharth6a974612005-07-28 12:44:13 +0000234 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000235 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000236 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000237 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000238
Chris Lattner54266522004-11-20 23:57:07 +0000239 /// JITCompilerFn - This function is called to resolve a stub to a compiled
240 /// address. If the LLVM Function corresponding to the stub has not yet
241 /// been compiled, this function compiles it first.
242 static void *JITCompilerFn(void *Stub);
243 };
244}
245
Chris Lattnere7484012007-02-24 02:57:03 +0000246JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000247
Evan Cheng704bff92008-11-13 21:50:50 +0000248/// getFunctionStubIfAvailable - This returns a pointer to a function stub
249/// if it has already been created.
250void *JITResolver::getFunctionStubIfAvailable(Function *F) {
251 MutexGuard locked(TheJIT->lock);
252
253 // If we already have a stub for this function, recycle it.
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000254 return state.getFunctionToStubMap(locked).lookup(F);
Evan Cheng704bff92008-11-13 21:50:50 +0000255}
256
Chris Lattner54266522004-11-20 23:57:07 +0000257/// getFunctionStub - This returns a pointer to a function stub, creating
258/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000259void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000260 MutexGuard locked(TheJIT->lock);
261
Chris Lattner54266522004-11-20 23:57:07 +0000262 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000263 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000264 if (Stub) return Stub;
265
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000266 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
267 // case we must resolve the symbol now.
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000268 void *Actual = TheJIT->isLazyCompilationDisabled()
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000269 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000270
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000271 // If this is an external declaration, attempt to resolve the address now
272 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000273 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000274 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000275
Dan Gohman69f93782009-01-05 05:32:42 +0000276 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000277 // don't emit a stub. Return a null pointer to the application. If dlsym
278 // stubs are enabled, not being able to resolve the address is not
279 // meaningful.
280 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000281 }
282
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000283 // Codegen a new stub, calling the lazy resolver or the actual address of the
284 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000285 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000286 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000287
Chris Lattner870286a2006-06-01 17:29:22 +0000288 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000289 // If we are getting the stub for an external function, we really want the
290 // address of the stub in the GlobalAddressMap for the JIT, not the address
291 // of the external function.
292 TheJIT->updateGlobalMapping(F, Stub);
293 }
Chris Lattner54266522004-11-20 23:57:07 +0000294
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000295 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
296 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000297
Chris Lattner54266522004-11-20 23:57:07 +0000298 // Finally, keep track of the stub-to-Function mapping so that the
299 // JITCompilerFn knows which function to compile!
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000300 state.AddCallSite(locked, Stub, F);
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000301
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000302 // If we are JIT'ing non-lazily but need to call a function that does not
303 // exist yet, add it to the JIT's work list so that we can fill in the stub
304 // address later.
305 if (!Actual && TheJIT->isLazyCompilationDisabled())
306 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
307 TheJIT->addPendingFunction(F);
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000308
Chris Lattner54266522004-11-20 23:57:07 +0000309 return Stub;
310}
311
Evan Cheng5594f122008-11-10 01:52:24 +0000312/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000313/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000314void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000315 MutexGuard locked(TheJIT->lock);
316
317 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000318 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
319 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000320
Evan Chenge4d783d2008-11-10 23:26:16 +0000321 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000322 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000323 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000324
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000325 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
326 << "] for GV '" << GV->getName() << "'\n");
Evan Chengbe8c03f2008-01-04 10:46:51 +0000327
Evan Cheng5594f122008-11-10 01:52:24 +0000328 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000329}
330
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000331/// getExternalFunctionStub - Return a stub for the function at the
332/// specified address, created lazily on demand.
333void *JITResolver::getExternalFunctionStub(void *FnAddr) {
334 // If we already have a stub for this function, recycle it.
335 void *&Stub = ExternalFnToStubMap[FnAddr];
336 if (Stub) return Stub;
337
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000338 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000339 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000340
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000341 DEBUG(errs() << "JIT: Stub emitted at [" << Stub
342 << "] for external function at '" << FnAddr << "'\n");
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000343 return Stub;
344}
345
Andrew Lenharth6a974612005-07-28 12:44:13 +0000346unsigned JITResolver::getGOTIndexForAddr(void* addr) {
347 unsigned idx = revGOTMap[addr];
348 if (!idx) {
349 idx = ++nextGOTIndex;
350 revGOTMap[addr] = idx;
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000351 DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
352 << addr << "]\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000353 }
354 return idx;
355}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000356
Nate Begemand6b7a242009-02-18 08:31:02 +0000357void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
358 SmallVectorImpl<void*> &Ptrs) {
359 MutexGuard locked(TheJIT->lock);
360
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000361 const FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000362 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000363
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000364 for (FunctionToStubMapTy::const_iterator i = FM.begin(), e = FM.end();
365 i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000366 Function *F = i->first;
367 if (F->isDeclaration() && F->hasExternalLinkage()) {
368 GVs.push_back(i->first);
369 Ptrs.push_back(i->second);
370 }
371 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000372 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000373 i != e; ++i) {
374 GVs.push_back(i->first);
375 Ptrs.push_back(i->second);
376 }
377}
378
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000379GlobalValue *JITResolver::invalidateStub(void *Stub) {
380 MutexGuard locked(TheJIT->lock);
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000381
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000382 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000383
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000384 // Look up the cheap way first, to see if it's a function stub we are
385 // invalidating. If so, remove it from both the forward and reverse maps.
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000386 if (Function *F = state.EraseStub(locked, Stub)) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000387 return F;
388 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000389
Nate Begeman841c6a42009-03-11 07:03:43 +0000390 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000391 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000392 i != e; ++i) {
393 if (i->second != Stub)
394 continue;
395 GlobalValue *GV = i->first;
396 GM.erase(i);
397 return GV;
398 }
399
Nate Begeman841c6a42009-03-11 07:03:43 +0000400 // Lastly, check to see if it's in the ExternalFnToStubMap.
401 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
402 e = ExternalFnToStubMap.end(); i != e; ++i) {
403 if (i->second != Stub)
404 continue;
405 ExternalFnToStubMap.erase(i);
406 break;
407 }
408
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000409 return 0;
410}
411
Chris Lattner54266522004-11-20 23:57:07 +0000412/// JITCompilerFn - This function is called when a lazy compilation stub has
413/// been entered. It looks up which function this stub corresponds to, compiles
414/// it if necessary, then returns the resultant function pointer.
415void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000416 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000417
418 Function* F = 0;
419 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000420
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000421 {
422 // Only lock for getting the Function. The call getPointerToFunction made
423 // in this function might trigger function materializing, which requires
424 // JIT lock to be unlocked.
425 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000426
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000427 // The address given to us for the stub may not be exactly right, it might
428 // be a little bit after the stub. As such, use upper_bound to find it.
429 pair<void*, Function*> I =
430 JR.state.LookupFunctionFromCallSite(locked, Stub);
431 F = I.second;
432 ActualPtr = I.first;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000433 }
Chris Lattner54266522004-11-20 23:57:07 +0000434
Evan Cheng9da60f92007-06-30 00:10:37 +0000435 // If we have already code generated the function, just return the address.
436 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000437
Evan Cheng9da60f92007-06-30 00:10:37 +0000438 if (!Result) {
439 // Otherwise we don't have it, do lazy compilation now.
440
441 // If lazy compilation is disabled, emit a useful error message and abort.
442 if (TheJIT->isLazyCompilationDisabled()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000443 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
444 + F->getName() + "' when lazy compiles are disabled!");
Evan Cheng9da60f92007-06-30 00:10:37 +0000445 }
446
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000447 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
448 << "' In stub ptr = " << Stub << " actual ptr = "
449 << ActualPtr << "\n");
Chris Lattner54266522004-11-20 23:57:07 +0000450
Evan Cheng9da60f92007-06-30 00:10:37 +0000451 Result = TheJIT->getPointerToFunction(F);
452 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000453
454 // Reacquire the lock to update the GOT map.
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000455 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000456
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000457 // We might like to remove the call site from the CallSiteToFunction map, but
458 // we can't do that! Multiple threads could be stuck, waiting to acquire the
459 // lock above. As soon as the 1st function finishes compiling the function,
460 // the next one will be released, and needs to be able to find the function it
461 // needs to call.
Chris Lattner54266522004-11-20 23:57:07 +0000462
463 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000464
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000465 // What we will do is set the compiled function address to map to the
466 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000467 // if they see it still using the stub address.
468 // Note: this is done so the Resolver doesn't have to manage GOT memory
469 // Do this without allocating map space if the target isn't using a GOT
470 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
471 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
472
Chris Lattner54266522004-11-20 23:57:07 +0000473 return Result;
474}
Chris Lattner688506d2003-08-14 18:35:27 +0000475
Chris Lattner8ac66c12008-04-04 05:51:42 +0000476//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000477// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000478//
Chris Lattner688506d2003-08-14 18:35:27 +0000479namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000480 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
481 /// used to output functions to memory for execution.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000482 class JITEmitter : public JITCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000483 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000484
Chris Lattner6125fdd2003-05-09 03:30:07 +0000485 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000486 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000487 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000488
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000489 // When reattempting to JIT a function after running out of space, we store
490 // the estimated size of the function we're trying to JIT here, so we can
491 // ask the memory manager for at least this much space. When we
492 // successfully emit the function, we reset this back to zero.
493 uintptr_t SizeEstimate;
494
Chris Lattner5be478f2004-11-20 03:46:14 +0000495 /// Relocations - These are the relocations that the function needs, as
496 /// emitted.
497 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000498
499 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
500 /// It is filled in by the StartMachineBasicBlock callback and queried by
501 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000502 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000503
Chris Lattner239862c2006-02-09 04:49:59 +0000504 /// ConstantPool - The constant pool for the current function.
505 ///
506 MachineConstantPool *ConstantPool;
507
508 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
509 ///
510 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000511
Evan Cheng1606e8e2009-03-13 07:51:59 +0000512 /// ConstPoolAddresses - Addresses of individual constant pool entries.
513 ///
514 SmallVector<uintptr_t, 8> ConstPoolAddresses;
515
Nate Begeman019f8512006-09-10 23:03:44 +0000516 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000517 ///
518 MachineJumpTableInfo *JumpTable;
519
520 /// JumpTableBase - A pointer to the first entry in the jump table.
521 ///
522 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000523
Chris Lattnere7484012007-02-24 02:57:03 +0000524 /// Resolver - This contains info about the currently resolved functions.
525 JITResolver Resolver;
Reid Kleckner27632172009-09-20 23:52:43 +0000526
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000527 /// DE - The dwarf emitter for the jit.
Reid Kleckner27632172009-09-20 23:52:43 +0000528 OwningPtr<JITDwarfEmitter> DE;
529
530 /// DR - The debug registerer for the jit.
531 OwningPtr<JITDebugRegisterer> DR;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000532
533 /// LabelLocations - This vector is a mapping from Label ID's to their
534 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000535 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000536
537 /// MMI - Machine module info for exception informations
538 MachineModuleInfo* MMI;
539
Dale Johannesendd947ea2008-08-07 01:30:15 +0000540 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000541 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000542
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000543 // CurFn - The llvm function being emitted. Only valid during
544 // finishFunction().
545 const Function *CurFn;
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000546
547 /// Information about emitted code, which is passed to the
548 /// JITEventListeners. This is reset in startFunction and used in
549 /// finishFunction.
550 JITEvent_EmittedFunctionDetails EmissionDetails;
551
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000552 struct EmittedCode {
553 void *FunctionBody;
554 void *ExceptionTable;
555 EmittedCode() : FunctionBody(0), ExceptionTable(0) {}
556 };
557 DenseMap<const Function *, EmittedCode> EmittedFunctions;
558
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000559 // CurFnStubUses - For a given Function, a vector of stubs that it
560 // references. This facilitates the JIT detecting that a stub is no
561 // longer used, so that it may be deallocated.
562 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
563
564 // StubFnRefs - For a given pointer to a stub, a set of Functions which
565 // reference the stub. When the count of a stub's references drops to zero,
566 // the stub is unused.
567 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
568
Nate Begeman841c6a42009-03-11 07:03:43 +0000569 // ExtFnStubs - A map of external function names to stubs which have entries
570 // in the JITResolver's ExternalFnToStubMap.
571 StringMap<void *> ExtFnStubs;
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000572
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000573 DebugLocTuple PrevDLT;
574
Chris Lattnere7484012007-02-24 02:57:03 +0000575 public:
Reid Kleckner27632172009-09-20 23:52:43 +0000576 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
Xerxes Ranby3d47db52009-08-25 10:12:55 +0000577 : SizeEstimate(0), Resolver(jit), MMI(0), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000578 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000579 if (jit.getJITInfo().needsGOT()) {
580 MemMgr->AllocateGOT();
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000581 DEBUG(errs() << "JIT is managing a GOT\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000582 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000583
Reid Kleckner27632172009-09-20 23:52:43 +0000584 if (DwarfExceptionHandling || JITEmitDebugInfo) {
585 DE.reset(new JITDwarfEmitter(jit));
586 }
587 if (JITEmitDebugInfo) {
588 DR.reset(new JITDebugRegisterer(TM));
589 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000590 }
591 ~JITEmitter() {
592 delete MemMgr;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000593 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000594
595 /// classof - Methods for support type inquiry through isa, cast, and
596 /// dyn_cast:
597 ///
598 static inline bool classof(const JITEmitter*) { return true; }
599 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000600
601 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000602
603 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000604 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000605
606 void emitConstantPool(MachineConstantPool *MCP);
607 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000608 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000609
Evan Chengce4a70b2008-11-08 08:02:53 +0000610 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000611 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000612 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
613 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000614 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000615
Nuno Lopescef75272008-10-21 11:42:16 +0000616 /// allocateSpace - Reserves space in the current block if any, or
617 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000618 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000619
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000620 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
621 /// this method does not allocate memory in the current output buffer,
622 /// because a global may live longer than the current function.
623 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
624
Chris Lattner5be478f2004-11-20 03:46:14 +0000625 virtual void addRelocation(const MachineRelocation &MR) {
626 Relocations.push_back(MR);
627 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000628
629 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
630 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
631 MBBLocations.resize((MBB->getNumber()+1)*2);
632 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000633 DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
634 << (void*) getCurrentPCValue() << "]\n");
Chris Lattnerb4432f32006-05-03 17:10:41 +0000635 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000636
Evan Cheng5788d1a2008-12-10 02:32:19 +0000637 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
638 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000639
Evan Cheng5788d1a2008-12-10 02:32:19 +0000640 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000641 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
642 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
643 return MBBLocations[MBB->getNumber()];
644 }
645
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000646 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
647 /// given function. Increase the minimum allocation size so that we get
648 /// more memory next time.
649 void retryWithMoreMemory(MachineFunction &F);
650
Chris Lattnere993cc22006-05-11 23:08:08 +0000651 /// deallocateMemForFunction - Deallocate all memory for the specified
652 /// function body.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000653 void deallocateMemForFunction(const Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000654
655 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
656 /// using the stub at the specified address. Allows
657 /// deallocateMemForFunction to also remove stubs no longer referenced.
658 void AddStubToCurrentFunction(void *Stub);
659
660 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
661 /// MachineRelocations that reference external functions by name.
662 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000663
Devang Patel02c04232009-10-06 03:04:58 +0000664 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000665
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000666 virtual void emitLabel(uint64_t LabelID) {
667 if (LabelLocations.size() <= LabelID)
668 LabelLocations.resize((LabelID+1)*2);
669 LabelLocations[LabelID] = getCurrentPCValue();
670 }
671
Evan Cheng5788d1a2008-12-10 02:32:19 +0000672 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000673 assert(LabelLocations.size() > (unsigned)LabelID &&
674 LabelLocations[LabelID] && "Label not emitted!");
675 return LabelLocations[LabelID];
676 }
677
678 virtual void setModuleInfo(MachineModuleInfo* Info) {
679 MMI = Info;
Reid Kleckner27632172009-09-20 23:52:43 +0000680 if (DE.get()) DE->setModuleInfo(Info);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000681 }
682
Dan Gohmana9ad0412009-08-12 22:10:57 +0000683 void setMemoryExecutable() {
Jim Grosbachcce6c292008-10-03 16:17:20 +0000684 MemMgr->setMemoryExecutable();
685 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000686
Dan Gohmana9ad0412009-08-12 22:10:57 +0000687 JITMemoryManager *getMemMgr() const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000688
Chris Lattner54266522004-11-20 23:57:07 +0000689 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000690 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000691 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000692 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000693 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
694 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
695 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
696 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000697 };
698}
699
Chris Lattner166f2262004-11-22 22:00:25 +0000700void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
701 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000702 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000703 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000704
Chris Lattner18e04592008-06-25 20:21:35 +0000705 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000706 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000707
708 // If we have already compiled the function, return a pointer to its body.
709 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000710 void *ResultPtr;
Jeffrey Yasskinea5ed002009-10-06 00:35:55 +0000711 if (!DoesntNeedStub) {
Evan Cheng704bff92008-11-13 21:50:50 +0000712 // Return the function stub if it's already created.
713 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000714 if (ResultPtr)
715 AddStubToCurrentFunction(ResultPtr);
716 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000717 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000718 }
Chris Lattner54266522004-11-20 23:57:07 +0000719 if (ResultPtr) return ResultPtr;
720
Nate Begemand6b7a242009-02-18 08:31:02 +0000721 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000722 // 'compile' it, which really just adds it to the map. In dlsym mode,
723 // external functions are forced through a stub, regardless of reloc type.
724 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
725 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000726 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000727
Chris Lattner5e225582004-11-21 03:37:42 +0000728 // Okay, the function has not been compiled yet, if the target callback
729 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000730 // that instead of emitting a stub. This uses the lazy resolver, so is not
731 // legal if lazy compilation is disabled.
732 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000733 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000734
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000735 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000736 void *StubAddr = Resolver.getFunctionStub(F);
737
738 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000739 // deallocate them if the current function is ever freed. It's possible to
740 // return null from getFunctionStub in the case of a weak extern that fails
741 // to resolve.
742 if (StubAddr)
743 AddStubToCurrentFunction(StubAddr);
744
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000745 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000746}
747
Evan Cheng5594f122008-11-10 01:52:24 +0000748void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000749 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000750 // Make sure GV is emitted first, and create a stub containing the fully
751 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000752 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000753 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
754
755 // Add the stub to the current function's list of referenced stubs, so we can
756 // deallocate them if the current function is ever freed.
757 AddStubToCurrentFunction(StubAddr);
758
759 return StubAddr;
760}
761
762void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000763 assert(CurFn && "Stub added to current function, but current function is 0!");
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000764
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000765 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
766 StubsUsed.push_back(StubAddr);
767
768 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
769 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000770}
771
Devang Patel02c04232009-10-06 03:04:58 +0000772void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000773 if (!DL.isUnknown()) {
774 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
775
Devang Patel02c04232009-10-06 03:04:58 +0000776 if (BeforePrintingInsn) {
Devang Patel1619dc32009-10-13 23:28:53 +0000777 if (CurDLT.Scope != 0 && PrevDLT != CurDLT) {
Devang Patel02c04232009-10-06 03:04:58 +0000778 JITEvent_EmittedFunctionDetails::LineStart NextLine;
779 NextLine.Address = getCurrentPCValue();
780 NextLine.Loc = DL;
781 EmissionDetails.LineStarts.push_back(NextLine);
782 }
783
784 PrevDLT = CurDLT;
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000785 }
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000786 }
787}
788
Evan Cheng1606e8e2009-03-13 07:51:59 +0000789static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
790 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000791 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
792 if (Constants.empty()) return 0;
793
Evan Cheng1606e8e2009-03-13 07:51:59 +0000794 unsigned Size = 0;
795 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
796 MachineConstantPoolEntry CPE = Constants[i];
797 unsigned AlignMask = CPE.getAlignment() - 1;
798 Size = (Size + AlignMask) & ~AlignMask;
799 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000800 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000801 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000802 return Size;
803}
804
805static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
806 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
807 if (JT.empty()) return 0;
808
809 unsigned NumEntries = 0;
810 for (unsigned i = 0, e = JT.size(); i != e; ++i)
811 NumEntries += JT[i].MBBs.size();
812
813 unsigned EntrySize = MJTI->getEntrySize();
814
815 return NumEntries * EntrySize;
816}
817
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000818static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000819 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000820 // Since we do not know where the buffer will be allocated, be pessimistic.
821 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000822}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000823
Dale Johannesendd947ea2008-08-07 01:30:15 +0000824/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
825/// into the running total Size.
826
827unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
828 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000829 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000830 size_t GVAlign =
831 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000832 DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000833 DEBUG(GV->dump());
834 // Assume code section ends with worst possible alignment, so first
835 // variable needs maximal padding.
836 if (Size==0)
837 Size = 1;
838 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
839 Size += GVSize;
840 return Size;
841}
842
843/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
844/// but are referenced from the constant; put them in GVSet and add their
845/// size into the running total Size.
846
847unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
848 unsigned Size) {
849 // If its undefined, return the garbage.
850 if (isa<UndefValue>(C))
851 return Size;
852
853 // If the value is a ConstantExpr
854 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
855 Constant *Op0 = CE->getOperand(0);
856 switch (CE->getOpcode()) {
857 case Instruction::GetElementPtr:
858 case Instruction::Trunc:
859 case Instruction::ZExt:
860 case Instruction::SExt:
861 case Instruction::FPTrunc:
862 case Instruction::FPExt:
863 case Instruction::UIToFP:
864 case Instruction::SIToFP:
865 case Instruction::FPToUI:
866 case Instruction::FPToSI:
867 case Instruction::PtrToInt:
868 case Instruction::IntToPtr:
869 case Instruction::BitCast: {
870 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
871 break;
872 }
873 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000874 case Instruction::FAdd:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000875 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000876 case Instruction::FSub:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000877 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000878 case Instruction::FMul:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000879 case Instruction::UDiv:
880 case Instruction::SDiv:
881 case Instruction::URem:
882 case Instruction::SRem:
883 case Instruction::And:
884 case Instruction::Or:
885 case Instruction::Xor: {
886 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
887 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
888 break;
889 }
890 default: {
Torok Edwin7d696d82009-07-11 13:10:19 +0000891 std::string msg;
892 raw_string_ostream Msg(msg);
893 Msg << "ConstantExpr not handled: " << *CE;
894 llvm_report_error(Msg.str());
Dale Johannesendd947ea2008-08-07 01:30:15 +0000895 }
896 }
897 }
898
899 if (C->getType()->getTypeID() == Type::PointerTyID)
900 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000901 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000902 Size = addSizeOfGlobal(GV, Size);
903
904 return Size;
905}
906
907/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
908/// but are referenced from the given initializer.
909
910unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
911 unsigned Size) {
912 if (!isa<UndefValue>(Init) &&
913 !isa<ConstantVector>(Init) &&
914 !isa<ConstantAggregateZero>(Init) &&
915 !isa<ConstantArray>(Init) &&
916 !isa<ConstantStruct>(Init) &&
917 Init->getType()->isFirstClassType())
918 Size = addSizeOfGlobalsInConstantVal(Init, Size);
919 return Size;
920}
921
922/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
923/// globals; then walk the initializers of those globals looking for more.
924/// If their size has not been considered yet, add it into the running total
925/// Size.
926
927unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
928 unsigned Size = 0;
929 GVSet.clear();
930
931 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
932 MBB != E; ++MBB) {
933 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
934 I != E; ++I) {
935 const TargetInstrDesc &Desc = I->getDesc();
936 const MachineInstr &MI = *I;
937 unsigned NumOps = Desc.getNumOperands();
938 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
939 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000940 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000941 GlobalValue* V = MO.getGlobal();
942 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
943 if (!GV)
944 continue;
945 // If seen in previous function, it will have an entry here.
946 if (TheJIT->getPointerToGlobalIfAvailable(GV))
947 continue;
948 // If seen earlier in this function, it will have an entry here.
949 // FIXME: it should be possible to combine these tables, by
950 // assuming the addresses of the new globals in this module
951 // start at 0 (or something) and adjusting them after codegen
952 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000953 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000954 // A variable as yet unseen. Add in its size.
955 Size = addSizeOfGlobal(GV, Size);
956 }
957 }
958 }
959 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000960 DEBUG(errs() << "JIT: About to look through initializers\n");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000961 // Look for more globals that are referenced only from initializers.
962 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000963 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000964 I != GVSet.end(); I++) {
965 const GlobalVariable* GV = *I;
966 if (GV->hasInitializer())
967 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
968 }
969
970 return Size;
971}
972
Chris Lattner166f2262004-11-22 22:00:25 +0000973void JITEmitter::startFunction(MachineFunction &F) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000974 DEBUG(errs() << "JIT: Starting CodeGen of Function "
975 << F.getFunction()->getName() << "\n");
Evan Chengeb5d95a2008-11-06 17:46:04 +0000976
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000977 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000978 // Set the memory writable, if it's not already
979 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000980 if (MemMgr->NeedsExactSize()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000981 DEBUG(errs() << "JIT: ExactSize\n");
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000982 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
983 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
984 MachineConstantPool *MCP = F.getConstantPool();
985
986 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000987 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000988
989 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000990 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000991
992 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +0000993 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000994
995 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000996 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000997
998 // Add the jump table size
999 ActualSize += GetJumpTableSizeInBytes(MJTI);
1000
1001 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001002 ActualSize = RoundUpToAlign(ActualSize,
1003 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001004
1005 // Add the function size
1006 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +00001007
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001008 DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
Dale Johannesendd947ea2008-08-07 01:30:15 +00001009 // Add the size of the globals that will be allocated after this function.
1010 // These are all the ones referenced from this function that were not
1011 // previously allocated.
1012 ActualSize += GetSizeOfGlobalsInBytes(F);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001013 DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001014 } else if (SizeEstimate > 0) {
1015 // SizeEstimate will be non-zero on reallocation attempts.
1016 ActualSize = SizeEstimate;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001017 }
1018
Chris Lattner8907b4b2007-12-05 23:39:57 +00001019 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1020 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +00001021 BufferEnd = BufferBegin+ActualSize;
Jeffrey Yasskin1e861322009-10-20 18:13:21 +00001022 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
1023
Evan Cheng9a1e9b92006-11-16 20:04:54 +00001024 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1025 emitAlignment(16);
1026
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001027 emitConstantPool(F.getConstantPool());
1028 initJumpTableInfo(F.getJumpTableInfo());
1029
1030 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +00001031 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001032 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +00001033
Chris Lattnerb4432f32006-05-03 17:10:41 +00001034 MBBLocations.clear();
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00001035
1036 EmissionDetails.MF = &F;
1037 EmissionDetails.LineStarts.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001038}
1039
Chris Lattner43b429b2006-05-02 18:27:26 +00001040bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +00001041 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001042 // We must call endFunctionBody before retrying, because
1043 // deallocateMemForFunction requires it.
1044 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1045 retryWithMoreMemory(F);
1046 return true;
Chris Lattnere993cc22006-05-11 23:08:08 +00001047 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001048
Jim Laskeyb92767a2006-12-14 22:53:42 +00001049 emitJumpTableInfo(F.getJumpTableInfo());
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001050
Chris Lattnera8279532006-06-16 18:09:26 +00001051 // FnStart is the start of the text, not the start of the constant pool and
1052 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001053 uint8_t *FnStart =
1054 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001055
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001056 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001057 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001058
Chris Lattner5be478f2004-11-20 03:46:14 +00001059 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001060 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +00001061 NumRelos += Relocations.size();
1062
Chris Lattner5be478f2004-11-20 03:46:14 +00001063 // Resolve the relocations to concrete pointers.
1064 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1065 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001066 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001067 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001068 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001069 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1070 false);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001071 DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1072 << ResultPtr << "]\n");
Misha Brukmanf976c852005-04-21 22:55:34 +00001073
Evan Chengef5784e2008-10-29 23:54:46 +00001074 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001075 if (!MR.doesntNeedStub()) {
1076 if (!TheJIT->areDlsymStubsEnabled()) {
1077 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1078 } else {
1079 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1080 if (!Stub) {
1081 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1082 AddStubToCurrentFunction(Stub);
1083 }
1084 ResultPtr = Stub;
1085 }
1086 }
Evan Chengef5784e2008-10-29 23:54:46 +00001087 } else if (MR.isGlobalValue()) {
1088 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1089 BufferBegin+MR.getMachineCodeOffset(),
1090 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001091 } else if (MR.isIndirectSymbol()) {
1092 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001093 BufferBegin+MR.getMachineCodeOffset(),
1094 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001095 } else if (MR.isBasicBlock()) {
1096 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1097 } else if (MR.isConstantPoolIndex()) {
1098 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1099 } else {
1100 assert(MR.isJumpTableIndex());
1101 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1102 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001103
Evan Chengef5784e2008-10-29 23:54:46 +00001104 MR.setResultPointer(ResultPtr);
1105 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001106
Andrew Lenharth6a974612005-07-28 12:44:13 +00001107 // if we are managing the GOT and the relocation wants an index,
1108 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001109 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001110 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001111 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001112 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001113 DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1114 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1115 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +00001116 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001117 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001118 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001119 }
1120
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001121 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001122 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001123 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001124 }
1125
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001126 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001127 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001128 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001129 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001130 DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1131 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1132 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +00001133 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001134 }
1135 }
1136
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001137 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1138 // global variables that were referenced in the relocations.
1139 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001140
1141 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001142 retryWithMoreMemory(F);
1143 return true;
1144 } else {
1145 // Now that we've succeeded in emitting the function, reset the
1146 // SizeEstimate back down to zero.
1147 SizeEstimate = 0;
Evan Cheng5788d1a2008-12-10 02:32:19 +00001148 }
1149
Nuno Lopescef75272008-10-21 11:42:16 +00001150 BufferBegin = CurBufferPtr = 0;
1151 NumBytes += FnEnd-FnStart;
1152
Evan Cheng55fc2802006-07-25 20:40:54 +00001153 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001154 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001155
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001156 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00001157 EmissionDetails);
Evan Cheng55fc2802006-07-25 20:40:54 +00001158
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001159 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1160 << "] Function: " << F.getFunction()->getName()
1161 << ": " << (FnEnd-FnStart) << " bytes of text, "
1162 << Relocations.size() << " relocations\n");
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001163
Chris Lattner5be478f2004-11-20 03:46:14 +00001164 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001165 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001166
Evan Chengbc4707a2008-09-18 07:54:21 +00001167 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001168 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001169
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001170 DEBUG(
Evan Chenge7c35512008-11-12 08:22:43 +00001171 if (sys::hasDisassembler()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001172 errs() << "JIT: Disassembled code:\n";
1173 errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1174 (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001175 } else {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001176 errs() << "JIT: Binary code:\n";
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001177 uint8_t* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001178 for (int i = 0; q < FnEnd; q += 4, ++i) {
1179 if (i == 4)
1180 i = 0;
1181 if (i == 0)
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001182 errs() << "JIT: " << (long)(q - FnStart) << ": ";
Evan Chenge7c35512008-11-12 08:22:43 +00001183 bool Done = false;
1184 for (int j = 3; j >= 0; --j) {
1185 if (q + j >= FnEnd)
1186 Done = true;
1187 else
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001188 errs() << (unsigned short)q[j];
Evan Chenge7c35512008-11-12 08:22:43 +00001189 }
1190 if (Done)
1191 break;
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001192 errs() << ' ';
Evan Chenge7c35512008-11-12 08:22:43 +00001193 if (i == 3)
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001194 errs() << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001195 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001196 errs()<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001197 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001198 );
1199
Reid Kleckner27632172009-09-20 23:52:43 +00001200 if (DwarfExceptionHandling || JITEmitDebugInfo) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001201 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001202 SavedBufferBegin = BufferBegin;
1203 SavedBufferEnd = BufferEnd;
1204 SavedCurBufferPtr = CurBufferPtr;
Reid Kleckner27632172009-09-20 23:52:43 +00001205
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001206 if (MemMgr->NeedsExactSize()) {
1207 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001208 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001209
1210 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1211 ActualSize);
1212 BufferEnd = BufferBegin+ActualSize;
Jeffrey Yasskin1e861322009-10-20 18:13:21 +00001213 EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
Reid Kleckner27632172009-09-20 23:52:43 +00001214 uint8_t *EhStart;
1215 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1216 EhStart);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001217 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1218 FrameRegister);
Reid Kleckner27632172009-09-20 23:52:43 +00001219 uint8_t *EhEnd = CurBufferPtr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001220 BufferBegin = SavedBufferBegin;
1221 BufferEnd = SavedBufferEnd;
1222 CurBufferPtr = SavedCurBufferPtr;
1223
Reid Kleckner27632172009-09-20 23:52:43 +00001224 if (DwarfExceptionHandling) {
1225 TheJIT->RegisterTable(FrameRegister);
1226 }
1227
1228 if (JITEmitDebugInfo) {
1229 DebugInfo I;
1230 I.FnStart = FnStart;
1231 I.FnEnd = FnEnd;
1232 I.EhStart = EhStart;
1233 I.EhEnd = EhEnd;
1234 DR->RegisterFunction(F.getFunction(), I);
1235 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001236 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001237
1238 if (MMI)
1239 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001240
Chris Lattner43b429b2006-05-02 18:27:26 +00001241 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001242}
1243
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001244void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001245 DEBUG(errs() << "JIT: Ran out of space for native code. Reattempting.\n");
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001246 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1247 ConstPoolAddresses.clear();
1248 ++NumRetries;
1249 deallocateMemForFunction(F.getFunction());
1250 // Try again with at least twice as much free space.
1251 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1252}
1253
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001254/// deallocateMemForFunction - Deallocate all memory for the specified
1255/// function body. Also drop any references the function has to stubs.
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001256void JITEmitter::deallocateMemForFunction(const Function *F) {
Jeffrey Yasskin1e861322009-10-20 18:13:21 +00001257 DenseMap<const Function *, EmittedCode>::iterator Emitted =
1258 EmittedFunctions.find(F);
1259 if (Emitted != EmittedFunctions.end()) {
1260 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
1261 MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
1262 EmittedFunctions.erase(Emitted);
1263 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001264
Reid Kleckner27632172009-09-20 23:52:43 +00001265 // TODO: Do we need to unregister exception handling information from libgcc
1266 // here?
1267
1268 if (JITEmitDebugInfo) {
1269 DR->UnregisterFunction(F);
1270 }
1271
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001272 // If the function did not reference any stubs, return.
1273 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1274 return;
1275
1276 // For each referenced stub, erase the reference to this function, and then
1277 // erase the list of referenced stubs.
1278 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1279 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1280 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001281
1282 // If we already invalidated this stub for this function, continue.
1283 if (StubFnRefs.count(Stub) == 0)
1284 continue;
1285
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001286 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1287 FnRefs.erase(F);
1288
1289 // If this function was the last reference to the stub, invalidate the stub
1290 // in the JITResolver. Were there a memory manager deallocateStub routine,
1291 // we could call that at this point too.
1292 if (FnRefs.empty()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001293 DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
Nate Begeman841c6a42009-03-11 07:03:43 +00001294 StubFnRefs.erase(Stub);
1295
1296 // Invalidate the stub. If it is a GV stub, update the JIT's global
1297 // mapping for that GV to zero, otherwise, search the string map of
1298 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001299 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001300 if (GV) {
1301 TheJIT->updateGlobalMapping(GV, 0);
1302 } else {
1303 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1304 e = ExtFnStubs.end(); i != e; ++i) {
1305 if (i->second == Stub) {
1306 ExtFnStubs.erase(i);
1307 break;
1308 }
1309 }
1310 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001311 }
1312 }
1313 CurFnStubUses.erase(F);
1314}
1315
1316
Evan Cheng5788d1a2008-12-10 02:32:19 +00001317void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001318 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001319 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +00001320
1321 // create a new memory block if there is no active one.
1322 // care must be taken so that BufferBegin is invalidated when a
1323 // block is trimmed
1324 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1325 BufferEnd = BufferBegin+Size;
1326 return CurBufferPtr;
1327}
1328
Jeffrey Yasskin489393d2009-07-08 21:59:57 +00001329void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1330 // Delegate this call through the memory manager.
1331 return MemMgr->allocateGlobal(Size, Alignment);
1332}
1333
Chris Lattner166f2262004-11-22 22:00:25 +00001334void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001335 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001336 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001337
Chris Lattnerfa77d432006-02-09 04:22:52 +00001338 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001339 if (Constants.empty()) return;
1340
Evan Cheng1606e8e2009-03-13 07:51:59 +00001341 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1342 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001343 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001344 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001345
1346 if (ConstantPoolBase == 0) return; // Buffer overflow.
1347
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001348 DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1349 << "] (size: " << Size << ", alignment: " << Align << ")\n");
Evan Cheng97b8c402008-04-12 00:22:01 +00001350
Chris Lattner239862c2006-02-09 04:49:59 +00001351 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001352 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001353 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001354 MachineConstantPoolEntry CPE = Constants[i];
1355 unsigned AlignMask = CPE.getAlignment() - 1;
1356 Offset = (Offset + AlignMask) & ~AlignMask;
1357
1358 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1359 ConstPoolAddresses.push_back(CAddr);
1360 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001361 // FIXME: add support to lower machine constant pool values into bytes!
Torok Edwin7d696d82009-07-11 13:10:19 +00001362 llvm_report_error("Initialize memory with machine specific constant pool"
1363 "entry has not been implemented!");
Evan Chengcd5731d2006-09-12 20:59:59 +00001364 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001365 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001366 DEBUG(errs() << "JIT: CP" << i << " at [0x";
1367 errs().write_hex(CAddr) << "]\n");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001368
1369 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001370 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001371 }
1372}
1373
Nate Begeman37efe672006-04-22 18:53:45 +00001374void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001375 if (TheJIT->getJITInfo().hasCustomJumpTables())
1376 return;
1377
Nate Begeman37efe672006-04-22 18:53:45 +00001378 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1379 if (JT.empty()) return;
1380
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001381 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001382 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001383 NumEntries += JT[i].MBBs.size();
1384
1385 unsigned EntrySize = MJTI->getEntrySize();
1386
Nate Begeman37efe672006-04-22 18:53:45 +00001387 // Just allocate space for all the jump tables now. We will fix up the actual
1388 // MBB entries in the tables after we emit the code for each block, since then
1389 // we will know the final locations of the MBBs in memory.
1390 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001391 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001392}
1393
Jim Laskeyb92767a2006-12-14 22:53:42 +00001394void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001395 if (TheJIT->getJITInfo().hasCustomJumpTables())
1396 return;
1397
Nate Begeman37efe672006-04-22 18:53:45 +00001398 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001399 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001400
Jim Laskeyb92767a2006-12-14 22:53:42 +00001401 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001402 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1403 // For each jump table, place the offset from the beginning of the table
1404 // to the target address.
1405 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001406
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001407 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1408 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1409 // Store the offset of the basic block for this jump table slot in the
1410 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001411 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001412 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001413 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001414 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1415 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001416 }
1417 } else {
1418 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1419
1420 // For each jump table, map each target in the jump table to the address of
1421 // an emitted MachineBasicBlock.
1422 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1423
1424 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1425 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1426 // Store the address of the basic block for this jump table slot in the
1427 // memory we allocated for the jump table in 'initJumpTableInfo'
1428 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1429 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1430 }
Nate Begeman37efe672006-04-22 18:53:45 +00001431 }
1432}
1433
Evan Chengce4a70b2008-11-08 08:02:53 +00001434void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1435 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001436 SavedBufferBegin = BufferBegin;
1437 SavedBufferEnd = BufferEnd;
1438 SavedCurBufferPtr = CurBufferPtr;
1439
Evan Chengce4a70b2008-11-08 08:02:53 +00001440 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001441 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001442}
1443
Nate Begemand6b7a242009-02-18 08:31:02 +00001444void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1445 unsigned StubSize) {
1446 SavedBufferBegin = BufferBegin;
1447 SavedBufferEnd = BufferEnd;
1448 SavedCurBufferPtr = CurBufferPtr;
1449
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001450 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001451 BufferEnd = BufferBegin+StubSize+1;
1452}
1453
Evan Chengce4a70b2008-11-08 08:02:53 +00001454void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001455 NumBytes += getCurrentPCOffset();
1456 std::swap(SavedBufferBegin, BufferBegin);
1457 BufferEnd = SavedBufferEnd;
1458 CurBufferPtr = SavedCurBufferPtr;
1459 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001460}
1461
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001462// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1463// in the constant pool that was last emitted with the 'emitConstantPool'
1464// method.
1465//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001466uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001467 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001468 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001469 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001470}
1471
Nate Begeman37efe672006-04-22 18:53:45 +00001472// getJumpTableEntryAddress - Return the address of the JumpTable with index
1473// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1474//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001475uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001476 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1477 assert(Index < JT.size() && "Invalid jump table index!");
1478
1479 unsigned Offset = 0;
1480 unsigned EntrySize = JumpTable->getEntrySize();
1481
1482 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001483 Offset += JT[i].MBBs.size();
1484
1485 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001486
Evan Cheng5788d1a2008-12-10 02:32:19 +00001487 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001488}
1489
Chris Lattnere993cc22006-05-11 23:08:08 +00001490//===----------------------------------------------------------------------===//
1491// Public interface to this file
1492//===----------------------------------------------------------------------===//
1493
Reid Kleckner27632172009-09-20 23:52:43 +00001494JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1495 TargetMachine &tm) {
1496 return new JITEmitter(jit, JMM, tm);
Chris Lattnere993cc22006-05-11 23:08:08 +00001497}
1498
Misha Brukmand69c1e62003-07-28 19:09:06 +00001499// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001500// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001501// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1502// need to resolve function(s) that are being mis-codegenerated, so we need to
1503// resolve their addresses at runtime, and this is the way to do it.
1504extern "C" {
1505 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001506 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001507 return TheJIT->getPointerToFunction(F);
1508 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001509 }
1510}
Chris Lattnere993cc22006-05-11 23:08:08 +00001511
1512// getPointerToFunctionOrStub - If the specified function has been
1513// code-gen'd, return a pointer to the function. If not, compile it, or use
1514// a stub to implement lazy compilation if available.
1515//
1516void *JIT::getPointerToFunctionOrStub(Function *F) {
1517 // If we have already code generated the function, just return the address.
1518 if (void *Addr = getPointerToGlobalIfAvailable(F))
1519 return Addr;
1520
Chris Lattnere7484012007-02-24 02:57:03 +00001521 // Get a stub if the target supports it.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001522 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Chenga044dfc2008-08-20 00:28:12 +00001523 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001524 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001525}
1526
Nate Begemand6b7a242009-02-18 08:31:02 +00001527void JIT::updateFunctionStub(Function *F) {
1528 // Get the empty stub we generated earlier.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001529 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001530 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1531 void *Stub = JE->getJITResolver().getFunctionStub(F);
1532
1533 // Tell the target jit info to rewrite the stub at the specified address,
1534 // rather than creating a new one.
1535 void *Addr = getPointerToGlobalIfAvailable(F);
1536 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1537}
1538
1539/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1540/// that were emitted during code generation.
1541///
1542void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001543 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001544 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1545
1546 SmallVector<GlobalValue*, 8> GVs;
1547 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001548 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001549
1550 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1551
Nate Begeman841c6a42009-03-11 07:03:43 +00001552 unsigned nStubs = GVs.size() + ExtFns.size();
1553
Nate Begemand6b7a242009-02-18 08:31:02 +00001554 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001555 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001556 return;
1557
1558 // If there are no new relocatable stubs, return.
1559 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001560 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001561 return;
1562
1563 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001564 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001565
1566 SmallVector<unsigned, 8> Offsets;
1567 for (unsigned i = 0; i != GVs.size(); ++i) {
1568 Offsets.push_back(offset);
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001569 offset += GVs[i]->getName().size() + 1;
Nate Begemand6b7a242009-02-18 08:31:02 +00001570 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001571 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1572 i != e; ++i) {
1573 Offsets.push_back(offset);
1574 offset += strlen(i->first()) + 1;
1575 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001576
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001577 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001578 JE->startGVStub(0, offset, 4);
1579
1580 // Emit the number of records
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001581 JE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001582
1583 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001584 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001585 JE->emitInt32(Offsets[i]);
Nate Begemand6b7a242009-02-18 08:31:02 +00001586
Nate Begeman66941982009-03-04 19:10:38 +00001587 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1588 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1589 // relocation can write the relocated pointer at the appropriate place in
1590 // the stub.
1591 for (unsigned i = 0; i != GVs.size(); ++i) {
1592 intptr_t Ptr = (intptr_t)Ptrs[i];
1593 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1594
1595 if (isa<Function>(GVs[i]))
1596 Ptr |= (intptr_t)1;
1597
Nate Begeman841c6a42009-03-11 07:03:43 +00001598 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001599 JE->emitInt64(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001600 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001601 JE->emitInt32(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001602 }
1603 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1604 i != e; ++i) {
1605 intptr_t Ptr = (intptr_t)i->second | 1;
1606
1607 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001608 JE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001609 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001610 JE->emitInt32(Ptr);
Nate Begeman66941982009-03-04 19:10:38 +00001611 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001612
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001613 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001614 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001615 JE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001616 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1617 i != e; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001618 JE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001619
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001620 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1621 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001622 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1623}
1624
Chris Lattnere993cc22006-05-11 23:08:08 +00001625/// freeMachineCodeForFunction - release machine code memory for given Function.
1626///
1627void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001628
Chris Lattnere993cc22006-05-11 23:08:08 +00001629 // Delete translation for this from the ExecutionEngine, so it will get
1630 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001631 void *OldPtr = updateGlobalMapping(F, 0);
1632
1633 if (OldPtr)
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001634 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001635
1636 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001637 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1638 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001639}