blob: 1fbeba923c3583efb94b16882f59df182398b5af [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"
Anton Korobeynikovfd58e6e2007-01-23 10:26:08 +000035#include "llvm/System/Disassembler.h"
Chris Lattnerbc52cad2008-06-25 17:18:44 +000036#include "llvm/System/Memory.h"
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +000037#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000038#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000039#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000041#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000042#ifndef NDEBUG
43#include <iomanip>
44#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner36343732006-12-19 22:43:32 +000047STATISTIC(NumBytes, "Number of bytes of machine code compiled");
48STATISTIC(NumRelos, "Number of relocations applied");
49static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000050
Andrew Lenhartha00269b2005-07-29 23:40:16 +000051
Chris Lattner54266522004-11-20 23:57:07 +000052//===----------------------------------------------------------------------===//
53// JIT lazy compilation code.
54//
55namespace {
Reid Spenceree448632005-07-12 15:51:55 +000056 class JITResolverState {
57 private:
58 /// FunctionToStubMap - Keep track of the stub created for a particular
59 /// function so that we can reuse them if necessary.
60 std::map<Function*, void*> FunctionToStubMap;
61
62 /// StubToFunctionMap - Keep track of the function that each stub
63 /// corresponds to.
64 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000065
Evan Cheng5594f122008-11-10 01:52:24 +000066 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000067 /// particular GlobalVariable so that we can reuse them if necessary.
Evan Cheng5594f122008-11-10 01:52:24 +000068 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000069
Reid Spenceree448632005-07-12 15:51:55 +000070 public:
71 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return FunctionToStubMap;
74 }
Jeff Cohen00b168892005-07-27 06:12:32 +000075
Reid Spenceree448632005-07-12 15:51:55 +000076 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return StubToFunctionMap;
79 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000080
81 std::map<GlobalValue*, void*>&
Evan Cheng5594f122008-11-10 01:52:24 +000082 getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000083 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000084 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000085 }
Reid Spenceree448632005-07-12 15:51:55 +000086 };
Jeff Cohen00b168892005-07-27 06:12:32 +000087
Chris Lattner54266522004-11-20 23:57:07 +000088 /// JITResolver - Keep track of, and resolve, call sites for functions that
89 /// have not yet been compiled.
90 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000091 /// LazyResolverFn - The target lazy resolver function that we actually
92 /// rewrite instructions to use.
93 TargetJITInfo::LazyResolverFn LazyResolverFn;
94
Reid Spenceree448632005-07-12 15:51:55 +000095 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000096
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000097 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
98 /// external functions.
99 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000100
101 //map addresses to indexes in the GOT
102 std::map<void*, unsigned> revGOTMap;
103 unsigned nextGOTIndex;
104
Chris Lattnere7484012007-02-24 02:57:03 +0000105 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000106 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000107 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000108 TheJIT = &jit;
109
110 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
111 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
112 TheJITResolver = this;
113 }
114
115 ~JITResolver() {
116 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000117 }
Chris Lattner54266522004-11-20 23:57:07 +0000118
Evan Cheng704bff92008-11-13 21:50:50 +0000119 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
120 /// if it has already been created.
121 void *getFunctionStubIfAvailable(Function *F);
122
Chris Lattner54266522004-11-20 23:57:07 +0000123 /// getFunctionStub - This returns a pointer to a function stub, creating
Nate Begemand6b7a242009-02-18 08:31:02 +0000124 /// one on demand as needed. If empty is true, create a function stub
125 /// pointing at address 0, to be filled in later.
126 void *getFunctionStub(Function *F, bool empty = false);
Chris Lattner54266522004-11-20 23:57:07 +0000127
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000128 /// getExternalFunctionStub - Return a stub for the function at the
129 /// specified address, created lazily on demand.
130 void *getExternalFunctionStub(void *FnAddr);
131
Evan Cheng5594f122008-11-10 01:52:24 +0000132 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000133 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000134 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000135
Chris Lattner5e225582004-11-21 03:37:42 +0000136 /// AddCallbackAtLocation - If the target is capable of rewriting an
137 /// instruction without the use of a stub, record the location of the use so
138 /// we know which function is being used at the location.
139 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000140 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000141 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000142 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000143 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000144 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000145
146 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
147 SmallVectorImpl<void*> &Ptrs);
Chris Lattner5e225582004-11-21 03:37:42 +0000148
Andrew Lenharth6a974612005-07-28 12:44:13 +0000149 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000150 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000151 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000152 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000153
Chris Lattner54266522004-11-20 23:57:07 +0000154 /// JITCompilerFn - This function is called to resolve a stub to a compiled
155 /// address. If the LLVM Function corresponding to the stub has not yet
156 /// been compiled, this function compiles it first.
157 static void *JITCompilerFn(void *Stub);
158 };
159}
160
Chris Lattnere7484012007-02-24 02:57:03 +0000161JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000162
Evan Cheng704bff92008-11-13 21:50:50 +0000163/// getFunctionStubIfAvailable - This returns a pointer to a function stub
164/// if it has already been created.
165void *JITResolver::getFunctionStubIfAvailable(Function *F) {
166 MutexGuard locked(TheJIT->lock);
167
168 // If we already have a stub for this function, recycle it.
169 void *&Stub = state.getFunctionToStubMap(locked)[F];
170 return Stub;
171}
172
Chris Lattner54266522004-11-20 23:57:07 +0000173/// getFunctionStub - This returns a pointer to a function stub, creating
174/// one on demand as needed.
Nate Begemand6b7a242009-02-18 08:31:02 +0000175void *JITResolver::getFunctionStub(Function *F, bool empty) {
Reid Spenceree448632005-07-12 15:51:55 +0000176 MutexGuard locked(TheJIT->lock);
177
Chris Lattner54266522004-11-20 23:57:07 +0000178 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000179 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000180 if (Stub) return Stub;
181
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000182 // Call the lazy resolver function unless we already KNOW it is an external
183 // function, in which case we just skip the lazy resolution step.
Nate Begemand6b7a242009-02-18 08:31:02 +0000184 void *Actual = empty ? (void*)0 : (void*)(intptr_t)LazyResolverFn;
Dan Gohman69f93782009-01-05 05:32:42 +0000185 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000186 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000187
Dan Gohman69f93782009-01-05 05:32:42 +0000188 // If we resolved the symbol to a null address (eg. a weak external)
189 // don't emit a stub. Return a null pointer to the application.
190 if (!Actual) return 0;
191 }
192
Chris Lattner54266522004-11-20 23:57:07 +0000193 // Otherwise, codegen a new stub. For now, the stub will call the lazy
194 // resolver function.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000195 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000196 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000197
Chris Lattner870286a2006-06-01 17:29:22 +0000198 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000199 // If we are getting the stub for an external function, we really want the
200 // address of the stub in the GlobalAddressMap for the JIT, not the address
201 // of the external function.
202 TheJIT->updateGlobalMapping(F, Stub);
203 }
Chris Lattner54266522004-11-20 23:57:07 +0000204
Bill Wendling832171c2006-12-07 20:04:42 +0000205 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
206 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000207
Chris Lattner54266522004-11-20 23:57:07 +0000208 // Finally, keep track of the stub-to-Function mapping so that the
209 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000210 state.getStubToFunctionMap(locked)[Stub] = F;
Nate Begemand6b7a242009-02-18 08:31:02 +0000211
212 // If this is an "empty" stub, then inform the JIT that it will need to
213 // JIT the function so an address can be provided.
214 if (empty)
215 TheJIT->addPendingFunction(F);
216
Chris Lattner54266522004-11-20 23:57:07 +0000217 return Stub;
218}
219
Evan Cheng5594f122008-11-10 01:52:24 +0000220/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000221/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000222void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000223 MutexGuard locked(TheJIT->lock);
224
225 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000226 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
227 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000228
Evan Chenge4d783d2008-11-10 23:26:16 +0000229 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000230 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000231 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000232
Evan Cheng5594f122008-11-10 01:52:24 +0000233 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000234 << GV->getName() << "'\n";
235
Evan Cheng5594f122008-11-10 01:52:24 +0000236 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000237}
238
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000239/// getExternalFunctionStub - Return a stub for the function at the
240/// specified address, created lazily on demand.
241void *JITResolver::getExternalFunctionStub(void *FnAddr) {
242 // If we already have a stub for this function, recycle it.
243 void *&Stub = ExternalFnToStubMap[FnAddr];
244 if (Stub) return Stub;
245
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000246 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000247 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000248
Bill Wendling832171c2006-12-07 20:04:42 +0000249 DOUT << "JIT: Stub emitted at [" << Stub
250 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000251 return Stub;
252}
253
Andrew Lenharth6a974612005-07-28 12:44:13 +0000254unsigned JITResolver::getGOTIndexForAddr(void* addr) {
255 unsigned idx = revGOTMap[addr];
256 if (!idx) {
257 idx = ++nextGOTIndex;
258 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000259 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000260 }
261 return idx;
262}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000263
Nate Begemand6b7a242009-02-18 08:31:02 +0000264void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
265 SmallVectorImpl<void*> &Ptrs) {
266 MutexGuard locked(TheJIT->lock);
267
268 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
269 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
270
271 for (std::map<Function*,void*>::iterator i = FM.begin(), e = FM.end();
272 i != e; ++i) {
273 Function *F = i->first;
274 if (F->isDeclaration() && F->hasExternalLinkage()) {
275 GVs.push_back(i->first);
276 Ptrs.push_back(i->second);
277 }
278 }
279 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
280 i != e; ++i) {
281 GVs.push_back(i->first);
282 Ptrs.push_back(i->second);
283 }
284}
285
Chris Lattner54266522004-11-20 23:57:07 +0000286/// JITCompilerFn - This function is called when a lazy compilation stub has
287/// been entered. It looks up which function this stub corresponds to, compiles
288/// it if necessary, then returns the resultant function pointer.
289void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000290 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000291
292 Function* F = 0;
293 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000294
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000295 {
296 // Only lock for getting the Function. The call getPointerToFunction made
297 // in this function might trigger function materializing, which requires
298 // JIT lock to be unlocked.
299 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000300
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000301 // The address given to us for the stub may not be exactly right, it might be
302 // a little bit after the stub. As such, use upper_bound to find it.
303 std::map<void*, Function*>::iterator I =
304 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
305 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
306 "This is not a known stub!");
307 F = (--I)->second;
308 ActualPtr = I->first;
309 }
Chris Lattner54266522004-11-20 23:57:07 +0000310
Evan Cheng9da60f92007-06-30 00:10:37 +0000311 // If we have already code generated the function, just return the address.
312 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000313
Evan Cheng9da60f92007-06-30 00:10:37 +0000314 if (!Result) {
315 // Otherwise we don't have it, do lazy compilation now.
316
317 // If lazy compilation is disabled, emit a useful error message and abort.
318 if (TheJIT->isLazyCompilationDisabled()) {
319 cerr << "LLVM JIT requested to do lazy compilation of function '"
320 << F->getName() << "' when lazy compiles are disabled!\n";
321 abort();
322 }
323
324 // We might like to remove the stub from the StubToFunction map.
325 // We can't do that! Multiple threads could be stuck, waiting to acquire the
326 // lock above. As soon as the 1st function finishes compiling the function,
327 // the next one will be released, and needs to be able to find the function
328 // it needs to call.
329 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000330
Evan Cheng9da60f92007-06-30 00:10:37 +0000331 DOUT << "JIT: Lazily resolving function '" << F->getName()
332 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000333 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000334
Evan Cheng9da60f92007-06-30 00:10:37 +0000335 Result = TheJIT->getPointerToFunction(F);
336 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000337
338 // Reacquire the lock to erase the stub in the map.
339 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000340
341 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000342 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000343
344 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000345
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000346 // What we will do is set the compiled function address to map to the
347 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000348 // if they see it still using the stub address.
349 // Note: this is done so the Resolver doesn't have to manage GOT memory
350 // Do this without allocating map space if the target isn't using a GOT
351 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
352 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
353
Chris Lattner54266522004-11-20 23:57:07 +0000354 return Result;
355}
Chris Lattner688506d2003-08-14 18:35:27 +0000356
Chris Lattner8ac66c12008-04-04 05:51:42 +0000357//===----------------------------------------------------------------------===//
358// Function Index Support
359
360// On MacOS we generate an index of currently JIT'd functions so that
361// performance tools can determine a symbol name and accurate code range for a
362// PC value. Because performance tools are generally asynchronous, the code
363// below is written with the hope that it could be interrupted at any time and
364// have useful answers. However, we don't go crazy with atomic operations, we
365// just do a "reasonable effort".
366#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000367#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000368#endif
369
370/// JitSymbolEntry - Each function that is JIT compiled results in one of these
371/// being added to an array of symbols. This indicates the name of the function
372/// as well as the address range it occupies. This allows the client to map
373/// from a PC value to the name of the function.
374struct JitSymbolEntry {
375 const char *FnName; // FnName - a strdup'd string.
376 void *FnStart;
377 intptr_t FnSize;
378};
379
380
381struct JitSymbolTable {
382 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
383 /// pointer is not used right now, but might be used in the future. Consider
384 /// it reserved for future use.
385 JitSymbolTable *NextPtr;
386
387 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
388 /// 'NumSymbols' symbols are valid.
389 JitSymbolEntry *Symbols;
390
391 /// NumSymbols - This indicates the number entries in the Symbols array that
392 /// are valid.
393 unsigned NumSymbols;
394
395 /// NumAllocated - This indicates the amount of space we have in the Symbols
396 /// array. This is a private field that should not be read by external tools.
397 unsigned NumAllocated;
398};
399
400#if ENABLE_JIT_SYMBOL_TABLE
401JitSymbolTable *__jitSymbolTable;
402#endif
403
404static void AddFunctionToSymbolTable(const char *FnName,
405 void *FnStart, intptr_t FnSize) {
406 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
407 JitSymbolTable **SymTabPtrPtr = 0;
408#if !ENABLE_JIT_SYMBOL_TABLE
409 return;
410#else
411 SymTabPtrPtr = &__jitSymbolTable;
412#endif
413
414 // If this is the first entry in the symbol table, add the JitSymbolTable
415 // index.
416 if (*SymTabPtrPtr == 0) {
417 JitSymbolTable *New = new JitSymbolTable();
418 New->NextPtr = 0;
419 New->Symbols = 0;
420 New->NumSymbols = 0;
421 New->NumAllocated = 0;
422 *SymTabPtrPtr = New;
423 }
424
425 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
426
427 // If we have space in the table, reallocate the table.
428 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
429 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000430 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000431 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
432 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
433
434 // Copy the old entries over.
Nate Begemand6b7a242009-02-18 08:31:02 +0000435 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000436
437 // Swap the new symbols in, delete the old ones.
438 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000439 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000440 delete [] OldSymbols;
441 }
442
443 // Otherwise, we have enough space, just tack it onto the end of the array.
444 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
445 Entry.FnName = strdup(FnName);
446 Entry.FnStart = FnStart;
447 Entry.FnSize = FnSize;
448 ++SymTabPtr->NumSymbols;
449}
450
451static void RemoveFunctionFromSymbolTable(void *FnStart) {
452 assert(FnStart && "Invalid function pointer");
453 JitSymbolTable **SymTabPtrPtr = 0;
454#if !ENABLE_JIT_SYMBOL_TABLE
455 return;
456#else
457 SymTabPtrPtr = &__jitSymbolTable;
458#endif
459
460 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
461 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
462
463 // Scan the table to find its index. The table is not sorted, so do a linear
464 // scan.
465 unsigned Index;
466 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
467 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
468
469 // Once we have an index, we know to nuke this entry, overwrite it with the
470 // entry at the end of the array, making the last entry redundant.
471 const char *OldName = Symbols[Index].FnName;
472 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
473 free((void*)OldName);
474
475 // Drop the number of symbols in the table.
476 --SymTabPtr->NumSymbols;
477
478 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000479 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000480 return;
481
482 *SymTabPtrPtr = 0;
483 delete [] Symbols;
484 delete SymTabPtr;
485}
Chris Lattner688506d2003-08-14 18:35:27 +0000486
Chris Lattner54266522004-11-20 23:57:07 +0000487//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000488// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000489//
Chris Lattner688506d2003-08-14 18:35:27 +0000490namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000491 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
492 /// used to output functions to memory for execution.
493 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000494 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000495
Chris Lattner6125fdd2003-05-09 03:30:07 +0000496 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000497 // save BufferBegin/BufferEnd/CurBufferPtr here.
498 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000499
Chris Lattner5be478f2004-11-20 03:46:14 +0000500 /// Relocations - These are the relocations that the function needs, as
501 /// emitted.
502 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000503
504 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
505 /// It is filled in by the StartMachineBasicBlock callback and queried by
506 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000507 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000508
Chris Lattner239862c2006-02-09 04:49:59 +0000509 /// ConstantPool - The constant pool for the current function.
510 ///
511 MachineConstantPool *ConstantPool;
512
513 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
514 ///
515 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000516
Nate Begeman019f8512006-09-10 23:03:44 +0000517 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000518 ///
519 MachineJumpTableInfo *JumpTable;
520
521 /// JumpTableBase - A pointer to the first entry in the jump table.
522 ///
523 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000524
Chris Lattnere7484012007-02-24 02:57:03 +0000525 /// Resolver - This contains info about the currently resolved functions.
526 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000527
528 /// DE - The dwarf emitter for the jit.
529 JITDwarfEmitter *DE;
530
531 /// LabelLocations - This vector is a mapping from Label ID's to their
532 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000533 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000534
535 /// MMI - Machine module info for exception informations
536 MachineModuleInfo* MMI;
537
Dale Johannesendd947ea2008-08-07 01:30:15 +0000538 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000539 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000540
Chris Lattnere7484012007-02-24 02:57:03 +0000541 public:
Chris Lattner9f2f1422007-12-06 01:08:09 +0000542 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
543 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000544 if (jit.getJITInfo().needsGOT()) {
545 MemMgr->AllocateGOT();
546 DOUT << "JIT is managing a GOT\n";
547 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000548
549 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000550 }
551 ~JITEmitter() {
552 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000553 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000554 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000555
556 /// classof - Methods for support type inquiry through isa, cast, and
557 /// dyn_cast:
558 ///
559 static inline bool classof(const JITEmitter*) { return true; }
560 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000561
562 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000563
564 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000565 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000566
567 void emitConstantPool(MachineConstantPool *MCP);
568 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000569 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000570
Evan Chengce4a70b2008-11-08 08:02:53 +0000571 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000572 unsigned Alignment = 1);
Nate Begemand6b7a242009-02-18 08:31:02 +0000573 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
574 unsigned StubSize);
Evan Chengce4a70b2008-11-08 08:02:53 +0000575 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000576
Nuno Lopescef75272008-10-21 11:42:16 +0000577 /// allocateSpace - Reserves space in the current block if any, or
578 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000579 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000580
Chris Lattner5be478f2004-11-20 03:46:14 +0000581 virtual void addRelocation(const MachineRelocation &MR) {
582 Relocations.push_back(MR);
583 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000584
585 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
586 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
587 MBBLocations.resize((MBB->getNumber()+1)*2);
588 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000589 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
590 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000591 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000592
Evan Cheng5788d1a2008-12-10 02:32:19 +0000593 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
594 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000595
Evan Cheng5788d1a2008-12-10 02:32:19 +0000596 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000597 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
598 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
599 return MBBLocations[MBB->getNumber()];
600 }
601
Chris Lattnere993cc22006-05-11 23:08:08 +0000602 /// deallocateMemForFunction - Deallocate all memory for the specified
603 /// function body.
604 void deallocateMemForFunction(Function *F) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000605 MemMgr->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000606 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000607
608 virtual void emitLabel(uint64_t LabelID) {
609 if (LabelLocations.size() <= LabelID)
610 LabelLocations.resize((LabelID+1)*2);
611 LabelLocations[LabelID] = getCurrentPCValue();
612 }
613
Evan Cheng5788d1a2008-12-10 02:32:19 +0000614 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000615 assert(LabelLocations.size() > (unsigned)LabelID &&
616 LabelLocations[LabelID] && "Label not emitted!");
617 return LabelLocations[LabelID];
618 }
619
620 virtual void setModuleInfo(MachineModuleInfo* Info) {
621 MMI = Info;
622 if (ExceptionHandling) DE->setModuleInfo(Info);
623 }
624
Jim Grosbachcce6c292008-10-03 16:17:20 +0000625 void setMemoryExecutable(void) {
626 MemMgr->setMemoryExecutable();
627 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000628
629 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000630
Chris Lattner54266522004-11-20 23:57:07 +0000631 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000632 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000633 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000634 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000635 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
636 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
637 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
638 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000639 };
640}
641
Chris Lattner166f2262004-11-22 22:00:25 +0000642void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
643 bool DoesntNeedStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000644 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000645 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000646
Chris Lattner18e04592008-06-25 20:21:35 +0000647 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000648 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000649
650 // If we have already compiled the function, return a pointer to its body.
651 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000652 void *ResultPtr;
Evan Cheng369e02d2008-12-10 01:33:59 +0000653 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Evan Cheng704bff92008-11-13 21:50:50 +0000654 // Return the function stub if it's already created.
655 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
656 else
657 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner54266522004-11-20 23:57:07 +0000658 if (ResultPtr) return ResultPtr;
659
Nate Begemand6b7a242009-02-18 08:31:02 +0000660 // If this is an external function pointer, we can force the JIT to
661 // 'compile' it, which really just adds it to the map.
662 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() && DoesntNeedStub)
663 return TheJIT->getPointerToFunction(F);
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000664
Nate Begemand6b7a242009-02-18 08:31:02 +0000665 // If we are jitting non-lazily but encounter a function that has not been
666 // jitted yet, we need to allocate a blank stub to call the function
667 // once we JIT it and its address is known.
668 if (TheJIT->isLazyCompilationDisabled())
669 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
670 return Resolver.getFunctionStub(F, true);
671
Chris Lattner5e225582004-11-21 03:37:42 +0000672 // Okay, the function has not been compiled yet, if the target callback
673 // mechanism is capable of rewriting the instruction directly, prefer to do
674 // that instead of emitting a stub.
675 if (DoesntNeedStub)
Chris Lattnere7484012007-02-24 02:57:03 +0000676 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000677
Chris Lattner54266522004-11-20 23:57:07 +0000678 // Otherwise, we have to emit a lazy resolving stub.
Chris Lattnere7484012007-02-24 02:57:03 +0000679 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000680}
681
Evan Cheng5594f122008-11-10 01:52:24 +0000682void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000683 bool NoNeedStub) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000684 // Make sure GV is emitted first.
685 // FIXME: For now, if the GV is an external function we force the JIT to
Evan Cheng5594f122008-11-10 01:52:24 +0000686 // compile it so the indirect symbol will contain the fully resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000687 void *GVAddress = getPointerToGlobal(V, Reference, true);
Evan Cheng5594f122008-11-10 01:52:24 +0000688 return Resolver.getGlobalValueIndirectSym(V, GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000689}
690
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000691static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
692 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
693 if (Constants.empty()) return 0;
694
695 MachineConstantPoolEntry CPE = Constants.back();
696 unsigned Size = CPE.Offset;
697 const Type *Ty = CPE.isMachineConstantPoolEntry()
698 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000699 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000700 return Size;
701}
702
703static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
704 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
705 if (JT.empty()) return 0;
706
707 unsigned NumEntries = 0;
708 for (unsigned i = 0, e = JT.size(); i != e; ++i)
709 NumEntries += JT[i].MBBs.size();
710
711 unsigned EntrySize = MJTI->getEntrySize();
712
713 return NumEntries * EntrySize;
714}
715
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000716static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000717 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000718 // Since we do not know where the buffer will be allocated, be pessimistic.
719 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000720}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000721
Dale Johannesendd947ea2008-08-07 01:30:15 +0000722/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
723/// into the running total Size.
724
725unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
726 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000727 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000728 size_t GVAlign =
729 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000730 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000731 DEBUG(GV->dump());
732 // Assume code section ends with worst possible alignment, so first
733 // variable needs maximal padding.
734 if (Size==0)
735 Size = 1;
736 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
737 Size += GVSize;
738 return Size;
739}
740
741/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
742/// but are referenced from the constant; put them in GVSet and add their
743/// size into the running total Size.
744
745unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
746 unsigned Size) {
747 // If its undefined, return the garbage.
748 if (isa<UndefValue>(C))
749 return Size;
750
751 // If the value is a ConstantExpr
752 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
753 Constant *Op0 = CE->getOperand(0);
754 switch (CE->getOpcode()) {
755 case Instruction::GetElementPtr:
756 case Instruction::Trunc:
757 case Instruction::ZExt:
758 case Instruction::SExt:
759 case Instruction::FPTrunc:
760 case Instruction::FPExt:
761 case Instruction::UIToFP:
762 case Instruction::SIToFP:
763 case Instruction::FPToUI:
764 case Instruction::FPToSI:
765 case Instruction::PtrToInt:
766 case Instruction::IntToPtr:
767 case Instruction::BitCast: {
768 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
769 break;
770 }
771 case Instruction::Add:
772 case Instruction::Sub:
773 case Instruction::Mul:
774 case Instruction::UDiv:
775 case Instruction::SDiv:
776 case Instruction::URem:
777 case Instruction::SRem:
778 case Instruction::And:
779 case Instruction::Or:
780 case Instruction::Xor: {
781 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
782 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
783 break;
784 }
785 default: {
786 cerr << "ConstantExpr not handled: " << *CE << "\n";
787 abort();
788 }
789 }
790 }
791
792 if (C->getType()->getTypeID() == Type::PointerTyID)
793 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000794 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000795 Size = addSizeOfGlobal(GV, Size);
796
797 return Size;
798}
799
800/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
801/// but are referenced from the given initializer.
802
803unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
804 unsigned Size) {
805 if (!isa<UndefValue>(Init) &&
806 !isa<ConstantVector>(Init) &&
807 !isa<ConstantAggregateZero>(Init) &&
808 !isa<ConstantArray>(Init) &&
809 !isa<ConstantStruct>(Init) &&
810 Init->getType()->isFirstClassType())
811 Size = addSizeOfGlobalsInConstantVal(Init, Size);
812 return Size;
813}
814
815/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
816/// globals; then walk the initializers of those globals looking for more.
817/// If their size has not been considered yet, add it into the running total
818/// Size.
819
820unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
821 unsigned Size = 0;
822 GVSet.clear();
823
824 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
825 MBB != E; ++MBB) {
826 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
827 I != E; ++I) {
828 const TargetInstrDesc &Desc = I->getDesc();
829 const MachineInstr &MI = *I;
830 unsigned NumOps = Desc.getNumOperands();
831 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
832 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000833 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000834 GlobalValue* V = MO.getGlobal();
835 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
836 if (!GV)
837 continue;
838 // If seen in previous function, it will have an entry here.
839 if (TheJIT->getPointerToGlobalIfAvailable(GV))
840 continue;
841 // If seen earlier in this function, it will have an entry here.
842 // FIXME: it should be possible to combine these tables, by
843 // assuming the addresses of the new globals in this module
844 // start at 0 (or something) and adjusting them after codegen
845 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000846 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000847 // A variable as yet unseen. Add in its size.
848 Size = addSizeOfGlobal(GV, Size);
849 }
850 }
851 }
852 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000853 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000854 // Look for more globals that are referenced only from initializers.
855 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000856 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000857 I != GVSet.end(); I++) {
858 const GlobalVariable* GV = *I;
859 if (GV->hasInitializer())
860 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
861 }
862
863 return Size;
864}
865
Chris Lattner166f2262004-11-22 22:00:25 +0000866void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000867 DOUT << "JIT: Starting CodeGen of Function "
868 << F.getFunction()->getName() << "\n";
869
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000870 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000871 // Set the memory writable, if it's not already
872 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000873 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000874 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000875 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
876 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
877 MachineConstantPool *MCP = F.getConstantPool();
878
879 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000880 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000881
882 // Add the alignment of the constant pool
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000883 ActualSize = RoundUpToAlign(ActualSize,
884 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000885
886 // Add the constant pool size
887 ActualSize += GetConstantPoolSizeInBytes(MCP);
888
889 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000890 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000891
892 // Add the jump table size
893 ActualSize += GetJumpTableSizeInBytes(MJTI);
894
895 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000896 ActualSize = RoundUpToAlign(ActualSize,
897 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000898
899 // Add the function size
900 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000901
Evan Chengeb5d95a2008-11-06 17:46:04 +0000902 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000903 // Add the size of the globals that will be allocated after this function.
904 // These are all the ones referenced from this function that were not
905 // previously allocated.
906 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000907 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000908 }
909
Chris Lattner8907b4b2007-12-05 23:39:57 +0000910 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
911 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000912 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000913
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000914 // Ensure the constant pool/jump table info is at least 4-byte aligned.
915 emitAlignment(16);
916
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000917 emitConstantPool(F.getConstantPool());
918 initJumpTableInfo(F.getJumpTableInfo());
919
920 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000921 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000922 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000923
Chris Lattnerb4432f32006-05-03 17:10:41 +0000924 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000925}
926
Chris Lattner43b429b2006-05-02 18:27:26 +0000927bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000928 if (CurBufferPtr == BufferEnd) {
929 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000930 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000931 abort();
932 }
933
Jim Laskeyb92767a2006-12-14 22:53:42 +0000934 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000935
Chris Lattnera8279532006-06-16 18:09:26 +0000936 // FnStart is the start of the text, not the start of the constant pool and
937 // other per-function data.
938 unsigned char *FnStart =
939 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000940
Chris Lattner5be478f2004-11-20 03:46:14 +0000941 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000942 NumRelos += Relocations.size();
943
Chris Lattner5be478f2004-11-20 03:46:14 +0000944 // Resolve the relocations to concrete pointers.
945 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
946 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +0000947 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +0000948 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +0000949 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +0000950 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
951 false);
Evan Chengd7398c92008-11-08 07:37:34 +0000952 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +0000953 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +0000954
Evan Chengef5784e2008-10-29 23:54:46 +0000955 // If the target REALLY wants a stub for this function, emit it now.
956 if (!MR.doesntNeedStub())
957 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
958 } else if (MR.isGlobalValue()) {
959 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
960 BufferBegin+MR.getMachineCodeOffset(),
961 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +0000962 } else if (MR.isIndirectSymbol()) {
963 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +0000964 BufferBegin+MR.getMachineCodeOffset(),
965 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +0000966 } else if (MR.isBasicBlock()) {
967 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
968 } else if (MR.isConstantPoolIndex()) {
969 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
970 } else {
971 assert(MR.isJumpTableIndex());
972 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
973 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000974
Evan Chengef5784e2008-10-29 23:54:46 +0000975 MR.setResultPointer(ResultPtr);
976 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000977
Andrew Lenharth6a974612005-07-28 12:44:13 +0000978 // if we are managing the GOT and the relocation wants an index,
979 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000980 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000981 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000982 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000983 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000984 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000985 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000986 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000987 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000988 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000989 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000990 }
991
Chris Lattner43b429b2006-05-02 18:27:26 +0000992 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000993 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000994 }
995
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000996 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000997 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000998 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000999 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +00001000 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +00001001 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1002 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +00001003 }
1004 }
1005
Nuno Lopescef75272008-10-21 11:42:16 +00001006 unsigned char *FnEnd = CurBufferPtr;
1007
1008 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Evan Cheng5788d1a2008-12-10 02:32:19 +00001009
1010 if (CurBufferPtr == BufferEnd) {
1011 // FIXME: Allocate more space, then try again.
1012 cerr << "JIT: Ran out of space for generated machine code!\n";
1013 abort();
1014 }
1015
Nuno Lopescef75272008-10-21 11:42:16 +00001016 BufferBegin = CurBufferPtr = 0;
1017 NumBytes += FnEnd-FnStart;
1018
Evan Cheng55fc2802006-07-25 20:40:54 +00001019 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +00001020 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +00001021
1022 // Add it to the JIT symbol table if the host wants it.
1023 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1024 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +00001025
Bill Wendling832171c2006-12-07 20:04:42 +00001026 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1027 << "] Function: " << F.getFunction()->getName()
1028 << ": " << (FnEnd-FnStart) << " bytes of text, "
1029 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +00001030 Relocations.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +00001031
Evan Chengbc4707a2008-09-18 07:54:21 +00001032 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +00001033 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +00001034
Chris Lattnerc5633c22007-01-20 20:51:43 +00001035#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +00001036 {
Evan Chenge7c35512008-11-12 08:22:43 +00001037 if (sys::hasDisassembler()) {
1038 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001039 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001040 } else {
1041 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001042 DOUT << std::hex;
Evan Chenga7916f52008-11-05 23:44:08 +00001043 unsigned char* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001044 for (int i = 0; q < FnEnd; q += 4, ++i) {
1045 if (i == 4)
1046 i = 0;
1047 if (i == 0)
1048 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1049 << (long)(q - FnStart) << ": ";
1050 bool Done = false;
1051 for (int j = 3; j >= 0; --j) {
1052 if (q + j >= FnEnd)
1053 Done = true;
1054 else
1055 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1056 }
1057 if (Done)
1058 break;
1059 DOUT << ' ';
1060 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001061 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001062 }
1063 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001064 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001065 }
1066 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001067#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001068 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001069 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001070 SavedBufferBegin = BufferBegin;
1071 SavedBufferEnd = BufferEnd;
1072 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001073
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001074 if (MemMgr->NeedsExactSize()) {
1075 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001076 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001077
1078 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1079 ActualSize);
1080 BufferEnd = BufferBegin+ActualSize;
1081 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001082 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1083 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001084 BufferBegin = SavedBufferBegin;
1085 BufferEnd = SavedBufferEnd;
1086 CurBufferPtr = SavedCurBufferPtr;
1087
1088 TheJIT->RegisterTable(FrameRegister);
1089 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001090
1091 if (MMI)
1092 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001093
Chris Lattner43b429b2006-05-02 18:27:26 +00001094 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001095}
1096
Evan Cheng5788d1a2008-12-10 02:32:19 +00001097void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001098 if (BufferBegin)
1099 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1100
1101 // create a new memory block if there is no active one.
1102 // care must be taken so that BufferBegin is invalidated when a
1103 // block is trimmed
1104 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1105 BufferEnd = BufferBegin+Size;
1106 return CurBufferPtr;
1107}
1108
Chris Lattner166f2262004-11-22 22:00:25 +00001109void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001110 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001111 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001112
Chris Lattnerfa77d432006-02-09 04:22:52 +00001113 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001114 if (Constants.empty()) return;
1115
Evan Chengcd5731d2006-09-12 20:59:59 +00001116 MachineConstantPoolEntry CPE = Constants.back();
1117 unsigned Size = CPE.Offset;
1118 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +00001119 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001120 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001121
Evan Cheng97b8c402008-04-12 00:22:01 +00001122 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1123 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001124 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001125
1126 if (ConstantPoolBase == 0) return; // Buffer overflow.
1127
Evan Cheng97b8c402008-04-12 00:22:01 +00001128 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1129 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1130
Chris Lattner239862c2006-02-09 04:49:59 +00001131 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +00001132 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +00001133 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +00001134 if (Constants[i].isMachineConstantPoolEntry()) {
1135 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001136 cerr << "Initialize memory with machine specific constant pool entry"
1137 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001138 abort();
1139 }
1140 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng97b8c402008-04-12 00:22:01 +00001141 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Chris Lattner1cc08382003-01-13 01:00:12 +00001142 }
1143}
1144
Nate Begeman37efe672006-04-22 18:53:45 +00001145void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001146 if (TheJIT->getJITInfo().hasCustomJumpTables())
1147 return;
1148
Nate Begeman37efe672006-04-22 18:53:45 +00001149 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1150 if (JT.empty()) return;
1151
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001152 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001153 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001154 NumEntries += JT[i].MBBs.size();
1155
1156 unsigned EntrySize = MJTI->getEntrySize();
1157
Nate Begeman37efe672006-04-22 18:53:45 +00001158 // Just allocate space for all the jump tables now. We will fix up the actual
1159 // MBB entries in the tables after we emit the code for each block, since then
1160 // we will know the final locations of the MBBs in memory.
1161 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001162 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001163}
1164
Jim Laskeyb92767a2006-12-14 22:53:42 +00001165void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001166 if (TheJIT->getJITInfo().hasCustomJumpTables())
1167 return;
1168
Nate Begeman37efe672006-04-22 18:53:45 +00001169 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001170 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001171
Jim Laskeyb92767a2006-12-14 22:53:42 +00001172 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001173 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1174 // For each jump table, place the offset from the beginning of the table
1175 // to the target address.
1176 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001177
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001178 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1179 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1180 // Store the offset of the basic block for this jump table slot in the
1181 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001182 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001183 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001184 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001185 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1186 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001187 }
1188 } else {
1189 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1190
1191 // For each jump table, map each target in the jump table to the address of
1192 // an emitted MachineBasicBlock.
1193 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1194
1195 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1196 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1197 // Store the address of the basic block for this jump table slot in the
1198 // memory we allocated for the jump table in 'initJumpTableInfo'
1199 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1200 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1201 }
Nate Begeman37efe672006-04-22 18:53:45 +00001202 }
1203}
1204
Evan Chengce4a70b2008-11-08 08:02:53 +00001205void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1206 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001207 SavedBufferBegin = BufferBegin;
1208 SavedBufferEnd = BufferEnd;
1209 SavedCurBufferPtr = CurBufferPtr;
1210
Evan Chengce4a70b2008-11-08 08:02:53 +00001211 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001212 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001213}
1214
Nate Begemand6b7a242009-02-18 08:31:02 +00001215void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1216 unsigned StubSize) {
1217 SavedBufferBegin = BufferBegin;
1218 SavedBufferEnd = BufferEnd;
1219 SavedCurBufferPtr = CurBufferPtr;
1220
1221 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1222 BufferEnd = BufferBegin+StubSize+1;
1223}
1224
Evan Chengce4a70b2008-11-08 08:02:53 +00001225void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001226 NumBytes += getCurrentPCOffset();
1227 std::swap(SavedBufferBegin, BufferBegin);
1228 BufferEnd = SavedBufferEnd;
1229 CurBufferPtr = SavedCurBufferPtr;
1230 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001231}
1232
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001233// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1234// in the constant pool that was last emitted with the 'emitConstantPool'
1235// method.
1236//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001237uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001238 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001239 "Invalid ConstantPoolIndex!");
Evan Cheng5788d1a2008-12-10 02:32:19 +00001240 return (uintptr_t)ConstantPoolBase +
Chris Lattner239862c2006-02-09 04:49:59 +00001241 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001242}
1243
Nate Begeman37efe672006-04-22 18:53:45 +00001244// getJumpTableEntryAddress - Return the address of the JumpTable with index
1245// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1246//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001247uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001248 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1249 assert(Index < JT.size() && "Invalid jump table index!");
1250
1251 unsigned Offset = 0;
1252 unsigned EntrySize = JumpTable->getEntrySize();
1253
1254 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001255 Offset += JT[i].MBBs.size();
1256
1257 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001258
Evan Cheng5788d1a2008-12-10 02:32:19 +00001259 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001260}
1261
Chris Lattnere993cc22006-05-11 23:08:08 +00001262//===----------------------------------------------------------------------===//
1263// Public interface to this file
1264//===----------------------------------------------------------------------===//
1265
Chris Lattner9f2f1422007-12-06 01:08:09 +00001266MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1267 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001268}
1269
Misha Brukmand69c1e62003-07-28 19:09:06 +00001270// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001271// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001272// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1273// need to resolve function(s) that are being mis-codegenerated, so we need to
1274// resolve their addresses at runtime, and this is the way to do it.
1275extern "C" {
1276 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001277 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001278 return TheJIT->getPointerToFunction(F);
1279 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001280 }
1281}
Chris Lattnere993cc22006-05-11 23:08:08 +00001282
1283// getPointerToFunctionOrStub - If the specified function has been
1284// code-gen'd, return a pointer to the function. If not, compile it, or use
1285// a stub to implement lazy compilation if available.
1286//
1287void *JIT::getPointerToFunctionOrStub(Function *F) {
1288 // If we have already code generated the function, just return the address.
1289 if (void *Addr = getPointerToGlobalIfAvailable(F))
1290 return Addr;
1291
Chris Lattnere7484012007-02-24 02:57:03 +00001292 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001293 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1294 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001295 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001296}
1297
Nate Begemand6b7a242009-02-18 08:31:02 +00001298void JIT::updateFunctionStub(Function *F) {
1299 // Get the empty stub we generated earlier.
1300 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1301 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1302 void *Stub = JE->getJITResolver().getFunctionStub(F);
1303
1304 // Tell the target jit info to rewrite the stub at the specified address,
1305 // rather than creating a new one.
1306 void *Addr = getPointerToGlobalIfAvailable(F);
1307 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1308}
1309
1310/// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1311/// that were emitted during code generation.
1312///
1313void JIT::updateDlsymStubTable() {
1314 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1315 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1316
1317 SmallVector<GlobalValue*, 8> GVs;
1318 SmallVector<void*, 8> Ptrs;
1319
1320 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1321
1322 // If there are no relocatable stubs, return.
1323 if (GVs.empty())
1324 return;
1325
1326 // If there are no new relocatable stubs, return.
1327 void *CurTable = JE->getMemMgr()->getDlsymTable();
1328 if (CurTable && (*(unsigned *)CurTable == GVs.size()))
1329 return;
1330
1331 // Calculate the size of the stub info
1332 unsigned offset = 4 + 4 * GVs.size();
1333
1334 SmallVector<unsigned, 8> Offsets;
1335 for (unsigned i = 0; i != GVs.size(); ++i) {
1336 Offsets.push_back(offset);
1337 offset += GVs[i]->getName().length() + 1;
1338 }
1339
1340 // FIXME: This currently allocates new space every time it's called. A
1341 // different data structure could be used to make this unnecessary.
1342 JE->startGVStub(0, offset, 4);
1343
1344 // Emit the number of records
1345 MCE->emitInt32(GVs.size());
1346
1347 // Emit the string offsets
1348 for (unsigned i = 0; i != GVs.size(); ++i)
1349 MCE->emitInt32(Offsets[i]);
1350
1351 // Emit the pointers
1352 for (unsigned i = 0; i != GVs.size(); ++i)
1353 if (sizeof(void *) == 8)
1354 MCE->emitInt64((intptr_t)Ptrs[i]);
1355 else
1356 MCE->emitInt32((intptr_t)Ptrs[i]);
1357
1358 // Emit the strings
1359 for (unsigned i = 0; i != GVs.size(); ++i)
1360 MCE->emitString(GVs[i]->getName());
1361
1362 // Tell the JIT memory manager where it is.
1363 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1364}
1365
Chris Lattnere993cc22006-05-11 23:08:08 +00001366/// freeMachineCodeForFunction - release machine code memory for given Function.
1367///
1368void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001369
Chris Lattnere993cc22006-05-11 23:08:08 +00001370 // Delete translation for this from the ExecutionEngine, so it will get
1371 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001372 void *OldPtr = updateGlobalMapping(F, 0);
1373
1374 if (OldPtr)
1375 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001376
1377 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001378 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1379 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001380}
1381