blob: 590846bfded0b4f6ecd78da889520f47a4be4e48 [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"
Evan Cheng47c01a02008-11-07 09:02:17 +000045#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000046#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000048#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000049#ifndef NDEBUG
50#include <iomanip>
51#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000052using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000053
Chris Lattner36343732006-12-19 22:43:32 +000054STATISTIC(NumBytes, "Number of bytes of machine code compiled");
55STATISTIC(NumRelos, "Number of relocations applied");
Reid Kleckner10b4fc52009-07-23 21:46:56 +000056STATISTIC(NumRetries, "Number of retries with more memory");
Chris Lattner36343732006-12-19 22:43:32 +000057static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000058
Andrew Lenhartha00269b2005-07-29 23:40:16 +000059
Chris Lattner54266522004-11-20 23:57:07 +000060//===----------------------------------------------------------------------===//
61// JIT lazy compilation code.
62//
63namespace {
Reid Spenceree448632005-07-12 15:51:55 +000064 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000065 public:
66 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
67 typedef std::map<void*, Function*> StubToFunctionMapTy;
68 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000069 private:
70 /// FunctionToStubMap - Keep track of the stub created for a particular
71 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000072 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000073
74 /// StubToFunctionMap - Keep track of the function that each stub
75 /// corresponds to.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000076 StubToFunctionMapTy StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000077
Evan Cheng5594f122008-11-10 01:52:24 +000078 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000079 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000080 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000081
Reid Spenceree448632005-07-12 15:51:55 +000082 public:
Nick Lewyckye2bcf132009-04-27 05:09:44 +000083 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000084 assert(locked.holds(TheJIT->lock));
85 return FunctionToStubMap;
86 }
Jeff Cohen00b168892005-07-27 06:12:32 +000087
Nick Lewyckye2bcf132009-04-27 05:09:44 +000088 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000089 assert(locked.holds(TheJIT->lock));
90 return StubToFunctionMap;
91 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000092
Nick Lewyckye2bcf132009-04-27 05:09:44 +000093 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000094 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000095 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000096 }
Reid Spenceree448632005-07-12 15:51:55 +000097 };
Jeff Cohen00b168892005-07-27 06:12:32 +000098
Chris Lattner54266522004-11-20 23:57:07 +000099 /// JITResolver - Keep track of, and resolve, call sites for functions that
100 /// have not yet been compiled.
101 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000102 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
103 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
104 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
105
Chris Lattner5e225582004-11-21 03:37:42 +0000106 /// LazyResolverFn - The target lazy resolver function that we actually
107 /// rewrite instructions to use.
108 TargetJITInfo::LazyResolverFn LazyResolverFn;
109
Reid Spenceree448632005-07-12 15:51:55 +0000110 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000111
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000112 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
113 /// external functions.
114 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000115
Evan Cheng1606e8e2009-03-13 07:51:59 +0000116 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000117 std::map<void*, unsigned> revGOTMap;
118 unsigned nextGOTIndex;
119
Chris Lattnere7484012007-02-24 02:57:03 +0000120 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000121 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000122 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000123 TheJIT = &jit;
124
125 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
126 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
127 TheJITResolver = this;
128 }
129
130 ~JITResolver() {
131 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000132 }
Chris Lattner54266522004-11-20 23:57:07 +0000133
Evan Cheng704bff92008-11-13 21:50:50 +0000134 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
135 /// if it has already been created.
136 void *getFunctionStubIfAvailable(Function *F);
137
Chris Lattner54266522004-11-20 23:57:07 +0000138 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000139 /// one on demand as needed. If empty is true, create a function stub
140 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000141 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000142
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000143 /// getExternalFunctionStub - Return a stub for the function at the
144 /// specified address, created lazily on demand.
145 void *getExternalFunctionStub(void *FnAddr);
146
Evan Cheng5594f122008-11-10 01:52:24 +0000147 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000148 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000149 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000150
Chris Lattner5e225582004-11-21 03:37:42 +0000151 /// AddCallbackAtLocation - If the target is capable of rewriting an
152 /// instruction without the use of a stub, record the location of the use so
153 /// we know which function is being used at the location.
154 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000155 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000156 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000157 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000158 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000159 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000160
161 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000162 SmallVectorImpl<void*> &Ptrs);
163
164 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000165
Andrew Lenharth6a974612005-07-28 12:44:13 +0000166 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000167 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000168 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000169 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000170
Chris Lattner54266522004-11-20 23:57:07 +0000171 /// JITCompilerFn - This function is called to resolve a stub to a compiled
172 /// address. If the LLVM Function corresponding to the stub has not yet
173 /// been compiled, this function compiles it first.
174 static void *JITCompilerFn(void *Stub);
175 };
176}
177
Chris Lattnere7484012007-02-24 02:57:03 +0000178JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000179
Evan Cheng704bff92008-11-13 21:50:50 +0000180/// getFunctionStubIfAvailable - This returns a pointer to a function stub
181/// if it has already been created.
182void *JITResolver::getFunctionStubIfAvailable(Function *F) {
183 MutexGuard locked(TheJIT->lock);
184
185 // If we already have a stub for this function, recycle it.
186 void *&Stub = state.getFunctionToStubMap(locked)[F];
187 return Stub;
188}
189
Chris Lattner54266522004-11-20 23:57:07 +0000190/// getFunctionStub - This returns a pointer to a function stub, creating
191/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000192void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000193 MutexGuard locked(TheJIT->lock);
194
Chris Lattner54266522004-11-20 23:57:07 +0000195 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000196 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000197 if (Stub) return Stub;
198
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000199 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
200 // case we must resolve the symbol now.
201 void *Actual = TheJIT->isLazyCompilationDisabled()
202 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
203
204 // If this is an external declaration, attempt to resolve the address now
205 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000206 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000207 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000208
Dan Gohman69f93782009-01-05 05:32:42 +0000209 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000210 // don't emit a stub. Return a null pointer to the application. If dlsym
211 // stubs are enabled, not being able to resolve the address is not
212 // meaningful.
213 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000214 }
215
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000216 // Codegen a new stub, calling the lazy resolver or the actual address of the
217 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000218 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000219 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000220
Chris Lattner870286a2006-06-01 17:29:22 +0000221 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000222 // If we are getting the stub for an external function, we really want the
223 // address of the stub in the GlobalAddressMap for the JIT, not the address
224 // of the external function.
225 TheJIT->updateGlobalMapping(F, Stub);
226 }
Chris Lattner54266522004-11-20 23:57:07 +0000227
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000228 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
229 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000230
Chris Lattner54266522004-11-20 23:57:07 +0000231 // Finally, keep track of the stub-to-Function mapping so that the
232 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000233 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000234
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000235 // If we are JIT'ing non-lazily but need to call a function that does not
236 // exist yet, add it to the JIT's work list so that we can fill in the stub
237 // address later.
238 if (!Actual && TheJIT->isLazyCompilationDisabled())
239 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
240 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000241
Chris Lattner54266522004-11-20 23:57:07 +0000242 return Stub;
243}
244
Evan Cheng5594f122008-11-10 01:52:24 +0000245/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000246/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000247void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000248 MutexGuard locked(TheJIT->lock);
249
250 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000251 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
252 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000253
Evan Chenge4d783d2008-11-10 23:26:16 +0000254 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000255 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000256 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000257
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000258 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
259 << "] for GV '" << GV->getName() << "'\n");
Evan Chengbe8c03f2008-01-04 10:46:51 +0000260
Evan Cheng5594f122008-11-10 01:52:24 +0000261 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000262}
263
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000264/// getExternalFunctionStub - Return a stub for the function at the
265/// specified address, created lazily on demand.
266void *JITResolver::getExternalFunctionStub(void *FnAddr) {
267 // If we already have a stub for this function, recycle it.
268 void *&Stub = ExternalFnToStubMap[FnAddr];
269 if (Stub) return Stub;
270
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000271 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000272 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000273
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000274 DEBUG(errs() << "JIT: Stub emitted at [" << Stub
275 << "] for external function at '" << FnAddr << "'\n");
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000276 return Stub;
277}
278
Andrew Lenharth6a974612005-07-28 12:44:13 +0000279unsigned JITResolver::getGOTIndexForAddr(void* addr) {
280 unsigned idx = revGOTMap[addr];
281 if (!idx) {
282 idx = ++nextGOTIndex;
283 revGOTMap[addr] = idx;
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000284 DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
285 << addr << "]\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000286 }
287 return idx;
288}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000289
Nate Begemand6b7a242009-02-18 08:31:02 +0000290void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
291 SmallVectorImpl<void*> &Ptrs) {
292 MutexGuard locked(TheJIT->lock);
293
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000294 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
295 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000296
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000297 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000298 Function *F = i->first;
299 if (F->isDeclaration() && F->hasExternalLinkage()) {
300 GVs.push_back(i->first);
301 Ptrs.push_back(i->second);
302 }
303 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000304 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000305 i != e; ++i) {
306 GVs.push_back(i->first);
307 Ptrs.push_back(i->second);
308 }
309}
310
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000311GlobalValue *JITResolver::invalidateStub(void *Stub) {
312 MutexGuard locked(TheJIT->lock);
313
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000314 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
315 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
316 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000317
318 // Look up the cheap way first, to see if it's a function stub we are
319 // invalidating. If so, remove it from both the forward and reverse maps.
320 if (SM.find(Stub) != SM.end()) {
321 Function *F = SM[Stub];
322 SM.erase(Stub);
323 FM.erase(F);
324 return F;
325 }
326
Nate Begeman841c6a42009-03-11 07:03:43 +0000327 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000328 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000329 i != e; ++i) {
330 if (i->second != Stub)
331 continue;
332 GlobalValue *GV = i->first;
333 GM.erase(i);
334 return GV;
335 }
336
Nate Begeman841c6a42009-03-11 07:03:43 +0000337 // Lastly, check to see if it's in the ExternalFnToStubMap.
338 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
339 e = ExternalFnToStubMap.end(); i != e; ++i) {
340 if (i->second != Stub)
341 continue;
342 ExternalFnToStubMap.erase(i);
343 break;
344 }
345
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000346 return 0;
347}
348
Chris Lattner54266522004-11-20 23:57:07 +0000349/// JITCompilerFn - This function is called when a lazy compilation stub has
350/// been entered. It looks up which function this stub corresponds to, compiles
351/// it if necessary, then returns the resultant function pointer.
352void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000353 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000354
355 Function* F = 0;
356 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000357
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000358 {
359 // Only lock for getting the Function. The call getPointerToFunction made
360 // in this function might trigger function materializing, which requires
361 // JIT lock to be unlocked.
362 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000363
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000364 // The address given to us for the stub may not be exactly right, it might be
365 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000366 StubToFunctionMapTy::iterator I =
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000367 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
368 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
369 "This is not a known stub!");
370 F = (--I)->second;
371 ActualPtr = I->first;
372 }
Chris Lattner54266522004-11-20 23:57:07 +0000373
Evan Cheng9da60f92007-06-30 00:10:37 +0000374 // If we have already code generated the function, just return the address.
375 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000376
Evan Cheng9da60f92007-06-30 00:10:37 +0000377 if (!Result) {
378 // Otherwise we don't have it, do lazy compilation now.
379
380 // If lazy compilation is disabled, emit a useful error message and abort.
381 if (TheJIT->isLazyCompilationDisabled()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000382 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
383 + F->getName() + "' when lazy compiles are disabled!");
Evan Cheng9da60f92007-06-30 00:10:37 +0000384 }
385
386 // We might like to remove the stub from the StubToFunction map.
387 // We can't do that! Multiple threads could be stuck, waiting to acquire the
388 // lock above. As soon as the 1st function finishes compiling the function,
389 // the next one will be released, and needs to be able to find the function
390 // it needs to call.
391 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000392
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000393 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
394 << "' In stub ptr = " << Stub << " actual ptr = "
395 << ActualPtr << "\n");
Chris Lattner54266522004-11-20 23:57:07 +0000396
Evan Cheng9da60f92007-06-30 00:10:37 +0000397 Result = TheJIT->getPointerToFunction(F);
398 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000399
400 // Reacquire the lock to erase the stub in the map.
401 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000402
403 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000404 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000405
406 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000407
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000408 // What we will do is set the compiled function address to map to the
409 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000410 // if they see it still using the stub address.
411 // Note: this is done so the Resolver doesn't have to manage GOT memory
412 // Do this without allocating map space if the target isn't using a GOT
413 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
414 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
415
Chris Lattner54266522004-11-20 23:57:07 +0000416 return Result;
417}
Chris Lattner688506d2003-08-14 18:35:27 +0000418
Chris Lattner8ac66c12008-04-04 05:51:42 +0000419//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000420// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000421//
Chris Lattner688506d2003-08-14 18:35:27 +0000422namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000423 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
424 /// used to output functions to memory for execution.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000425 class JITEmitter : public JITCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000426 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000427
Chris Lattner6125fdd2003-05-09 03:30:07 +0000428 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000429 // save BufferBegin/BufferEnd/CurBufferPtr here.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000430 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000431
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000432 // When reattempting to JIT a function after running out of space, we store
433 // the estimated size of the function we're trying to JIT here, so we can
434 // ask the memory manager for at least this much space. When we
435 // successfully emit the function, we reset this back to zero.
436 uintptr_t SizeEstimate;
437
Chris Lattner5be478f2004-11-20 03:46:14 +0000438 /// Relocations - These are the relocations that the function needs, as
439 /// emitted.
440 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000441
442 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
443 /// It is filled in by the StartMachineBasicBlock callback and queried by
444 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000445 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000446
Chris Lattner239862c2006-02-09 04:49:59 +0000447 /// ConstantPool - The constant pool for the current function.
448 ///
449 MachineConstantPool *ConstantPool;
450
451 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
452 ///
453 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000454
Evan Cheng1606e8e2009-03-13 07:51:59 +0000455 /// ConstPoolAddresses - Addresses of individual constant pool entries.
456 ///
457 SmallVector<uintptr_t, 8> ConstPoolAddresses;
458
Nate Begeman019f8512006-09-10 23:03:44 +0000459 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000460 ///
461 MachineJumpTableInfo *JumpTable;
462
463 /// JumpTableBase - A pointer to the first entry in the jump table.
464 ///
465 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000466
Chris Lattnere7484012007-02-24 02:57:03 +0000467 /// Resolver - This contains info about the currently resolved functions.
468 JITResolver Resolver;
Reid Kleckner27632172009-09-20 23:52:43 +0000469
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000470 /// DE - The dwarf emitter for the jit.
Reid Kleckner27632172009-09-20 23:52:43 +0000471 OwningPtr<JITDwarfEmitter> DE;
472
473 /// DR - The debug registerer for the jit.
474 OwningPtr<JITDebugRegisterer> DR;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000475
476 /// LabelLocations - This vector is a mapping from Label ID's to their
477 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000478 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000479
480 /// MMI - Machine module info for exception informations
481 MachineModuleInfo* MMI;
482
Dale Johannesendd947ea2008-08-07 01:30:15 +0000483 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000484 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000485
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000486 // CurFn - The llvm function being emitted. Only valid during
487 // finishFunction().
488 const Function *CurFn;
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000489
490 /// Information about emitted code, which is passed to the
491 /// JITEventListeners. This is reset in startFunction and used in
492 /// finishFunction.
493 JITEvent_EmittedFunctionDetails EmissionDetails;
494
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000495 // CurFnStubUses - For a given Function, a vector of stubs that it
496 // references. This facilitates the JIT detecting that a stub is no
497 // longer used, so that it may be deallocated.
498 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
499
500 // StubFnRefs - For a given pointer to a stub, a set of Functions which
501 // reference the stub. When the count of a stub's references drops to zero,
502 // the stub is unused.
503 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
504
Nate Begeman841c6a42009-03-11 07:03:43 +0000505 // ExtFnStubs - A map of external function names to stubs which have entries
506 // in the JITResolver's ExternalFnToStubMap.
507 StringMap<void *> ExtFnStubs;
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000508
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000509 DebugLocTuple PrevDLT;
510
Chris Lattnere7484012007-02-24 02:57:03 +0000511 public:
Reid Kleckner27632172009-09-20 23:52:43 +0000512 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
Xerxes Ranby3d47db52009-08-25 10:12:55 +0000513 : SizeEstimate(0), Resolver(jit), MMI(0), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000514 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000515 if (jit.getJITInfo().needsGOT()) {
516 MemMgr->AllocateGOT();
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000517 DEBUG(errs() << "JIT is managing a GOT\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000518 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000519
Reid Kleckner27632172009-09-20 23:52:43 +0000520 if (DwarfExceptionHandling || JITEmitDebugInfo) {
521 DE.reset(new JITDwarfEmitter(jit));
522 }
523 if (JITEmitDebugInfo) {
524 DR.reset(new JITDebugRegisterer(TM));
525 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000526 }
527 ~JITEmitter() {
528 delete MemMgr;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000529 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000530
531 /// classof - Methods for support type inquiry through isa, cast, and
532 /// dyn_cast:
533 ///
534 static inline bool classof(const JITEmitter*) { return true; }
535 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000536
537 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000538
539 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000540 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000541
542 void emitConstantPool(MachineConstantPool *MCP);
543 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000544 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000545
Evan Chengce4a70b2008-11-08 08:02:53 +0000546 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000547 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000548 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
549 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000550 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000551
Nuno Lopescef75272008-10-21 11:42:16 +0000552 /// allocateSpace - Reserves space in the current block if any, or
553 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000554 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000555
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000556 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
557 /// this method does not allocate memory in the current output buffer,
558 /// because a global may live longer than the current function.
559 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
560
Chris Lattner5be478f2004-11-20 03:46:14 +0000561 virtual void addRelocation(const MachineRelocation &MR) {
562 Relocations.push_back(MR);
563 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000564
565 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
566 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
567 MBBLocations.resize((MBB->getNumber()+1)*2);
568 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000569 DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
570 << (void*) getCurrentPCValue() << "]\n");
Chris Lattnerb4432f32006-05-03 17:10:41 +0000571 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000572
Evan Cheng5788d1a2008-12-10 02:32:19 +0000573 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
574 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000575
Evan Cheng5788d1a2008-12-10 02:32:19 +0000576 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000577 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
578 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
579 return MBBLocations[MBB->getNumber()];
580 }
581
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000582 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
583 /// given function. Increase the minimum allocation size so that we get
584 /// more memory next time.
585 void retryWithMoreMemory(MachineFunction &F);
586
Chris Lattnere993cc22006-05-11 23:08:08 +0000587 /// deallocateMemForFunction - Deallocate all memory for the specified
588 /// function body.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000589 void deallocateMemForFunction(const Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000590
591 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
592 /// using the stub at the specified address. Allows
593 /// deallocateMemForFunction to also remove stubs no longer referenced.
594 void AddStubToCurrentFunction(void *Stub);
595
596 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
597 /// MachineRelocations that reference external functions by name.
598 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000599
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000600 virtual void processDebugLoc(DebugLoc DL);
601
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000602 virtual void emitLabel(uint64_t LabelID) {
603 if (LabelLocations.size() <= LabelID)
604 LabelLocations.resize((LabelID+1)*2);
605 LabelLocations[LabelID] = getCurrentPCValue();
606 }
607
Evan Cheng5788d1a2008-12-10 02:32:19 +0000608 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000609 assert(LabelLocations.size() > (unsigned)LabelID &&
610 LabelLocations[LabelID] && "Label not emitted!");
611 return LabelLocations[LabelID];
612 }
613
614 virtual void setModuleInfo(MachineModuleInfo* Info) {
615 MMI = Info;
Reid Kleckner27632172009-09-20 23:52:43 +0000616 if (DE.get()) DE->setModuleInfo(Info);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000617 }
618
Dan Gohmana9ad0412009-08-12 22:10:57 +0000619 void setMemoryExecutable() {
Jim Grosbachcce6c292008-10-03 16:17:20 +0000620 MemMgr->setMemoryExecutable();
621 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000622
Dan Gohmana9ad0412009-08-12 22:10:57 +0000623 JITMemoryManager *getMemMgr() const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000624
Chris Lattner54266522004-11-20 23:57:07 +0000625 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000626 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000627 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000628 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000629 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
630 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
631 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
632 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000633 };
634}
635
Chris Lattner166f2262004-11-22 22:00:25 +0000636void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
637 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000638 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000639 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000640
Chris Lattner18e04592008-06-25 20:21:35 +0000641 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000642 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000643
644 // If we have already compiled the function, return a pointer to its body.
645 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000646 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000647 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000648 // Return the function stub if it's already created.
649 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000650 if (ResultPtr)
651 AddStubToCurrentFunction(ResultPtr);
652 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000653 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000654 }
Chris Lattner54266522004-11-20 23:57:07 +0000655 if (ResultPtr) return ResultPtr;
656
Nate Begemand6b7a242009-02-18 08:31:02 +0000657 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000658 // 'compile' it, which really just adds it to the map. In dlsym mode,
659 // external functions are forced through a stub, regardless of reloc type.
660 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
661 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000662 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000663
Chris Lattner5e225582004-11-21 03:37:42 +0000664 // Okay, the function has not been compiled yet, if the target callback
665 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000666 // that instead of emitting a stub. This uses the lazy resolver, so is not
667 // legal if lazy compilation is disabled.
668 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000669 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000670
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000671 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000672 void *StubAddr = Resolver.getFunctionStub(F);
673
674 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000675 // deallocate them if the current function is ever freed. It's possible to
676 // return null from getFunctionStub in the case of a weak extern that fails
677 // to resolve.
678 if (StubAddr)
679 AddStubToCurrentFunction(StubAddr);
680
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000681 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000682}
683
Evan Cheng5594f122008-11-10 01:52:24 +0000684void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000685 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000686 // Make sure GV is emitted first, and create a stub containing the fully
687 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000688 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000689 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
690
691 // Add the stub to the current function's list of referenced stubs, so we can
692 // deallocate them if the current function is ever freed.
693 AddStubToCurrentFunction(StubAddr);
694
695 return StubAddr;
696}
697
698void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
699 if (!TheJIT->areDlsymStubsEnabled())
700 return;
701
702 assert(CurFn && "Stub added to current function, but current function is 0!");
703
704 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
705 StubsUsed.push_back(StubAddr);
706
707 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
708 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000709}
710
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000711void JITEmitter::processDebugLoc(DebugLoc DL) {
712 if (!DL.isUnknown()) {
713 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
714
715 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
716 JITEvent_EmittedFunctionDetails::LineStart NextLine;
717 NextLine.Address = getCurrentPCValue();
718 NextLine.Loc = DL;
719 EmissionDetails.LineStarts.push_back(NextLine);
720 }
721
722 PrevDLT = CurDLT;
723 }
724}
725
Evan Cheng1606e8e2009-03-13 07:51:59 +0000726static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
727 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000728 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
729 if (Constants.empty()) return 0;
730
Evan Cheng1606e8e2009-03-13 07:51:59 +0000731 unsigned Size = 0;
732 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
733 MachineConstantPoolEntry CPE = Constants[i];
734 unsigned AlignMask = CPE.getAlignment() - 1;
735 Size = (Size + AlignMask) & ~AlignMask;
736 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000737 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000738 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000739 return Size;
740}
741
742static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
743 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
744 if (JT.empty()) return 0;
745
746 unsigned NumEntries = 0;
747 for (unsigned i = 0, e = JT.size(); i != e; ++i)
748 NumEntries += JT[i].MBBs.size();
749
750 unsigned EntrySize = MJTI->getEntrySize();
751
752 return NumEntries * EntrySize;
753}
754
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000755static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000756 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000757 // Since we do not know where the buffer will be allocated, be pessimistic.
758 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000759}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000760
Dale Johannesendd947ea2008-08-07 01:30:15 +0000761/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
762/// into the running total Size.
763
764unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
765 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000766 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000767 size_t GVAlign =
768 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000769 DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000770 DEBUG(GV->dump());
771 // Assume code section ends with worst possible alignment, so first
772 // variable needs maximal padding.
773 if (Size==0)
774 Size = 1;
775 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
776 Size += GVSize;
777 return Size;
778}
779
780/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
781/// but are referenced from the constant; put them in GVSet and add their
782/// size into the running total Size.
783
784unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
785 unsigned Size) {
786 // If its undefined, return the garbage.
787 if (isa<UndefValue>(C))
788 return Size;
789
790 // If the value is a ConstantExpr
791 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
792 Constant *Op0 = CE->getOperand(0);
793 switch (CE->getOpcode()) {
794 case Instruction::GetElementPtr:
795 case Instruction::Trunc:
796 case Instruction::ZExt:
797 case Instruction::SExt:
798 case Instruction::FPTrunc:
799 case Instruction::FPExt:
800 case Instruction::UIToFP:
801 case Instruction::SIToFP:
802 case Instruction::FPToUI:
803 case Instruction::FPToSI:
804 case Instruction::PtrToInt:
805 case Instruction::IntToPtr:
806 case Instruction::BitCast: {
807 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
808 break;
809 }
810 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000811 case Instruction::FAdd:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000812 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000813 case Instruction::FSub:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000814 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000815 case Instruction::FMul:
Dale Johannesendd947ea2008-08-07 01:30:15 +0000816 case Instruction::UDiv:
817 case Instruction::SDiv:
818 case Instruction::URem:
819 case Instruction::SRem:
820 case Instruction::And:
821 case Instruction::Or:
822 case Instruction::Xor: {
823 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
824 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
825 break;
826 }
827 default: {
Torok Edwin7d696d82009-07-11 13:10:19 +0000828 std::string msg;
829 raw_string_ostream Msg(msg);
830 Msg << "ConstantExpr not handled: " << *CE;
831 llvm_report_error(Msg.str());
Dale Johannesendd947ea2008-08-07 01:30:15 +0000832 }
833 }
834 }
835
836 if (C->getType()->getTypeID() == Type::PointerTyID)
837 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000838 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000839 Size = addSizeOfGlobal(GV, Size);
840
841 return Size;
842}
843
844/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
845/// but are referenced from the given initializer.
846
847unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
848 unsigned Size) {
849 if (!isa<UndefValue>(Init) &&
850 !isa<ConstantVector>(Init) &&
851 !isa<ConstantAggregateZero>(Init) &&
852 !isa<ConstantArray>(Init) &&
853 !isa<ConstantStruct>(Init) &&
854 Init->getType()->isFirstClassType())
855 Size = addSizeOfGlobalsInConstantVal(Init, Size);
856 return Size;
857}
858
859/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
860/// globals; then walk the initializers of those globals looking for more.
861/// If their size has not been considered yet, add it into the running total
862/// Size.
863
864unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
865 unsigned Size = 0;
866 GVSet.clear();
867
868 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
869 MBB != E; ++MBB) {
870 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
871 I != E; ++I) {
872 const TargetInstrDesc &Desc = I->getDesc();
873 const MachineInstr &MI = *I;
874 unsigned NumOps = Desc.getNumOperands();
875 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
876 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000877 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000878 GlobalValue* V = MO.getGlobal();
879 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
880 if (!GV)
881 continue;
882 // If seen in previous function, it will have an entry here.
883 if (TheJIT->getPointerToGlobalIfAvailable(GV))
884 continue;
885 // If seen earlier in this function, it will have an entry here.
886 // FIXME: it should be possible to combine these tables, by
887 // assuming the addresses of the new globals in this module
888 // start at 0 (or something) and adjusting them after codegen
889 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000890 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000891 // A variable as yet unseen. Add in its size.
892 Size = addSizeOfGlobal(GV, Size);
893 }
894 }
895 }
896 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000897 DEBUG(errs() << "JIT: About to look through initializers\n");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000898 // Look for more globals that are referenced only from initializers.
899 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000900 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000901 I != GVSet.end(); I++) {
902 const GlobalVariable* GV = *I;
903 if (GV->hasInitializer())
904 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
905 }
906
907 return Size;
908}
909
Chris Lattner166f2262004-11-22 22:00:25 +0000910void JITEmitter::startFunction(MachineFunction &F) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000911 DEBUG(errs() << "JIT: Starting CodeGen of Function "
912 << F.getFunction()->getName() << "\n");
Evan Chengeb5d95a2008-11-06 17:46:04 +0000913
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000914 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000915 // Set the memory writable, if it's not already
916 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000917 if (MemMgr->NeedsExactSize()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000918 DEBUG(errs() << "JIT: ExactSize\n");
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000919 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
920 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
921 MachineConstantPool *MCP = F.getConstantPool();
922
923 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000924 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000925
926 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000927 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000928
929 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +0000930 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000931
932 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000933 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000934
935 // Add the jump table size
936 ActualSize += GetJumpTableSizeInBytes(MJTI);
937
938 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000939 ActualSize = RoundUpToAlign(ActualSize,
940 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000941
942 // Add the function size
943 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000944
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000945 DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000946 // Add the size of the globals that will be allocated after this function.
947 // These are all the ones referenced from this function that were not
948 // previously allocated.
949 ActualSize += GetSizeOfGlobalsInBytes(F);
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000950 DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000951 } else if (SizeEstimate > 0) {
952 // SizeEstimate will be non-zero on reallocation attempts.
953 ActualSize = SizeEstimate;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000954 }
955
Chris Lattner8907b4b2007-12-05 23:39:57 +0000956 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
957 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000958 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000959
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000960 // Ensure the constant pool/jump table info is at least 4-byte aligned.
961 emitAlignment(16);
962
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000963 emitConstantPool(F.getConstantPool());
964 initJumpTableInfo(F.getJumpTableInfo());
965
966 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000967 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000968 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000969
Chris Lattnerb4432f32006-05-03 17:10:41 +0000970 MBBLocations.clear();
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000971
972 EmissionDetails.MF = &F;
973 EmissionDetails.LineStarts.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000974}
975
Chris Lattner43b429b2006-05-02 18:27:26 +0000976bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000977 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000978 // We must call endFunctionBody before retrying, because
979 // deallocateMemForFunction requires it.
980 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
981 retryWithMoreMemory(F);
982 return true;
Chris Lattnere993cc22006-05-11 23:08:08 +0000983 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000984
Jim Laskeyb92767a2006-12-14 22:53:42 +0000985 emitJumpTableInfo(F.getJumpTableInfo());
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000986
Chris Lattnera8279532006-06-16 18:09:26 +0000987 // FnStart is the start of the text, not the start of the constant pool and
988 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000989 uint8_t *FnStart =
990 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000991
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000992 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000993 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000994
Chris Lattner5be478f2004-11-20 03:46:14 +0000995 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000996 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +0000997 NumRelos += Relocations.size();
998
Chris Lattner5be478f2004-11-20 03:46:14 +0000999 // Resolve the relocations to concrete pointers.
1000 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1001 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001002 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001003 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001004 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001005 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1006 false);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001007 DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1008 << ResultPtr << "]\n");
Misha Brukmanf976c852005-04-21 22:55:34 +00001009
Evan Chengef5784e2008-10-29 23:54:46 +00001010 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001011 if (!MR.doesntNeedStub()) {
1012 if (!TheJIT->areDlsymStubsEnabled()) {
1013 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1014 } else {
1015 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1016 if (!Stub) {
1017 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1018 AddStubToCurrentFunction(Stub);
1019 }
1020 ResultPtr = Stub;
1021 }
1022 }
Evan Chengef5784e2008-10-29 23:54:46 +00001023 } else if (MR.isGlobalValue()) {
1024 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1025 BufferBegin+MR.getMachineCodeOffset(),
1026 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001027 } else if (MR.isIndirectSymbol()) {
1028 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001029 BufferBegin+MR.getMachineCodeOffset(),
1030 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001031 } else if (MR.isBasicBlock()) {
1032 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1033 } else if (MR.isConstantPoolIndex()) {
1034 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1035 } else {
1036 assert(MR.isJumpTableIndex());
1037 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1038 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001039
Evan Chengef5784e2008-10-29 23:54:46 +00001040 MR.setResultPointer(ResultPtr);
1041 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001042
Andrew Lenharth6a974612005-07-28 12:44:13 +00001043 // if we are managing the GOT and the relocation wants an index,
1044 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001045 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001046 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001047 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001048 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001049 DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1050 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1051 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +00001052 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001053 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001054 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001055 }
1056
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001057 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001058 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001059 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001060 }
1061
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001062 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001063 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001064 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001065 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001066 DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1067 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1068 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +00001069 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001070 }
1071 }
1072
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001073 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1074 // global variables that were referenced in the relocations.
1075 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001076
1077 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001078 retryWithMoreMemory(F);
1079 return true;
1080 } else {
1081 // Now that we've succeeded in emitting the function, reset the
1082 // SizeEstimate back down to zero.
1083 SizeEstimate = 0;
Evan Cheng5788d1a2008-12-10 02:32:19 +00001084 }
1085
Nuno Lopescef75272008-10-21 11:42:16 +00001086 BufferBegin = CurBufferPtr = 0;
1087 NumBytes += FnEnd-FnStart;
1088
Evan Cheng55fc2802006-07-25 20:40:54 +00001089 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001090 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001091
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001092 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
Jeffrey Yasskin32360a72009-07-16 21:07:26 +00001093 EmissionDetails);
Evan Cheng55fc2802006-07-25 20:40:54 +00001094
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001095 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1096 << "] Function: " << F.getFunction()->getName()
1097 << ": " << (FnEnd-FnStart) << " bytes of text, "
1098 << Relocations.size() << " relocations\n");
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +00001099
Chris Lattner5be478f2004-11-20 03:46:14 +00001100 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001101 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001102
Evan Chengbc4707a2008-09-18 07:54:21 +00001103 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001104 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001105
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001106 DEBUG(
Evan Chenge7c35512008-11-12 08:22:43 +00001107 if (sys::hasDisassembler()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001108 errs() << "JIT: Disassembled code:\n";
1109 errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1110 (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001111 } else {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001112 errs() << "JIT: Binary code:\n";
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001113 uint8_t* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001114 for (int i = 0; q < FnEnd; q += 4, ++i) {
1115 if (i == 4)
1116 i = 0;
1117 if (i == 0)
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001118 errs() << "JIT: " << (long)(q - FnStart) << ": ";
Evan Chenge7c35512008-11-12 08:22:43 +00001119 bool Done = false;
1120 for (int j = 3; j >= 0; --j) {
1121 if (q + j >= FnEnd)
1122 Done = true;
1123 else
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001124 errs() << (unsigned short)q[j];
Evan Chenge7c35512008-11-12 08:22:43 +00001125 }
1126 if (Done)
1127 break;
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001128 errs() << ' ';
Evan Chenge7c35512008-11-12 08:22:43 +00001129 if (i == 3)
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001130 errs() << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001131 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001132 errs()<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001133 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001134 );
1135
Reid Kleckner27632172009-09-20 23:52:43 +00001136 if (DwarfExceptionHandling || JITEmitDebugInfo) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001137 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001138 SavedBufferBegin = BufferBegin;
1139 SavedBufferEnd = BufferEnd;
1140 SavedCurBufferPtr = CurBufferPtr;
Reid Kleckner27632172009-09-20 23:52:43 +00001141
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001142 if (MemMgr->NeedsExactSize()) {
1143 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001144 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001145
1146 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1147 ActualSize);
1148 BufferEnd = BufferBegin+ActualSize;
Reid Kleckner27632172009-09-20 23:52:43 +00001149 uint8_t *EhStart;
1150 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1151 EhStart);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001152 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1153 FrameRegister);
Reid Kleckner27632172009-09-20 23:52:43 +00001154 uint8_t *EhEnd = CurBufferPtr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001155 BufferBegin = SavedBufferBegin;
1156 BufferEnd = SavedBufferEnd;
1157 CurBufferPtr = SavedCurBufferPtr;
1158
Reid Kleckner27632172009-09-20 23:52:43 +00001159 if (DwarfExceptionHandling) {
1160 TheJIT->RegisterTable(FrameRegister);
1161 }
1162
1163 if (JITEmitDebugInfo) {
1164 DebugInfo I;
1165 I.FnStart = FnStart;
1166 I.FnEnd = FnEnd;
1167 I.EhStart = EhStart;
1168 I.EhEnd = EhEnd;
1169 DR->RegisterFunction(F.getFunction(), I);
1170 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001171 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001172
1173 if (MMI)
1174 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001175
Chris Lattner43b429b2006-05-02 18:27:26 +00001176 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001177}
1178
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001179void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001180 DEBUG(errs() << "JIT: Ran out of space for native code. Reattempting.\n");
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001181 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1182 ConstPoolAddresses.clear();
1183 ++NumRetries;
1184 deallocateMemForFunction(F.getFunction());
1185 // Try again with at least twice as much free space.
1186 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1187}
1188
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001189/// deallocateMemForFunction - Deallocate all memory for the specified
1190/// function body. Also drop any references the function has to stubs.
Reid Kleckner10b4fc52009-07-23 21:46:56 +00001191void JITEmitter::deallocateMemForFunction(const Function *F) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001192 MemMgr->deallocateMemForFunction(F);
1193
Reid Kleckner27632172009-09-20 23:52:43 +00001194 // TODO: Do we need to unregister exception handling information from libgcc
1195 // here?
1196
1197 if (JITEmitDebugInfo) {
1198 DR->UnregisterFunction(F);
1199 }
1200
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001201 // If the function did not reference any stubs, return.
1202 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1203 return;
1204
1205 // For each referenced stub, erase the reference to this function, and then
1206 // erase the list of referenced stubs.
1207 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1208 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1209 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001210
1211 // If we already invalidated this stub for this function, continue.
1212 if (StubFnRefs.count(Stub) == 0)
1213 continue;
1214
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001215 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1216 FnRefs.erase(F);
1217
1218 // If this function was the last reference to the stub, invalidate the stub
1219 // in the JITResolver. Were there a memory manager deallocateStub routine,
1220 // we could call that at this point too.
1221 if (FnRefs.empty()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001222 DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
Nate Begeman841c6a42009-03-11 07:03:43 +00001223 StubFnRefs.erase(Stub);
1224
1225 // Invalidate the stub. If it is a GV stub, update the JIT's global
1226 // mapping for that GV to zero, otherwise, search the string map of
1227 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001228 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001229 if (GV) {
1230 TheJIT->updateGlobalMapping(GV, 0);
1231 } else {
1232 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1233 e = ExtFnStubs.end(); i != e; ++i) {
1234 if (i->second == Stub) {
1235 ExtFnStubs.erase(i);
1236 break;
1237 }
1238 }
1239 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001240 }
1241 }
1242 CurFnStubUses.erase(F);
1243}
1244
1245
Evan Cheng5788d1a2008-12-10 02:32:19 +00001246void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001247 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001248 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +00001249
1250 // create a new memory block if there is no active one.
1251 // care must be taken so that BufferBegin is invalidated when a
1252 // block is trimmed
1253 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1254 BufferEnd = BufferBegin+Size;
1255 return CurBufferPtr;
1256}
1257
Jeffrey Yasskin489393d2009-07-08 21:59:57 +00001258void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1259 // Delegate this call through the memory manager.
1260 return MemMgr->allocateGlobal(Size, Alignment);
1261}
1262
Chris Lattner166f2262004-11-22 22:00:25 +00001263void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001264 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001265 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001266
Chris Lattnerfa77d432006-02-09 04:22:52 +00001267 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001268 if (Constants.empty()) return;
1269
Evan Cheng1606e8e2009-03-13 07:51:59 +00001270 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1271 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001272 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001273 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001274
1275 if (ConstantPoolBase == 0) return; // Buffer overflow.
1276
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001277 DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1278 << "] (size: " << Size << ", alignment: " << Align << ")\n");
Evan Cheng97b8c402008-04-12 00:22:01 +00001279
Chris Lattner239862c2006-02-09 04:49:59 +00001280 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001281 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001282 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001283 MachineConstantPoolEntry CPE = Constants[i];
1284 unsigned AlignMask = CPE.getAlignment() - 1;
1285 Offset = (Offset + AlignMask) & ~AlignMask;
1286
1287 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1288 ConstPoolAddresses.push_back(CAddr);
1289 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001290 // FIXME: add support to lower machine constant pool values into bytes!
Torok Edwin7d696d82009-07-11 13:10:19 +00001291 llvm_report_error("Initialize memory with machine specific constant pool"
1292 "entry has not been implemented!");
Evan Chengcd5731d2006-09-12 20:59:59 +00001293 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001294 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001295 DEBUG(errs() << "JIT: CP" << i << " at [0x";
1296 errs().write_hex(CAddr) << "]\n");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001297
1298 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001299 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001300 }
1301}
1302
Nate Begeman37efe672006-04-22 18:53:45 +00001303void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001304 if (TheJIT->getJITInfo().hasCustomJumpTables())
1305 return;
1306
Nate Begeman37efe672006-04-22 18:53:45 +00001307 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1308 if (JT.empty()) return;
1309
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001310 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001311 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001312 NumEntries += JT[i].MBBs.size();
1313
1314 unsigned EntrySize = MJTI->getEntrySize();
1315
Nate Begeman37efe672006-04-22 18:53:45 +00001316 // Just allocate space for all the jump tables now. We will fix up the actual
1317 // MBB entries in the tables after we emit the code for each block, since then
1318 // we will know the final locations of the MBBs in memory.
1319 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001320 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001321}
1322
Jim Laskeyb92767a2006-12-14 22:53:42 +00001323void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001324 if (TheJIT->getJITInfo().hasCustomJumpTables())
1325 return;
1326
Nate Begeman37efe672006-04-22 18:53:45 +00001327 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001328 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001329
Jim Laskeyb92767a2006-12-14 22:53:42 +00001330 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001331 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1332 // For each jump table, place the offset from the beginning of the table
1333 // to the target address.
1334 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001335
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001336 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1337 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1338 // Store the offset of the basic block for this jump table slot in the
1339 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001340 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001341 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001342 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001343 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1344 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001345 }
1346 } else {
1347 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1348
1349 // For each jump table, map each target in the jump table to the address of
1350 // an emitted MachineBasicBlock.
1351 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1352
1353 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1354 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1355 // Store the address of the basic block for this jump table slot in the
1356 // memory we allocated for the jump table in 'initJumpTableInfo'
1357 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1358 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1359 }
Nate Begeman37efe672006-04-22 18:53:45 +00001360 }
1361}
1362
Evan Chengce4a70b2008-11-08 08:02:53 +00001363void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1364 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001365 SavedBufferBegin = BufferBegin;
1366 SavedBufferEnd = BufferEnd;
1367 SavedCurBufferPtr = CurBufferPtr;
1368
Evan Chengce4a70b2008-11-08 08:02:53 +00001369 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001370 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001371}
1372
Nate Begemand6b7a242009-02-18 08:31:02 +00001373void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1374 unsigned StubSize) {
1375 SavedBufferBegin = BufferBegin;
1376 SavedBufferEnd = BufferEnd;
1377 SavedCurBufferPtr = CurBufferPtr;
1378
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001379 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001380 BufferEnd = BufferBegin+StubSize+1;
1381}
1382
Evan Chengce4a70b2008-11-08 08:02:53 +00001383void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001384 NumBytes += getCurrentPCOffset();
1385 std::swap(SavedBufferBegin, BufferBegin);
1386 BufferEnd = SavedBufferEnd;
1387 CurBufferPtr = SavedCurBufferPtr;
1388 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001389}
1390
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001391// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1392// in the constant pool that was last emitted with the 'emitConstantPool'
1393// method.
1394//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001395uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001396 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001397 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001398 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001399}
1400
Nate Begeman37efe672006-04-22 18:53:45 +00001401// getJumpTableEntryAddress - Return the address of the JumpTable with index
1402// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1403//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001404uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001405 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1406 assert(Index < JT.size() && "Invalid jump table index!");
1407
1408 unsigned Offset = 0;
1409 unsigned EntrySize = JumpTable->getEntrySize();
1410
1411 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001412 Offset += JT[i].MBBs.size();
1413
1414 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001415
Evan Cheng5788d1a2008-12-10 02:32:19 +00001416 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001417}
1418
Chris Lattnere993cc22006-05-11 23:08:08 +00001419//===----------------------------------------------------------------------===//
1420// Public interface to this file
1421//===----------------------------------------------------------------------===//
1422
Reid Kleckner27632172009-09-20 23:52:43 +00001423JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1424 TargetMachine &tm) {
1425 return new JITEmitter(jit, JMM, tm);
Chris Lattnere993cc22006-05-11 23:08:08 +00001426}
1427
Misha Brukmand69c1e62003-07-28 19:09:06 +00001428// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001429// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001430// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1431// need to resolve function(s) that are being mis-codegenerated, so we need to
1432// resolve their addresses at runtime, and this is the way to do it.
1433extern "C" {
1434 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001435 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001436 return TheJIT->getPointerToFunction(F);
1437 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001438 }
1439}
Chris Lattnere993cc22006-05-11 23:08:08 +00001440
1441// getPointerToFunctionOrStub - If the specified function has been
1442// code-gen'd, return a pointer to the function. If not, compile it, or use
1443// a stub to implement lazy compilation if available.
1444//
1445void *JIT::getPointerToFunctionOrStub(Function *F) {
1446 // If we have already code generated the function, just return the address.
1447 if (void *Addr = getPointerToGlobalIfAvailable(F))
1448 return Addr;
1449
Chris Lattnere7484012007-02-24 02:57:03 +00001450 // Get a stub if the target supports it.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001451 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Evan Chenga044dfc2008-08-20 00:28:12 +00001452 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001453 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001454}
1455
Nate Begemand6b7a242009-02-18 08:31:02 +00001456void JIT::updateFunctionStub(Function *F) {
1457 // Get the empty stub we generated earlier.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001458 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001459 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1460 void *Stub = JE->getJITResolver().getFunctionStub(F);
1461
1462 // Tell the target jit info to rewrite the stub at the specified address,
1463 // rather than creating a new one.
1464 void *Addr = getPointerToGlobalIfAvailable(F);
1465 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1466}
1467
1468/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1469/// that were emitted during code generation.
1470///
1471void JIT::updateDlsymStubTable() {
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001472 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
Nate Begemand6b7a242009-02-18 08:31:02 +00001473 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1474
1475 SmallVector<GlobalValue*, 8> GVs;
1476 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001477 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001478
1479 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1480
Nate Begeman841c6a42009-03-11 07:03:43 +00001481 unsigned nStubs = GVs.size() + ExtFns.size();
1482
Nate Begemand6b7a242009-02-18 08:31:02 +00001483 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001484 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001485 return;
1486
1487 // If there are no new relocatable stubs, return.
1488 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001489 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001490 return;
1491
1492 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001493 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001494
1495 SmallVector<unsigned, 8> Offsets;
1496 for (unsigned i = 0; i != GVs.size(); ++i) {
1497 Offsets.push_back(offset);
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001498 offset += GVs[i]->getName().size() + 1;
Nate Begemand6b7a242009-02-18 08:31:02 +00001499 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001500 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1501 i != e; ++i) {
1502 Offsets.push_back(offset);
1503 offset += strlen(i->first()) + 1;
1504 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001505
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001506 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001507 JE->startGVStub(0, offset, 4);
1508
1509 // Emit the number of records
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001510 JE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001511
1512 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001513 for (unsigned i = 0; i != nStubs; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001514 JE->emitInt32(Offsets[i]);
Nate Begemand6b7a242009-02-18 08:31:02 +00001515
Nate Begeman66941982009-03-04 19:10:38 +00001516 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1517 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1518 // relocation can write the relocated pointer at the appropriate place in
1519 // the stub.
1520 for (unsigned i = 0; i != GVs.size(); ++i) {
1521 intptr_t Ptr = (intptr_t)Ptrs[i];
1522 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1523
1524 if (isa<Function>(GVs[i]))
1525 Ptr |= (intptr_t)1;
1526
Nate Begeman841c6a42009-03-11 07:03:43 +00001527 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001528 JE->emitInt64(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001529 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001530 JE->emitInt32(Ptr);
Nate Begeman841c6a42009-03-11 07:03:43 +00001531 }
1532 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1533 i != e; ++i) {
1534 intptr_t Ptr = (intptr_t)i->second | 1;
1535
1536 if (sizeof(Ptr) == 8)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001537 JE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001538 else
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001539 JE->emitInt32(Ptr);
Nate Begeman66941982009-03-04 19:10:38 +00001540 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001541
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001542 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001543 for (unsigned i = 0; i != GVs.size(); ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001544 JE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001545 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1546 i != e; ++i)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001547 JE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001548
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001549 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1550 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001551 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1552}
1553
Chris Lattnere993cc22006-05-11 23:08:08 +00001554/// freeMachineCodeForFunction - release machine code memory for given Function.
1555///
1556void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001557
Chris Lattnere993cc22006-05-11 23:08:08 +00001558 // Delete translation for this from the ExecutionEngine, so it will get
1559 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001560 void *OldPtr = updateGlobalMapping(F, 0);
1561
1562 if (OldPtr)
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +00001563 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001564
1565 // Free the actual memory for the function body and related stuff.
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +00001566 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1567 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001568}