blob: 58563563887c3b6233d705364f190a06ae8592e5 [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"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000017#include "JITDwarfEmitter.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000018#include "llvm/Constants.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000019#include "llvm/Module.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000020#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000021#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000023#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman37efe672006-04-22 18:53:45 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000026#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dale Johannesendd947ea2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000029#include "llvm/Target/TargetData.h"
Chris Lattner5be478f2004-11-20 03:46:14 +000030#include "llvm/Target/TargetJITInfo.h"
Jim Laskeyacd80ac2006-12-14 19:17:33 +000031#include "llvm/Target/TargetMachine.h"
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000032#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000034#include "llvm/Support/MutexGuard.h"
Nick Lewycky848b3142009-04-19 18:32:03 +000035#include "llvm/Support/ValueHandle.h"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000036#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000037#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000038#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000039#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000042#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000043#ifndef NDEBUG
44#include <iomanip>
45#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Chris Lattner36343732006-12-19 22:43:32 +000048STATISTIC(NumBytes, "Number of bytes of machine code compiled");
49STATISTIC(NumRelos, "Number of relocations applied");
50static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000051
Andrew Lenhartha00269b2005-07-29 23:40:16 +000052
Chris Lattner54266522004-11-20 23:57:07 +000053//===----------------------------------------------------------------------===//
54// JIT lazy compilation code.
55//
56namespace {
Reid Spenceree448632005-07-12 15:51:55 +000057 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000058 public:
59 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
60 typedef std::map<void*, Function*> StubToFunctionMapTy;
61 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000062 private:
63 /// FunctionToStubMap - Keep track of the stub created for a particular
64 /// function so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000065 FunctionToStubMapTy FunctionToStubMap;
Reid Spenceree448632005-07-12 15:51:55 +000066
67 /// StubToFunctionMap - Keep track of the function that each stub
68 /// corresponds to.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000069 StubToFunctionMapTy StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000070
Evan Cheng5594f122008-11-10 01:52:24 +000071 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000072 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +000073 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000074
Reid Spenceree448632005-07-12 15:51:55 +000075 public:
Nick Lewyckye2bcf132009-04-27 05:09:44 +000076 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000077 assert(locked.holds(TheJIT->lock));
78 return FunctionToStubMap;
79 }
Jeff Cohen00b168892005-07-27 06:12:32 +000080
Nick Lewyckye2bcf132009-04-27 05:09:44 +000081 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +000082 assert(locked.holds(TheJIT->lock));
83 return StubToFunctionMap;
84 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000085
Nick Lewyckye2bcf132009-04-27 05:09:44 +000086 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000087 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000088 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000089 }
Reid Spenceree448632005-07-12 15:51:55 +000090 };
Jeff Cohen00b168892005-07-27 06:12:32 +000091
Chris Lattner54266522004-11-20 23:57:07 +000092 /// JITResolver - Keep track of, and resolve, call sites for functions that
93 /// have not yet been compiled.
94 class JITResolver {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000095 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
96 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
97 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
98
Chris Lattner5e225582004-11-21 03:37:42 +000099 /// LazyResolverFn - The target lazy resolver function that we actually
100 /// rewrite instructions to use.
101 TargetJITInfo::LazyResolverFn LazyResolverFn;
102
Reid Spenceree448632005-07-12 15:51:55 +0000103 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000104
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000105 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
106 /// external functions.
107 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000108
Evan Cheng1606e8e2009-03-13 07:51:59 +0000109 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000110 std::map<void*, unsigned> revGOTMap;
111 unsigned nextGOTIndex;
112
Chris Lattnere7484012007-02-24 02:57:03 +0000113 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000114 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000115 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000116 TheJIT = &jit;
117
118 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
119 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
120 TheJITResolver = this;
121 }
122
123 ~JITResolver() {
124 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000125 }
Chris Lattner54266522004-11-20 23:57:07 +0000126
Evan Cheng704bff92008-11-13 21:50:50 +0000127 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
128 /// if it has already been created.
129 void *getFunctionStubIfAvailable(Function *F);
130
Chris Lattner54266522004-11-20 23:57:07 +0000131 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000132 /// one on demand as needed. If empty is true, create a function stub
133 /// pointing at address 0, to be filled in later.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000134 void *getFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000135
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000136 /// getExternalFunctionStub - Return a stub for the function at the
137 /// specified address, created lazily on demand.
138 void *getExternalFunctionStub(void *FnAddr);
139
Evan Cheng5594f122008-11-10 01:52:24 +0000140 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000141 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000142 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000143
Chris Lattner5e225582004-11-21 03:37:42 +0000144 /// AddCallbackAtLocation - If the target is capable of rewriting an
145 /// instruction without the use of a stub, record the location of the use so
146 /// we know which function is being used at the location.
147 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000148 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000149 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000150 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000151 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000152 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000153
154 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000155 SmallVectorImpl<void*> &Ptrs);
156
157 GlobalValue *invalidateStub(void *Stub);
Chris Lattner5e225582004-11-21 03:37:42 +0000158
Andrew Lenharth6a974612005-07-28 12:44:13 +0000159 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000160 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000161 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000162 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000163
Chris Lattner54266522004-11-20 23:57:07 +0000164 /// JITCompilerFn - This function is called to resolve a stub to a compiled
165 /// address. If the LLVM Function corresponding to the stub has not yet
166 /// been compiled, this function compiles it first.
167 static void *JITCompilerFn(void *Stub);
168 };
169}
170
Chris Lattnere7484012007-02-24 02:57:03 +0000171JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000172
Evan Cheng704bff92008-11-13 21:50:50 +0000173/// getFunctionStubIfAvailable - This returns a pointer to a function stub
174/// if it has already been created.
175void *JITResolver::getFunctionStubIfAvailable(Function *F) {
176 MutexGuard locked(TheJIT->lock);
177
178 // If we already have a stub for this function, recycle it.
179 void *&Stub = state.getFunctionToStubMap(locked)[F];
180 return Stub;
181}
182
Chris Lattner54266522004-11-20 23:57:07 +0000183/// getFunctionStub - This returns a pointer to a function stub, creating
184/// one on demand as needed.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000185void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000186 MutexGuard locked(TheJIT->lock);
187
Chris Lattner54266522004-11-20 23:57:07 +0000188 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000189 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000190 if (Stub) return Stub;
191
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000192 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
193 // case we must resolve the symbol now.
194 void *Actual = TheJIT->isLazyCompilationDisabled()
195 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
196
197 // If this is an external declaration, attempt to resolve the address now
198 // to place in the stub.
Dan Gohman69f93782009-01-05 05:32:42 +0000199 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000200 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000201
Dan Gohman69f93782009-01-05 05:32:42 +0000202 // If we resolved the symbol to a null address (eg. a weak external)
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000203 // don't emit a stub. Return a null pointer to the application. If dlsym
204 // stubs are enabled, not being able to resolve the address is not
205 // meaningful.
206 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
Dan Gohman69f93782009-01-05 05:32:42 +0000207 }
208
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000209 // Codegen a new stub, calling the lazy resolver or the actual address of the
210 // external function, if it was resolved.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000211 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000212 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000213
Chris Lattner870286a2006-06-01 17:29:22 +0000214 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000215 // If we are getting the stub for an external function, we really want the
216 // address of the stub in the GlobalAddressMap for the JIT, not the address
217 // of the external function.
218 TheJIT->updateGlobalMapping(F, Stub);
219 }
Chris Lattner54266522004-11-20 23:57:07 +0000220
Chris Lattnerbe3ae8e2009-03-05 06:48:16 +0000221 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
Bill Wendling832171c2006-12-07 20:04:42 +0000222 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000223
Chris Lattner54266522004-11-20 23:57:07 +0000224 // Finally, keep track of the stub-to-Function mapping so that the
225 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000226 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000227
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000228 // If we are JIT'ing non-lazily but need to call a function that does not
229 // exist yet, add it to the JIT's work list so that we can fill in the stub
230 // address later.
231 if (!Actual && TheJIT->isLazyCompilationDisabled())
232 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
233 TheJIT->addPendingFunction(F);
Nate Begemand6b7a242009-02-18 08:31:02 +0000234
Chris Lattner54266522004-11-20 23:57:07 +0000235 return Stub;
236}
237
Evan Cheng5594f122008-11-10 01:52:24 +0000238/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000239/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000240void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000241 MutexGuard locked(TheJIT->lock);
242
243 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000244 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
245 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000246
Evan Chenge4d783d2008-11-10 23:26:16 +0000247 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000248 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000249 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000250
Evan Cheng5594f122008-11-10 01:52:24 +0000251 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000252 << GV->getName() << "'\n";
253
Evan Cheng5594f122008-11-10 01:52:24 +0000254 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000255}
256
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000257/// getExternalFunctionStub - Return a stub for the function at the
258/// specified address, created lazily on demand.
259void *JITResolver::getExternalFunctionStub(void *FnAddr) {
260 // If we already have a stub for this function, recycle it.
261 void *&Stub = ExternalFnToStubMap[FnAddr];
262 if (Stub) return Stub;
263
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000264 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000265 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000266
Bill Wendling832171c2006-12-07 20:04:42 +0000267 DOUT << "JIT: Stub emitted at [" << Stub
268 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000269 return Stub;
270}
271
Andrew Lenharth6a974612005-07-28 12:44:13 +0000272unsigned JITResolver::getGOTIndexForAddr(void* addr) {
273 unsigned idx = revGOTMap[addr];
274 if (!idx) {
275 idx = ++nextGOTIndex;
276 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000277 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000278 }
279 return idx;
280}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000281
Nate Begemand6b7a242009-02-18 08:31:02 +0000282void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
283 SmallVectorImpl<void*> &Ptrs) {
284 MutexGuard locked(TheJIT->lock);
285
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000286 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
287 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begemand6b7a242009-02-18 08:31:02 +0000288
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000289 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
Nate Begemand6b7a242009-02-18 08:31:02 +0000290 Function *F = i->first;
291 if (F->isDeclaration() && F->hasExternalLinkage()) {
292 GVs.push_back(i->first);
293 Ptrs.push_back(i->second);
294 }
295 }
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000296 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begemand6b7a242009-02-18 08:31:02 +0000297 i != e; ++i) {
298 GVs.push_back(i->first);
299 Ptrs.push_back(i->second);
300 }
301}
302
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000303GlobalValue *JITResolver::invalidateStub(void *Stub) {
304 MutexGuard locked(TheJIT->lock);
305
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000306 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
307 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
308 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000309
310 // Look up the cheap way first, to see if it's a function stub we are
311 // invalidating. If so, remove it from both the forward and reverse maps.
312 if (SM.find(Stub) != SM.end()) {
313 Function *F = SM[Stub];
314 SM.erase(Stub);
315 FM.erase(F);
316 return F;
317 }
318
Nate Begeman841c6a42009-03-11 07:03:43 +0000319 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000320 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000321 i != e; ++i) {
322 if (i->second != Stub)
323 continue;
324 GlobalValue *GV = i->first;
325 GM.erase(i);
326 return GV;
327 }
328
Nate Begeman841c6a42009-03-11 07:03:43 +0000329 // Lastly, check to see if it's in the ExternalFnToStubMap.
330 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
331 e = ExternalFnToStubMap.end(); i != e; ++i) {
332 if (i->second != Stub)
333 continue;
334 ExternalFnToStubMap.erase(i);
335 break;
336 }
337
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000338 return 0;
339}
340
Chris Lattner54266522004-11-20 23:57:07 +0000341/// JITCompilerFn - This function is called when a lazy compilation stub has
342/// been entered. It looks up which function this stub corresponds to, compiles
343/// it if necessary, then returns the resultant function pointer.
344void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000345 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000346
347 Function* F = 0;
348 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000349
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000350 {
351 // Only lock for getting the Function. The call getPointerToFunction made
352 // in this function might trigger function materializing, which requires
353 // JIT lock to be unlocked.
354 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000355
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000356 // The address given to us for the stub may not be exactly right, it might be
357 // a little bit after the stub. As such, use upper_bound to find it.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000358 StubToFunctionMapTy::iterator I =
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000359 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
360 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
361 "This is not a known stub!");
362 F = (--I)->second;
363 ActualPtr = I->first;
364 }
Chris Lattner54266522004-11-20 23:57:07 +0000365
Evan Cheng9da60f92007-06-30 00:10:37 +0000366 // If we have already code generated the function, just return the address.
367 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000368
Evan Cheng9da60f92007-06-30 00:10:37 +0000369 if (!Result) {
370 // Otherwise we don't have it, do lazy compilation now.
371
372 // If lazy compilation is disabled, emit a useful error message and abort.
373 if (TheJIT->isLazyCompilationDisabled()) {
374 cerr << "LLVM JIT requested to do lazy compilation of function '"
375 << F->getName() << "' when lazy compiles are disabled!\n";
376 abort();
377 }
378
379 // We might like to remove the stub from the StubToFunction map.
380 // We can't do that! Multiple threads could be stuck, waiting to acquire the
381 // lock above. As soon as the 1st function finishes compiling the function,
382 // the next one will be released, and needs to be able to find the function
383 // it needs to call.
384 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000385
Evan Cheng9da60f92007-06-30 00:10:37 +0000386 DOUT << "JIT: Lazily resolving function '" << F->getName()
387 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000388 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000389
Evan Cheng9da60f92007-06-30 00:10:37 +0000390 Result = TheJIT->getPointerToFunction(F);
391 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000392
393 // Reacquire the lock to erase the stub in the map.
394 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000395
396 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000397 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000398
399 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000400
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000401 // What we will do is set the compiled function address to map to the
402 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000403 // if they see it still using the stub address.
404 // Note: this is done so the Resolver doesn't have to manage GOT memory
405 // Do this without allocating map space if the target isn't using a GOT
406 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
407 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
408
Chris Lattner54266522004-11-20 23:57:07 +0000409 return Result;
410}
Chris Lattner688506d2003-08-14 18:35:27 +0000411
Chris Lattner8ac66c12008-04-04 05:51:42 +0000412//===----------------------------------------------------------------------===//
413// Function Index Support
414
415// On MacOS we generate an index of currently JIT'd functions so that
416// performance tools can determine a symbol name and accurate code range for a
417// PC value. Because performance tools are generally asynchronous, the code
418// below is written with the hope that it could be interrupted at any time and
419// have useful answers. However, we don't go crazy with atomic operations, we
420// just do a "reasonable effort".
421#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000422#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000423#endif
424
425/// JitSymbolEntry - Each function that is JIT compiled results in one of these
426/// being added to an array of symbols. This indicates the name of the function
427/// as well as the address range it occupies. This allows the client to map
428/// from a PC value to the name of the function.
429struct JitSymbolEntry {
430 const char *FnName; // FnName - a strdup'd string.
431 void *FnStart;
432 intptr_t FnSize;
433};
434
435
436struct JitSymbolTable {
437 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
438 /// pointer is not used right now, but might be used in the future. Consider
439 /// it reserved for future use.
440 JitSymbolTable *NextPtr;
441
442 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
443 /// 'NumSymbols' symbols are valid.
444 JitSymbolEntry *Symbols;
445
446 /// NumSymbols - This indicates the number entries in the Symbols array that
447 /// are valid.
448 unsigned NumSymbols;
449
450 /// NumAllocated - This indicates the amount of space we have in the Symbols
451 /// array. This is a private field that should not be read by external tools.
452 unsigned NumAllocated;
453};
454
455#if ENABLE_JIT_SYMBOL_TABLE
456JitSymbolTable *__jitSymbolTable;
457#endif
458
459static void AddFunctionToSymbolTable(const char *FnName,
460 void *FnStart, intptr_t FnSize) {
461 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
462 JitSymbolTable **SymTabPtrPtr = 0;
463#if !ENABLE_JIT_SYMBOL_TABLE
464 return;
465#else
466 SymTabPtrPtr = &__jitSymbolTable;
467#endif
468
469 // If this is the first entry in the symbol table, add the JitSymbolTable
470 // index.
471 if (*SymTabPtrPtr == 0) {
472 JitSymbolTable *New = new JitSymbolTable();
473 New->NextPtr = 0;
474 New->Symbols = 0;
475 New->NumSymbols = 0;
476 New->NumAllocated = 0;
477 *SymTabPtrPtr = New;
478 }
479
480 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
481
482 // If we have space in the table, reallocate the table.
483 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
484 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000485 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000486 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
487 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
488
489 // Copy the old entries over.
Nate Begemand6b7a242009-02-18 08:31:02 +0000490 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000491
492 // Swap the new symbols in, delete the old ones.
493 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000494 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000495 delete [] OldSymbols;
496 }
497
498 // Otherwise, we have enough space, just tack it onto the end of the array.
499 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
500 Entry.FnName = strdup(FnName);
501 Entry.FnStart = FnStart;
502 Entry.FnSize = FnSize;
503 ++SymTabPtr->NumSymbols;
504}
505
506static void RemoveFunctionFromSymbolTable(void *FnStart) {
507 assert(FnStart && "Invalid function pointer");
508 JitSymbolTable **SymTabPtrPtr = 0;
509#if !ENABLE_JIT_SYMBOL_TABLE
510 return;
511#else
512 SymTabPtrPtr = &__jitSymbolTable;
513#endif
514
515 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
516 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
517
518 // Scan the table to find its index. The table is not sorted, so do a linear
519 // scan.
520 unsigned Index;
521 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
522 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
523
524 // Once we have an index, we know to nuke this entry, overwrite it with the
525 // entry at the end of the array, making the last entry redundant.
526 const char *OldName = Symbols[Index].FnName;
527 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
528 free((void*)OldName);
529
530 // Drop the number of symbols in the table.
531 --SymTabPtr->NumSymbols;
532
533 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000534 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000535 return;
536
537 *SymTabPtrPtr = 0;
538 delete [] Symbols;
539 delete SymTabPtr;
540}
Chris Lattner688506d2003-08-14 18:35:27 +0000541
Chris Lattner54266522004-11-20 23:57:07 +0000542//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000543// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000544//
Chris Lattner688506d2003-08-14 18:35:27 +0000545namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000546 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
547 /// used to output functions to memory for execution.
548 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000549 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000550
Chris Lattner6125fdd2003-05-09 03:30:07 +0000551 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000552 // save BufferBegin/BufferEnd/CurBufferPtr here.
553 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000554
Chris Lattner5be478f2004-11-20 03:46:14 +0000555 /// Relocations - These are the relocations that the function needs, as
556 /// emitted.
557 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000558
559 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
560 /// It is filled in by the StartMachineBasicBlock callback and queried by
561 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000562 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000563
Chris Lattner239862c2006-02-09 04:49:59 +0000564 /// ConstantPool - The constant pool for the current function.
565 ///
566 MachineConstantPool *ConstantPool;
567
568 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
569 ///
570 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000571
Evan Cheng1606e8e2009-03-13 07:51:59 +0000572 /// ConstPoolAddresses - Addresses of individual constant pool entries.
573 ///
574 SmallVector<uintptr_t, 8> ConstPoolAddresses;
575
Nate Begeman019f8512006-09-10 23:03:44 +0000576 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000577 ///
578 MachineJumpTableInfo *JumpTable;
579
580 /// JumpTableBase - A pointer to the first entry in the jump table.
581 ///
582 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000583
Chris Lattnere7484012007-02-24 02:57:03 +0000584 /// Resolver - This contains info about the currently resolved functions.
585 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000586
587 /// DE - The dwarf emitter for the jit.
588 JITDwarfEmitter *DE;
589
590 /// LabelLocations - This vector is a mapping from Label ID's to their
591 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000592 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000593
594 /// MMI - Machine module info for exception informations
595 MachineModuleInfo* MMI;
596
Dale Johannesendd947ea2008-08-07 01:30:15 +0000597 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000598 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000599
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000600 // CurFn - The llvm function being emitted. Only valid during
601 // finishFunction().
602 const Function *CurFn;
603
604 // CurFnStubUses - For a given Function, a vector of stubs that it
605 // references. This facilitates the JIT detecting that a stub is no
606 // longer used, so that it may be deallocated.
607 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
608
609 // StubFnRefs - For a given pointer to a stub, a set of Functions which
610 // reference the stub. When the count of a stub's references drops to zero,
611 // the stub is unused.
612 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
613
Nate Begeman841c6a42009-03-11 07:03:43 +0000614 // ExtFnStubs - A map of external function names to stubs which have entries
615 // in the JITResolver's ExternalFnToStubMap.
616 StringMap<void *> ExtFnStubs;
617
Chris Lattnere7484012007-02-24 02:57:03 +0000618 public:
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000619 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
Chris Lattner9f2f1422007-12-06 01:08:09 +0000620 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000621 if (jit.getJITInfo().needsGOT()) {
622 MemMgr->AllocateGOT();
623 DOUT << "JIT is managing a GOT\n";
624 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000625
626 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000627 }
628 ~JITEmitter() {
629 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000630 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000631 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000632
633 /// classof - Methods for support type inquiry through isa, cast, and
634 /// dyn_cast:
635 ///
636 static inline bool classof(const JITEmitter*) { return true; }
637 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000638
639 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000640
641 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000642 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000643
644 void emitConstantPool(MachineConstantPool *MCP);
645 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000646 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000647
Evan Chengce4a70b2008-11-08 08:02:53 +0000648 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000649 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000650 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
651 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000652 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000653
Nuno Lopescef75272008-10-21 11:42:16 +0000654 /// allocateSpace - Reserves space in the current block if any, or
655 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000656 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000657
Chris Lattner5be478f2004-11-20 03:46:14 +0000658 virtual void addRelocation(const MachineRelocation &MR) {
659 Relocations.push_back(MR);
660 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000661
662 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
663 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
664 MBBLocations.resize((MBB->getNumber()+1)*2);
665 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000666 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
667 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000668 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000669
Evan Cheng5788d1a2008-12-10 02:32:19 +0000670 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
671 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000672
Evan Cheng5788d1a2008-12-10 02:32:19 +0000673 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000674 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
675 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
676 return MBBLocations[MBB->getNumber()];
677 }
678
Chris Lattnere993cc22006-05-11 23:08:08 +0000679 /// deallocateMemForFunction - Deallocate all memory for the specified
680 /// function body.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000681 void deallocateMemForFunction(Function *F);
Nate Begeman841c6a42009-03-11 07:03:43 +0000682
683 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
684 /// using the stub at the specified address. Allows
685 /// deallocateMemForFunction to also remove stubs no longer referenced.
686 void AddStubToCurrentFunction(void *Stub);
687
688 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
689 /// MachineRelocations that reference external functions by name.
690 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000691
692 virtual void emitLabel(uint64_t LabelID) {
693 if (LabelLocations.size() <= LabelID)
694 LabelLocations.resize((LabelID+1)*2);
695 LabelLocations[LabelID] = getCurrentPCValue();
696 }
697
Evan Cheng5788d1a2008-12-10 02:32:19 +0000698 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000699 assert(LabelLocations.size() > (unsigned)LabelID &&
700 LabelLocations[LabelID] && "Label not emitted!");
701 return LabelLocations[LabelID];
702 }
703
704 virtual void setModuleInfo(MachineModuleInfo* Info) {
705 MMI = Info;
706 if (ExceptionHandling) DE->setModuleInfo(Info);
707 }
708
Jim Grosbachcce6c292008-10-03 16:17:20 +0000709 void setMemoryExecutable(void) {
710 MemMgr->setMemoryExecutable();
711 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000712
713 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000714
Chris Lattner54266522004-11-20 23:57:07 +0000715 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000716 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000717 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000718 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000719 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
720 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
721 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
722 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000723 };
724}
725
Chris Lattner166f2262004-11-22 22:00:25 +0000726void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
727 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000728 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000729 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000730
Chris Lattner18e04592008-06-25 20:21:35 +0000731 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000732 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000733
734 // If we have already compiled the function, return a pointer to its body.
735 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000736 void *ResultPtr;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000737 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
Evan Cheng704bff92008-11-13 21:50:50 +0000738 // Return the function stub if it's already created.
739 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000740 if (ResultPtr)
741 AddStubToCurrentFunction(ResultPtr);
742 } else {
Evan Cheng704bff92008-11-13 21:50:50 +0000743 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000744 }
Chris Lattner54266522004-11-20 23:57:07 +0000745 if (ResultPtr) return ResultPtr;
746
Nate Begemand6b7a242009-02-18 08:31:02 +0000747 // If this is an external function pointer, we can force the JIT to
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000748 // 'compile' it, which really just adds it to the map. In dlsym mode,
749 // external functions are forced through a stub, regardless of reloc type.
750 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
751 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
Nate Begemand6b7a242009-02-18 08:31:02 +0000752 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000753
Chris Lattner5e225582004-11-21 03:37:42 +0000754 // Okay, the function has not been compiled yet, if the target callback
755 // mechanism is capable of rewriting the instruction directly, prefer to do
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000756 // that instead of emitting a stub. This uses the lazy resolver, so is not
757 // legal if lazy compilation is disabled.
758 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Chris Lattnere7484012007-02-24 02:57:03 +0000759 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000760
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000761 // Otherwise, we have to emit a stub.
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000762 void *StubAddr = Resolver.getFunctionStub(F);
763
764 // Add the stub to the current function's list of referenced stubs, so we can
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000765 // deallocate them if the current function is ever freed. It's possible to
766 // return null from getFunctionStub in the case of a weak extern that fails
767 // to resolve.
768 if (StubAddr)
769 AddStubToCurrentFunction(StubAddr);
770
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000771 return StubAddr;
Chris Lattner54266522004-11-20 23:57:07 +0000772}
773
Evan Cheng5594f122008-11-10 01:52:24 +0000774void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000775 bool NoNeedStub) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000776 // Make sure GV is emitted first, and create a stub containing the fully
777 // resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000778 void *GVAddress = getPointerToGlobal(V, Reference, true);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000779 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
780
781 // Add the stub to the current function's list of referenced stubs, so we can
782 // deallocate them if the current function is ever freed.
783 AddStubToCurrentFunction(StubAddr);
784
785 return StubAddr;
786}
787
788void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
789 if (!TheJIT->areDlsymStubsEnabled())
790 return;
791
792 assert(CurFn && "Stub added to current function, but current function is 0!");
793
794 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
795 StubsUsed.push_back(StubAddr);
796
797 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
798 FnRefs.insert(CurFn);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000799}
800
Evan Cheng1606e8e2009-03-13 07:51:59 +0000801static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
802 const TargetData *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000803 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
804 if (Constants.empty()) return 0;
805
Evan Cheng1606e8e2009-03-13 07:51:59 +0000806 unsigned Size = 0;
807 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
808 MachineConstantPoolEntry CPE = Constants[i];
809 unsigned AlignMask = CPE.getAlignment() - 1;
810 Size = (Size + AlignMask) & ~AlignMask;
811 const Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000812 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000813 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000814 return Size;
815}
816
817static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
818 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
819 if (JT.empty()) return 0;
820
821 unsigned NumEntries = 0;
822 for (unsigned i = 0, e = JT.size(); i != e; ++i)
823 NumEntries += JT[i].MBBs.size();
824
825 unsigned EntrySize = MJTI->getEntrySize();
826
827 return NumEntries * EntrySize;
828}
829
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000830static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000831 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000832 // Since we do not know where the buffer will be allocated, be pessimistic.
833 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000834}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000835
Dale Johannesendd947ea2008-08-07 01:30:15 +0000836/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
837/// into the running total Size.
838
839unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
840 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000841 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000842 size_t GVAlign =
843 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000844 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000845 DEBUG(GV->dump());
846 // Assume code section ends with worst possible alignment, so first
847 // variable needs maximal padding.
848 if (Size==0)
849 Size = 1;
850 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
851 Size += GVSize;
852 return Size;
853}
854
855/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
856/// but are referenced from the constant; put them in GVSet and add their
857/// size into the running total Size.
858
859unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
860 unsigned Size) {
861 // If its undefined, return the garbage.
862 if (isa<UndefValue>(C))
863 return Size;
864
865 // If the value is a ConstantExpr
866 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
867 Constant *Op0 = CE->getOperand(0);
868 switch (CE->getOpcode()) {
869 case Instruction::GetElementPtr:
870 case Instruction::Trunc:
871 case Instruction::ZExt:
872 case Instruction::SExt:
873 case Instruction::FPTrunc:
874 case Instruction::FPExt:
875 case Instruction::UIToFP:
876 case Instruction::SIToFP:
877 case Instruction::FPToUI:
878 case Instruction::FPToSI:
879 case Instruction::PtrToInt:
880 case Instruction::IntToPtr:
881 case Instruction::BitCast: {
882 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
883 break;
884 }
885 case Instruction::Add:
886 case Instruction::Sub:
887 case Instruction::Mul:
888 case Instruction::UDiv:
889 case Instruction::SDiv:
890 case Instruction::URem:
891 case Instruction::SRem:
892 case Instruction::And:
893 case Instruction::Or:
894 case Instruction::Xor: {
895 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
896 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
897 break;
898 }
899 default: {
900 cerr << "ConstantExpr not handled: " << *CE << "\n";
901 abort();
902 }
903 }
904 }
905
906 if (C->getType()->getTypeID() == Type::PointerTyID)
907 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000908 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000909 Size = addSizeOfGlobal(GV, Size);
910
911 return Size;
912}
913
914/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
915/// but are referenced from the given initializer.
916
917unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
918 unsigned Size) {
919 if (!isa<UndefValue>(Init) &&
920 !isa<ConstantVector>(Init) &&
921 !isa<ConstantAggregateZero>(Init) &&
922 !isa<ConstantArray>(Init) &&
923 !isa<ConstantStruct>(Init) &&
924 Init->getType()->isFirstClassType())
925 Size = addSizeOfGlobalsInConstantVal(Init, Size);
926 return Size;
927}
928
929/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
930/// globals; then walk the initializers of those globals looking for more.
931/// If their size has not been considered yet, add it into the running total
932/// Size.
933
934unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
935 unsigned Size = 0;
936 GVSet.clear();
937
938 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
939 MBB != E; ++MBB) {
940 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
941 I != E; ++I) {
942 const TargetInstrDesc &Desc = I->getDesc();
943 const MachineInstr &MI = *I;
944 unsigned NumOps = Desc.getNumOperands();
945 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
946 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000947 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000948 GlobalValue* V = MO.getGlobal();
949 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
950 if (!GV)
951 continue;
952 // If seen in previous function, it will have an entry here.
953 if (TheJIT->getPointerToGlobalIfAvailable(GV))
954 continue;
955 // If seen earlier in this function, it will have an entry here.
956 // FIXME: it should be possible to combine these tables, by
957 // assuming the addresses of the new globals in this module
958 // start at 0 (or something) and adjusting them after codegen
959 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000960 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000961 // A variable as yet unseen. Add in its size.
962 Size = addSizeOfGlobal(GV, Size);
963 }
964 }
965 }
966 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000967 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000968 // Look for more globals that are referenced only from initializers.
969 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000970 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000971 I != GVSet.end(); I++) {
972 const GlobalVariable* GV = *I;
973 if (GV->hasInitializer())
974 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
975 }
976
977 return Size;
978}
979
Chris Lattner166f2262004-11-22 22:00:25 +0000980void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000981 DOUT << "JIT: Starting CodeGen of Function "
982 << F.getFunction()->getName() << "\n";
983
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000984 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000985 // Set the memory writable, if it's not already
986 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000987 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000988 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000989 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
990 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
991 MachineConstantPool *MCP = F.getConstantPool();
992
993 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000994 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000995
996 // Add the alignment of the constant pool
Evan Cheng1606e8e2009-03-13 07:51:59 +0000997 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000998
999 // Add the constant pool size
Evan Cheng1606e8e2009-03-13 07:51:59 +00001000 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001001
1002 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001003 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001004
1005 // Add the jump table size
1006 ActualSize += GetJumpTableSizeInBytes(MJTI);
1007
1008 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +00001009 ActualSize = RoundUpToAlign(ActualSize,
1010 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001011
1012 // Add the function size
1013 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +00001014
Evan Chengeb5d95a2008-11-06 17:46:04 +00001015 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +00001016 // Add the size of the globals that will be allocated after this function.
1017 // These are all the ones referenced from this function that were not
1018 // previously allocated.
1019 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +00001020 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001021 }
1022
Chris Lattner8907b4b2007-12-05 23:39:57 +00001023 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1024 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +00001025 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001026
Evan Cheng9a1e9b92006-11-16 20:04:54 +00001027 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1028 emitAlignment(16);
1029
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001030 emitConstantPool(F.getConstantPool());
1031 initJumpTableInfo(F.getJumpTableInfo());
1032
1033 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +00001034 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001035 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +00001036
Chris Lattnerb4432f32006-05-03 17:10:41 +00001037 MBBLocations.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) {
1042 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +00001043 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +00001044 abort();
1045 }
1046
Jim Laskeyb92767a2006-12-14 22:53:42 +00001047 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +00001048
Chris Lattnera8279532006-06-16 18:09:26 +00001049 // FnStart is the start of the text, not the start of the constant pool and
1050 // other per-function data.
1051 unsigned char *FnStart =
1052 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001053
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001054 // FnEnd is the end of the function's machine code.
1055 unsigned char *FnEnd = CurBufferPtr;
1056
Chris Lattner5be478f2004-11-20 03:46:14 +00001057 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001058 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +00001059 NumRelos += Relocations.size();
1060
Chris Lattner5be478f2004-11-20 03:46:14 +00001061 // Resolve the relocations to concrete pointers.
1062 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1063 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +00001064 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +00001065 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +00001066 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +00001067 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1068 false);
Evan Chengd7398c92008-11-08 07:37:34 +00001069 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +00001070 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001071
Evan Chengef5784e2008-10-29 23:54:46 +00001072 // If the target REALLY wants a stub for this function, emit it now.
Nate Begeman841c6a42009-03-11 07:03:43 +00001073 if (!MR.doesntNeedStub()) {
1074 if (!TheJIT->areDlsymStubsEnabled()) {
1075 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1076 } else {
1077 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1078 if (!Stub) {
1079 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1080 AddStubToCurrentFunction(Stub);
1081 }
1082 ResultPtr = Stub;
1083 }
1084 }
Evan Chengef5784e2008-10-29 23:54:46 +00001085 } else if (MR.isGlobalValue()) {
1086 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1087 BufferBegin+MR.getMachineCodeOffset(),
1088 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +00001089 } else if (MR.isIndirectSymbol()) {
1090 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +00001091 BufferBegin+MR.getMachineCodeOffset(),
1092 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +00001093 } else if (MR.isBasicBlock()) {
1094 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1095 } else if (MR.isConstantPoolIndex()) {
1096 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1097 } else {
1098 assert(MR.isJumpTableIndex());
1099 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1100 }
Jeff Cohen00b168892005-07-27 06:12:32 +00001101
Evan Chengef5784e2008-10-29 23:54:46 +00001102 MR.setResultPointer(ResultPtr);
1103 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001104
Andrew Lenharth6a974612005-07-28 12:44:13 +00001105 // if we are managing the GOT and the relocation wants an index,
1106 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +00001107 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001108 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +00001109 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001110 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001111 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +00001112 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +00001113 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +00001114 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001115 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +00001116 }
Chris Lattner5be478f2004-11-20 03:46:14 +00001117 }
1118
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001119 CurFn = 0;
Chris Lattner43b429b2006-05-02 18:27:26 +00001120 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +00001121 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +00001122 }
1123
Chris Lattnerd2d5c762006-05-03 18:55:56 +00001124 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +00001125 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +00001126 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +00001127 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001128 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001129 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1130 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001131 }
1132 }
1133
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +00001134 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1135 // global variables that were referenced in the relocations.
1136 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001137
1138 if (CurBufferPtr == BufferEnd) {
1139 // FIXME: Allocate more space, then try again.
1140 cerr << "JIT: Ran out of space for generated machine code!\n";
1141 abort();
1142 }
1143
Nuno Lopescef75272008-10-21 11:42:16 +00001144 BufferBegin = CurBufferPtr = 0;
1145 NumBytes += FnEnd-FnStart;
1146
Evan Cheng55fc2802006-07-25 20:40:54 +00001147 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001148 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +00001149
1150 // Add it to the JIT symbol table if the host wants it.
1151 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1152 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +00001153
Bill Wendling832171c2006-12-07 20:04:42 +00001154 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1155 << "] Function: " << F.getFunction()->getName()
1156 << ": " << (FnEnd-FnStart) << " bytes of text, "
1157 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +00001158 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +00001159 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001160
Evan Chengbc4707a2008-09-18 07:54:21 +00001161 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001162 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001163
Chris Lattnerc5633c22007-01-20 20:51:43 +00001164#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001165 {
Evan Chenge7c35512008-11-12 08:22:43 +00001166 if (sys::hasDisassembler()) {
1167 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001168 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001169 } else {
1170 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001171 DOUT << std::hex;
Evan Chenga7916f52008-11-05 23:44:08 +00001172 unsigned char* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001173 for (int i = 0; q < FnEnd; q += 4, ++i) {
1174 if (i == 4)
1175 i = 0;
1176 if (i == 0)
1177 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1178 << (long)(q - FnStart) << ": ";
1179 bool Done = false;
1180 for (int j = 3; j >= 0; --j) {
1181 if (q + j >= FnEnd)
1182 Done = true;
1183 else
1184 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1185 }
1186 if (Done)
1187 break;
1188 DOUT << ' ';
1189 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001190 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001191 }
1192 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001193 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001194 }
1195 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001196#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001197 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001198 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001199 SavedBufferBegin = BufferBegin;
1200 SavedBufferEnd = BufferEnd;
1201 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001202
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001203 if (MemMgr->NeedsExactSize()) {
1204 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001205 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001206
1207 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1208 ActualSize);
1209 BufferEnd = BufferBegin+ActualSize;
1210 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001211 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1212 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001213 BufferBegin = SavedBufferBegin;
1214 BufferEnd = SavedBufferEnd;
1215 CurBufferPtr = SavedCurBufferPtr;
1216
1217 TheJIT->RegisterTable(FrameRegister);
1218 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001219
1220 if (MMI)
1221 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001222
Chris Lattner43b429b2006-05-02 18:27:26 +00001223 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001224}
1225
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001226/// deallocateMemForFunction - Deallocate all memory for the specified
1227/// function body. Also drop any references the function has to stubs.
1228void JITEmitter::deallocateMemForFunction(Function *F) {
1229 MemMgr->deallocateMemForFunction(F);
1230
1231 // If the function did not reference any stubs, return.
1232 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1233 return;
1234
1235 // For each referenced stub, erase the reference to this function, and then
1236 // erase the list of referenced stubs.
1237 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1238 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1239 void *Stub = StubList[i];
Nate Begeman841c6a42009-03-11 07:03:43 +00001240
1241 // If we already invalidated this stub for this function, continue.
1242 if (StubFnRefs.count(Stub) == 0)
1243 continue;
1244
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001245 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1246 FnRefs.erase(F);
1247
1248 // If this function was the last reference to the stub, invalidate the stub
1249 // in the JITResolver. Were there a memory manager deallocateStub routine,
1250 // we could call that at this point too.
1251 if (FnRefs.empty()) {
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001252 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
Nate Begeman841c6a42009-03-11 07:03:43 +00001253 StubFnRefs.erase(Stub);
1254
1255 // Invalidate the stub. If it is a GV stub, update the JIT's global
1256 // mapping for that GV to zero, otherwise, search the string map of
1257 // external function names to stubs and remove the entry for this stub.
Nate Begemanb9c6c9b2009-03-07 06:41:19 +00001258 GlobalValue *GV = Resolver.invalidateStub(Stub);
Nate Begeman841c6a42009-03-11 07:03:43 +00001259 if (GV) {
1260 TheJIT->updateGlobalMapping(GV, 0);
1261 } else {
1262 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1263 e = ExtFnStubs.end(); i != e; ++i) {
1264 if (i->second == Stub) {
1265 ExtFnStubs.erase(i);
1266 break;
1267 }
1268 }
1269 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001270 }
1271 }
1272 CurFnStubUses.erase(F);
1273}
1274
1275
Evan Cheng5788d1a2008-12-10 02:32:19 +00001276void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001277 if (BufferBegin)
1278 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1279
1280 // create a new memory block if there is no active one.
1281 // care must be taken so that BufferBegin is invalidated when a
1282 // block is trimmed
1283 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1284 BufferEnd = BufferBegin+Size;
1285 return CurBufferPtr;
1286}
1287
Chris Lattner166f2262004-11-22 22:00:25 +00001288void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001289 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001290 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001291
Chris Lattnerfa77d432006-02-09 04:22:52 +00001292 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001293 if (Constants.empty()) return;
1294
Evan Cheng1606e8e2009-03-13 07:51:59 +00001295 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1296 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001297 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001298 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001299
1300 if (ConstantPoolBase == 0) return; // Buffer overflow.
1301
Evan Cheng97b8c402008-04-12 00:22:01 +00001302 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1303 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1304
Chris Lattner239862c2006-02-09 04:49:59 +00001305 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001306 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001307 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001308 MachineConstantPoolEntry CPE = Constants[i];
1309 unsigned AlignMask = CPE.getAlignment() - 1;
1310 Offset = (Offset + AlignMask) & ~AlignMask;
1311
1312 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1313 ConstPoolAddresses.push_back(CAddr);
1314 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001315 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001316 cerr << "Initialize memory with machine specific constant pool entry"
1317 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001318 abort();
1319 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001320 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1321 DOUT << "JIT: CP" << i << " at [0x"
1322 << std::hex << CAddr << std::dec << "]\n";
1323
1324 const Type *Ty = CPE.Val.ConstVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00001325 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001326 }
1327}
1328
Nate Begeman37efe672006-04-22 18:53:45 +00001329void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001330 if (TheJIT->getJITInfo().hasCustomJumpTables())
1331 return;
1332
Nate Begeman37efe672006-04-22 18:53:45 +00001333 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1334 if (JT.empty()) return;
1335
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001336 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001337 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001338 NumEntries += JT[i].MBBs.size();
1339
1340 unsigned EntrySize = MJTI->getEntrySize();
1341
Nate Begeman37efe672006-04-22 18:53:45 +00001342 // Just allocate space for all the jump tables now. We will fix up the actual
1343 // MBB entries in the tables after we emit the code for each block, since then
1344 // we will know the final locations of the MBBs in memory.
1345 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001346 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001347}
1348
Jim Laskeyb92767a2006-12-14 22:53:42 +00001349void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001350 if (TheJIT->getJITInfo().hasCustomJumpTables())
1351 return;
1352
Nate Begeman37efe672006-04-22 18:53:45 +00001353 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001354 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001355
Jim Laskeyb92767a2006-12-14 22:53:42 +00001356 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001357 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1358 // For each jump table, place the offset from the beginning of the table
1359 // to the target address.
1360 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001361
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001362 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1363 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1364 // Store the offset of the basic block for this jump table slot in the
1365 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001366 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001367 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001368 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001369 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1370 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001371 }
1372 } else {
1373 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1374
1375 // For each jump table, map each target in the jump table to the address of
1376 // an emitted MachineBasicBlock.
1377 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1378
1379 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1380 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1381 // Store the address of the basic block for this jump table slot in the
1382 // memory we allocated for the jump table in 'initJumpTableInfo'
1383 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1384 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1385 }
Nate Begeman37efe672006-04-22 18:53:45 +00001386 }
1387}
1388
Evan Chengce4a70b2008-11-08 08:02:53 +00001389void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1390 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001391 SavedBufferBegin = BufferBegin;
1392 SavedBufferEnd = BufferEnd;
1393 SavedCurBufferPtr = CurBufferPtr;
1394
Evan Chengce4a70b2008-11-08 08:02:53 +00001395 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001396 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001397}
1398
Nate Begemand6b7a242009-02-18 08:31:02 +00001399void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1400 unsigned StubSize) {
1401 SavedBufferBegin = BufferBegin;
1402 SavedBufferEnd = BufferEnd;
1403 SavedCurBufferPtr = CurBufferPtr;
1404
1405 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1406 BufferEnd = BufferBegin+StubSize+1;
1407}
1408
Evan Chengce4a70b2008-11-08 08:02:53 +00001409void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001410 NumBytes += getCurrentPCOffset();
1411 std::swap(SavedBufferBegin, BufferBegin);
1412 BufferEnd = SavedBufferEnd;
1413 CurBufferPtr = SavedCurBufferPtr;
1414 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001415}
1416
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001417// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1418// in the constant pool that was last emitted with the 'emitConstantPool'
1419// method.
1420//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001421uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001422 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001423 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001424 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001425}
1426
Nate Begeman37efe672006-04-22 18:53:45 +00001427// getJumpTableEntryAddress - Return the address of the JumpTable with index
1428// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1429//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001430uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001431 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1432 assert(Index < JT.size() && "Invalid jump table index!");
1433
1434 unsigned Offset = 0;
1435 unsigned EntrySize = JumpTable->getEntrySize();
1436
1437 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001438 Offset += JT[i].MBBs.size();
1439
1440 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001441
Evan Cheng5788d1a2008-12-10 02:32:19 +00001442 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001443}
1444
Chris Lattnere993cc22006-05-11 23:08:08 +00001445//===----------------------------------------------------------------------===//
1446// Public interface to this file
1447//===----------------------------------------------------------------------===//
1448
Chris Lattner9f2f1422007-12-06 01:08:09 +00001449MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1450 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001451}
1452
Misha Brukmand69c1e62003-07-28 19:09:06 +00001453// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001454// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001455// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1456// need to resolve function(s) that are being mis-codegenerated, so we need to
1457// resolve their addresses at runtime, and this is the way to do it.
1458extern "C" {
1459 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001460 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001461 return TheJIT->getPointerToFunction(F);
1462 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001463 }
1464}
Chris Lattnere993cc22006-05-11 23:08:08 +00001465
1466// getPointerToFunctionOrStub - If the specified function has been
1467// code-gen'd, return a pointer to the function. If not, compile it, or use
1468// a stub to implement lazy compilation if available.
1469//
1470void *JIT::getPointerToFunctionOrStub(Function *F) {
1471 // If we have already code generated the function, just return the address.
1472 if (void *Addr = getPointerToGlobalIfAvailable(F))
1473 return Addr;
1474
Chris Lattnere7484012007-02-24 02:57:03 +00001475 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001476 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1477 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001478 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001479}
1480
Nate Begemand6b7a242009-02-18 08:31:02 +00001481void JIT::updateFunctionStub(Function *F) {
1482 // Get the empty stub we generated earlier.
1483 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1484 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1485 void *Stub = JE->getJITResolver().getFunctionStub(F);
1486
1487 // Tell the target jit info to rewrite the stub at the specified address,
1488 // rather than creating a new one.
1489 void *Addr = getPointerToGlobalIfAvailable(F);
1490 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1491}
1492
1493/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1494/// that were emitted during code generation.
1495///
1496void JIT::updateDlsymStubTable() {
1497 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1498 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1499
1500 SmallVector<GlobalValue*, 8> GVs;
1501 SmallVector<void*, 8> Ptrs;
Nate Begeman841c6a42009-03-11 07:03:43 +00001502 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
Nate Begemand6b7a242009-02-18 08:31:02 +00001503
1504 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1505
Nate Begeman841c6a42009-03-11 07:03:43 +00001506 unsigned nStubs = GVs.size() + ExtFns.size();
1507
Nate Begemand6b7a242009-02-18 08:31:02 +00001508 // If there are no relocatable stubs, return.
Nate Begeman841c6a42009-03-11 07:03:43 +00001509 if (nStubs == 0)
Nate Begemand6b7a242009-02-18 08:31:02 +00001510 return;
1511
1512 // If there are no new relocatable stubs, return.
1513 void *CurTable = JE->getMemMgr()->getDlsymTable();
Nate Begeman841c6a42009-03-11 07:03:43 +00001514 if (CurTable && (*(unsigned *)CurTable == nStubs))
Nate Begemand6b7a242009-02-18 08:31:02 +00001515 return;
1516
1517 // Calculate the size of the stub info
Nate Begeman841c6a42009-03-11 07:03:43 +00001518 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
Nate Begemand6b7a242009-02-18 08:31:02 +00001519
1520 SmallVector<unsigned, 8> Offsets;
1521 for (unsigned i = 0; i != GVs.size(); ++i) {
1522 Offsets.push_back(offset);
1523 offset += GVs[i]->getName().length() + 1;
1524 }
Nate Begeman841c6a42009-03-11 07:03:43 +00001525 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1526 i != e; ++i) {
1527 Offsets.push_back(offset);
1528 offset += strlen(i->first()) + 1;
1529 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001530
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001531 // Allocate space for the new "stub", which contains the dlsym table.
Nate Begemand6b7a242009-02-18 08:31:02 +00001532 JE->startGVStub(0, offset, 4);
1533
1534 // Emit the number of records
Nate Begeman841c6a42009-03-11 07:03:43 +00001535 MCE->emitInt32(nStubs);
Nate Begemand6b7a242009-02-18 08:31:02 +00001536
1537 // Emit the string offsets
Nate Begeman841c6a42009-03-11 07:03:43 +00001538 for (unsigned i = 0; i != nStubs; ++i)
Nate Begemand6b7a242009-02-18 08:31:02 +00001539 MCE->emitInt32(Offsets[i]);
1540
Nate Begeman66941982009-03-04 19:10:38 +00001541 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1542 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1543 // relocation can write the relocated pointer at the appropriate place in
1544 // the stub.
1545 for (unsigned i = 0; i != GVs.size(); ++i) {
1546 intptr_t Ptr = (intptr_t)Ptrs[i];
1547 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1548
1549 if (isa<Function>(GVs[i]))
1550 Ptr |= (intptr_t)1;
1551
Nate Begeman841c6a42009-03-11 07:03:43 +00001552 if (sizeof(Ptr) == 8)
1553 MCE->emitInt64(Ptr);
1554 else
1555 MCE->emitInt32(Ptr);
1556 }
1557 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1558 i != e; ++i) {
1559 intptr_t Ptr = (intptr_t)i->second | 1;
1560
1561 if (sizeof(Ptr) == 8)
Nate Begeman66941982009-03-04 19:10:38 +00001562 MCE->emitInt64(Ptr);
Nate Begemand6b7a242009-02-18 08:31:02 +00001563 else
Nate Begeman66941982009-03-04 19:10:38 +00001564 MCE->emitInt32(Ptr);
1565 }
Nate Begemand6b7a242009-02-18 08:31:02 +00001566
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001567 // Emit the strings.
Nate Begemand6b7a242009-02-18 08:31:02 +00001568 for (unsigned i = 0; i != GVs.size(); ++i)
1569 MCE->emitString(GVs[i]->getName());
Nate Begeman841c6a42009-03-11 07:03:43 +00001570 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1571 i != e; ++i)
1572 MCE->emitString(i->first());
Nate Begemand6b7a242009-02-18 08:31:02 +00001573
Nate Begeman50cd6fd2009-03-05 06:34:37 +00001574 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1575 // deallocate space for the old one, if one existed.
Nate Begemand6b7a242009-02-18 08:31:02 +00001576 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1577}
1578
Chris Lattnere993cc22006-05-11 23:08:08 +00001579/// freeMachineCodeForFunction - release machine code memory for given Function.
1580///
1581void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001582
Chris Lattnere993cc22006-05-11 23:08:08 +00001583 // Delete translation for this from the ExecutionEngine, so it will get
1584 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001585 void *OldPtr = updateGlobalMapping(F, 0);
1586
1587 if (OldPtr)
1588 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001589
1590 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001591 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1592 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001593}
1594