blob: 1067c2287f9ce5351452a47d8501d13b3db78cbd [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000040#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000041#ifndef NDEBUG
42#include <iomanip>
43#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner36343732006-12-19 22:43:32 +000046STATISTIC(NumBytes, "Number of bytes of machine code compiled");
47STATISTIC(NumRelos, "Number of relocations applied");
48static JIT *TheJIT = 0;
Chris Lattner54266522004-11-20 23:57:07 +000049
Andrew Lenhartha00269b2005-07-29 23:40:16 +000050
Chris Lattner54266522004-11-20 23:57:07 +000051//===----------------------------------------------------------------------===//
52// JIT lazy compilation code.
53//
54namespace {
Reid Spenceree448632005-07-12 15:51:55 +000055 class JITResolverState {
56 private:
57 /// FunctionToStubMap - Keep track of the stub created for a particular
58 /// function so that we can reuse them if necessary.
59 std::map<Function*, void*> FunctionToStubMap;
60
61 /// StubToFunctionMap - Keep track of the function that each stub
62 /// corresponds to.
63 std::map<void*, Function*> StubToFunctionMap;
Jeff Cohen00b168892005-07-27 06:12:32 +000064
Evan Cheng5594f122008-11-10 01:52:24 +000065 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +000066 /// particular GlobalVariable so that we can reuse them if necessary.
Evan Cheng5594f122008-11-10 01:52:24 +000067 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000068
Reid Spenceree448632005-07-12 15:51:55 +000069 public:
70 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
71 assert(locked.holds(TheJIT->lock));
72 return FunctionToStubMap;
73 }
Jeff Cohen00b168892005-07-27 06:12:32 +000074
Reid Spenceree448632005-07-12 15:51:55 +000075 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
76 assert(locked.holds(TheJIT->lock));
77 return StubToFunctionMap;
78 }
Evan Chengbe8c03f2008-01-04 10:46:51 +000079
80 std::map<GlobalValue*, void*>&
Evan Cheng5594f122008-11-10 01:52:24 +000081 getGlobalToIndirectSymMap(const MutexGuard& locked) {
Evan Chengbe8c03f2008-01-04 10:46:51 +000082 assert(locked.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +000083 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +000084 }
Reid Spenceree448632005-07-12 15:51:55 +000085 };
Jeff Cohen00b168892005-07-27 06:12:32 +000086
Chris Lattner54266522004-11-20 23:57:07 +000087 /// JITResolver - Keep track of, and resolve, call sites for functions that
88 /// have not yet been compiled.
89 class JITResolver {
Chris Lattner5e225582004-11-21 03:37:42 +000090 /// LazyResolverFn - The target lazy resolver function that we actually
91 /// rewrite instructions to use.
92 TargetJITInfo::LazyResolverFn LazyResolverFn;
93
Reid Spenceree448632005-07-12 15:51:55 +000094 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +000095
Chris Lattnerd91ff7c2005-04-18 01:44:27 +000096 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
97 /// external functions.
98 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +000099
100 //map addresses to indexes in the GOT
101 std::map<void*, unsigned> revGOTMap;
102 unsigned nextGOTIndex;
103
Chris Lattnere7484012007-02-24 02:57:03 +0000104 static JITResolver *TheJITResolver;
Chris Lattner54266522004-11-20 23:57:07 +0000105 public:
Dan Gohman950a4c42008-03-25 22:06:05 +0000106 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Chris Lattnere7484012007-02-24 02:57:03 +0000107 TheJIT = &jit;
108
109 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
110 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
111 TheJITResolver = this;
112 }
113
114 ~JITResolver() {
115 TheJITResolver = 0;
Chris Lattner5e225582004-11-21 03:37:42 +0000116 }
Chris Lattner54266522004-11-20 23:57:07 +0000117
Evan Cheng704bff92008-11-13 21:50:50 +0000118 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
119 /// if it has already been created.
120 void *getFunctionStubIfAvailable(Function *F);
121
Chris Lattner54266522004-11-20 23:57:07 +0000122 /// getFunctionStub - This returns a pointer to a function stub, creating
123 /// one on demand as needed.
124 void *getFunctionStub(Function *F);
125
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000126 /// getExternalFunctionStub - Return a stub for the function at the
127 /// specified address, created lazily on demand.
128 void *getExternalFunctionStub(void *FnAddr);
129
Evan Cheng5594f122008-11-10 01:52:24 +0000130 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000131 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000132 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000133
Chris Lattner5e225582004-11-21 03:37:42 +0000134 /// AddCallbackAtLocation - If the target is capable of rewriting an
135 /// instruction without the use of a stub, record the location of the use so
136 /// we know which function is being used at the location.
137 void *AddCallbackAtLocation(Function *F, void *Location) {
Reid Spenceree448632005-07-12 15:51:55 +0000138 MutexGuard locked(TheJIT->lock);
Chris Lattner5e225582004-11-21 03:37:42 +0000139 /// Get the target-specific JIT resolver function.
Reid Spenceree448632005-07-12 15:51:55 +0000140 state.getStubToFunctionMap(locked)[Location] = F;
Chris Lattner870286a2006-06-01 17:29:22 +0000141 return (void*)(intptr_t)LazyResolverFn;
Chris Lattner5e225582004-11-21 03:37:42 +0000142 }
143
Andrew Lenharth6a974612005-07-28 12:44:13 +0000144 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000145 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000146 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000147 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000148
Chris Lattner54266522004-11-20 23:57:07 +0000149 /// JITCompilerFn - This function is called to resolve a stub to a compiled
150 /// address. If the LLVM Function corresponding to the stub has not yet
151 /// been compiled, this function compiles it first.
152 static void *JITCompilerFn(void *Stub);
153 };
154}
155
Chris Lattnere7484012007-02-24 02:57:03 +0000156JITResolver *JITResolver::TheJITResolver = 0;
Chris Lattner54266522004-11-20 23:57:07 +0000157
Evan Cheng704bff92008-11-13 21:50:50 +0000158/// getFunctionStubIfAvailable - This returns a pointer to a function stub
159/// if it has already been created.
160void *JITResolver::getFunctionStubIfAvailable(Function *F) {
161 MutexGuard locked(TheJIT->lock);
162
163 // If we already have a stub for this function, recycle it.
164 void *&Stub = state.getFunctionToStubMap(locked)[F];
165 return Stub;
166}
167
Chris Lattner54266522004-11-20 23:57:07 +0000168/// getFunctionStub - This returns a pointer to a function stub, creating
169/// one on demand as needed.
170void *JITResolver::getFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000171 MutexGuard locked(TheJIT->lock);
172
Chris Lattner54266522004-11-20 23:57:07 +0000173 // If we already have a stub for this function, recycle it.
Reid Spenceree448632005-07-12 15:51:55 +0000174 void *&Stub = state.getFunctionToStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000175 if (Stub) return Stub;
176
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000177 // Call the lazy resolver function unless we already KNOW it is an external
178 // function, in which case we just skip the lazy resolution step.
Chris Lattner870286a2006-06-01 17:29:22 +0000179 void *Actual = (void*)(intptr_t)LazyResolverFn;
Dan Gohman69f93782009-01-05 05:32:42 +0000180 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000181 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000182
Dan Gohman69f93782009-01-05 05:32:42 +0000183 // If we resolved the symbol to a null address (eg. a weak external)
184 // don't emit a stub. Return a null pointer to the application.
185 if (!Actual) return 0;
186 }
187
Chris Lattner54266522004-11-20 23:57:07 +0000188 // Otherwise, codegen a new stub. For now, the stub will call the lazy
189 // resolver function.
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000190 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Chris Lattnere7484012007-02-24 02:57:03 +0000191 *TheJIT->getCodeEmitter());
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000192
Chris Lattner870286a2006-06-01 17:29:22 +0000193 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000194 // If we are getting the stub for an external function, we really want the
195 // address of the stub in the GlobalAddressMap for the JIT, not the address
196 // of the external function.
197 TheJIT->updateGlobalMapping(F, Stub);
198 }
Chris Lattner54266522004-11-20 23:57:07 +0000199
Bill Wendling832171c2006-12-07 20:04:42 +0000200 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
201 << F->getName() << "'\n";
Chris Lattnercb479412004-11-21 03:44:32 +0000202
Chris Lattner54266522004-11-20 23:57:07 +0000203 // Finally, keep track of the stub-to-Function mapping so that the
204 // JITCompilerFn knows which function to compile!
Reid Spenceree448632005-07-12 15:51:55 +0000205 state.getStubToFunctionMap(locked)[Stub] = F;
Chris Lattner54266522004-11-20 23:57:07 +0000206 return Stub;
207}
208
Evan Cheng5594f122008-11-10 01:52:24 +0000209/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000210/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000211void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000212 MutexGuard locked(TheJIT->lock);
213
214 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000215 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
216 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000217
Evan Chenge4d783d2008-11-10 23:26:16 +0000218 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000219 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Evan Chengc96a8e72008-11-05 01:50:32 +0000220 *TheJIT->getCodeEmitter());
Evan Chengbe8c03f2008-01-04 10:46:51 +0000221
Evan Cheng5594f122008-11-10 01:52:24 +0000222 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
Evan Chengbe8c03f2008-01-04 10:46:51 +0000223 << GV->getName() << "'\n";
224
Evan Cheng5594f122008-11-10 01:52:24 +0000225 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000226}
227
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000228/// getExternalFunctionStub - Return a stub for the function at the
229/// specified address, created lazily on demand.
230void *JITResolver::getExternalFunctionStub(void *FnAddr) {
231 // If we already have a stub for this function, recycle it.
232 void *&Stub = ExternalFnToStubMap[FnAddr];
233 if (Stub) return Stub;
234
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000235 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Chris Lattnere7484012007-02-24 02:57:03 +0000236 *TheJIT->getCodeEmitter());
Evan Cheng55fc2802006-07-25 20:40:54 +0000237
Bill Wendling832171c2006-12-07 20:04:42 +0000238 DOUT << "JIT: Stub emitted at [" << Stub
239 << "] for external function at '" << FnAddr << "'\n";
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000240 return Stub;
241}
242
Andrew Lenharth6a974612005-07-28 12:44:13 +0000243unsigned JITResolver::getGOTIndexForAddr(void* addr) {
244 unsigned idx = revGOTMap[addr];
245 if (!idx) {
246 idx = ++nextGOTIndex;
247 revGOTMap[addr] = idx;
Evan Cheng366cf292008-11-07 22:30:29 +0000248 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
Andrew Lenharth6a974612005-07-28 12:44:13 +0000249 }
250 return idx;
251}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000252
Chris Lattner54266522004-11-20 23:57:07 +0000253/// JITCompilerFn - This function is called when a lazy compilation stub has
254/// been entered. It looks up which function this stub corresponds to, compiles
255/// it if necessary, then returns the resultant function pointer.
256void *JITResolver::JITCompilerFn(void *Stub) {
Chris Lattnere7484012007-02-24 02:57:03 +0000257 JITResolver &JR = *TheJITResolver;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000258
259 Function* F = 0;
260 void* ActualPtr = 0;
Misha Brukmanf976c852005-04-21 22:55:34 +0000261
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000262 {
263 // Only lock for getting the Function. The call getPointerToFunction made
264 // in this function might trigger function materializing, which requires
265 // JIT lock to be unlocked.
266 MutexGuard locked(TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000267
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000268 // The address given to us for the stub may not be exactly right, it might be
269 // a little bit after the stub. As such, use upper_bound to find it.
270 std::map<void*, Function*>::iterator I =
271 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
272 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
273 "This is not a known stub!");
274 F = (--I)->second;
275 ActualPtr = I->first;
276 }
Chris Lattner54266522004-11-20 23:57:07 +0000277
Evan Cheng9da60f92007-06-30 00:10:37 +0000278 // If we have already code generated the function, just return the address.
279 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner9cab56d2006-11-09 19:32:13 +0000280
Evan Cheng9da60f92007-06-30 00:10:37 +0000281 if (!Result) {
282 // Otherwise we don't have it, do lazy compilation now.
283
284 // If lazy compilation is disabled, emit a useful error message and abort.
285 if (TheJIT->isLazyCompilationDisabled()) {
286 cerr << "LLVM JIT requested to do lazy compilation of function '"
287 << F->getName() << "' when lazy compiles are disabled!\n";
288 abort();
289 }
290
291 // We might like to remove the stub from the StubToFunction map.
292 // We can't do that! Multiple threads could be stuck, waiting to acquire the
293 // lock above. As soon as the 1st function finishes compiling the function,
294 // the next one will be released, and needs to be able to find the function
295 // it needs to call.
296 //JR.state.getStubToFunctionMap(locked).erase(I);
Chris Lattner54266522004-11-20 23:57:07 +0000297
Evan Cheng9da60f92007-06-30 00:10:37 +0000298 DOUT << "JIT: Lazily resolving function '" << F->getName()
299 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000300 << ActualPtr << "\n";
Chris Lattner54266522004-11-20 23:57:07 +0000301
Evan Cheng9da60f92007-06-30 00:10:37 +0000302 Result = TheJIT->getPointerToFunction(F);
303 }
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000304
305 // Reacquire the lock to erase the stub in the map.
306 MutexGuard locked(TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000307
308 // We don't need to reuse this stub in the future, as F is now compiled.
Reid Spenceree448632005-07-12 15:51:55 +0000309 JR.state.getFunctionToStubMap(locked).erase(F);
Chris Lattner54266522004-11-20 23:57:07 +0000310
311 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000312
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000313 // What we will do is set the compiled function address to map to the
314 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000315 // if they see it still using the stub address.
316 // Note: this is done so the Resolver doesn't have to manage GOT memory
317 // Do this without allocating map space if the target isn't using a GOT
318 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
319 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
320
Chris Lattner54266522004-11-20 23:57:07 +0000321 return Result;
322}
Chris Lattner688506d2003-08-14 18:35:27 +0000323
Chris Lattner8ac66c12008-04-04 05:51:42 +0000324//===----------------------------------------------------------------------===//
325// Function Index Support
326
327// On MacOS we generate an index of currently JIT'd functions so that
328// performance tools can determine a symbol name and accurate code range for a
329// PC value. Because performance tools are generally asynchronous, the code
330// below is written with the hope that it could be interrupted at any time and
331// have useful answers. However, we don't go crazy with atomic operations, we
332// just do a "reasonable effort".
333#ifdef __APPLE__
Evan Chengbdb6ca12008-05-15 17:31:35 +0000334#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattner8ac66c12008-04-04 05:51:42 +0000335#endif
336
337/// JitSymbolEntry - Each function that is JIT compiled results in one of these
338/// being added to an array of symbols. This indicates the name of the function
339/// as well as the address range it occupies. This allows the client to map
340/// from a PC value to the name of the function.
341struct JitSymbolEntry {
342 const char *FnName; // FnName - a strdup'd string.
343 void *FnStart;
344 intptr_t FnSize;
345};
346
347
348struct JitSymbolTable {
349 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
350 /// pointer is not used right now, but might be used in the future. Consider
351 /// it reserved for future use.
352 JitSymbolTable *NextPtr;
353
354 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
355 /// 'NumSymbols' symbols are valid.
356 JitSymbolEntry *Symbols;
357
358 /// NumSymbols - This indicates the number entries in the Symbols array that
359 /// are valid.
360 unsigned NumSymbols;
361
362 /// NumAllocated - This indicates the amount of space we have in the Symbols
363 /// array. This is a private field that should not be read by external tools.
364 unsigned NumAllocated;
365};
366
367#if ENABLE_JIT_SYMBOL_TABLE
368JitSymbolTable *__jitSymbolTable;
369#endif
370
371static void AddFunctionToSymbolTable(const char *FnName,
372 void *FnStart, intptr_t FnSize) {
373 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
374 JitSymbolTable **SymTabPtrPtr = 0;
375#if !ENABLE_JIT_SYMBOL_TABLE
376 return;
377#else
378 SymTabPtrPtr = &__jitSymbolTable;
379#endif
380
381 // If this is the first entry in the symbol table, add the JitSymbolTable
382 // index.
383 if (*SymTabPtrPtr == 0) {
384 JitSymbolTable *New = new JitSymbolTable();
385 New->NextPtr = 0;
386 New->Symbols = 0;
387 New->NumSymbols = 0;
388 New->NumAllocated = 0;
389 *SymTabPtrPtr = New;
390 }
391
392 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
393
394 // If we have space in the table, reallocate the table.
395 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
396 // If we don't have space, reallocate the table.
Chris Lattner3b374482008-04-13 07:04:56 +0000397 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000398 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
399 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
400
401 // Copy the old entries over.
402 memcpy(NewSymbols, OldSymbols,
Chris Lattner3b374482008-04-13 07:04:56 +0000403 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattner8ac66c12008-04-04 05:51:42 +0000404
405 // Swap the new symbols in, delete the old ones.
406 SymTabPtr->Symbols = NewSymbols;
Chris Lattner3b374482008-04-13 07:04:56 +0000407 SymTabPtr->NumAllocated = NewSize;
Chris Lattner8ac66c12008-04-04 05:51:42 +0000408 delete [] OldSymbols;
409 }
410
411 // Otherwise, we have enough space, just tack it onto the end of the array.
412 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
413 Entry.FnName = strdup(FnName);
414 Entry.FnStart = FnStart;
415 Entry.FnSize = FnSize;
416 ++SymTabPtr->NumSymbols;
417}
418
419static void RemoveFunctionFromSymbolTable(void *FnStart) {
420 assert(FnStart && "Invalid function pointer");
421 JitSymbolTable **SymTabPtrPtr = 0;
422#if !ENABLE_JIT_SYMBOL_TABLE
423 return;
424#else
425 SymTabPtrPtr = &__jitSymbolTable;
426#endif
427
428 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
429 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
430
431 // Scan the table to find its index. The table is not sorted, so do a linear
432 // scan.
433 unsigned Index;
434 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
435 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
436
437 // Once we have an index, we know to nuke this entry, overwrite it with the
438 // entry at the end of the array, making the last entry redundant.
439 const char *OldName = Symbols[Index].FnName;
440 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
441 free((void*)OldName);
442
443 // Drop the number of symbols in the table.
444 --SymTabPtr->NumSymbols;
445
446 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begemanf44085a2008-05-18 19:09:10 +0000447 if (SymTabPtr->NumSymbols != 0)
Chris Lattner8ac66c12008-04-04 05:51:42 +0000448 return;
449
450 *SymTabPtrPtr = 0;
451 delete [] Symbols;
452 delete SymTabPtr;
453}
Chris Lattner688506d2003-08-14 18:35:27 +0000454
Chris Lattner54266522004-11-20 23:57:07 +0000455//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000456// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000457//
Chris Lattner688506d2003-08-14 18:35:27 +0000458namespace {
Chris Lattner166f2262004-11-22 22:00:25 +0000459 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
460 /// used to output functions to memory for execution.
461 class JITEmitter : public MachineCodeEmitter {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000462 JITMemoryManager *MemMgr;
Chris Lattner688506d2003-08-14 18:35:27 +0000463
Chris Lattner6125fdd2003-05-09 03:30:07 +0000464 // When outputting a function stub in the context of some other function, we
Chris Lattner43b429b2006-05-02 18:27:26 +0000465 // save BufferBegin/BufferEnd/CurBufferPtr here.
466 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000467
Chris Lattner5be478f2004-11-20 03:46:14 +0000468 /// Relocations - These are the relocations that the function needs, as
469 /// emitted.
470 std::vector<MachineRelocation> Relocations;
Chris Lattnerb4432f32006-05-03 17:10:41 +0000471
472 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
473 /// It is filled in by the StartMachineBasicBlock callback and queried by
474 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000475 std::vector<uintptr_t> MBBLocations;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000476
Chris Lattner239862c2006-02-09 04:49:59 +0000477 /// ConstantPool - The constant pool for the current function.
478 ///
479 MachineConstantPool *ConstantPool;
480
481 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
482 ///
483 void *ConstantPoolBase;
Nate Begeman37efe672006-04-22 18:53:45 +0000484
Nate Begeman019f8512006-09-10 23:03:44 +0000485 /// JumpTable - The jump tables for the current function.
Nate Begeman37efe672006-04-22 18:53:45 +0000486 ///
487 MachineJumpTableInfo *JumpTable;
488
489 /// JumpTableBase - A pointer to the first entry in the jump table.
490 ///
491 void *JumpTableBase;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000492
Chris Lattnere7484012007-02-24 02:57:03 +0000493 /// Resolver - This contains info about the currently resolved functions.
494 JITResolver Resolver;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000495
496 /// DE - The dwarf emitter for the jit.
497 JITDwarfEmitter *DE;
498
499 /// LabelLocations - This vector is a mapping from Label ID's to their
500 /// address.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000501 std::vector<uintptr_t> LabelLocations;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000502
503 /// MMI - Machine module info for exception informations
504 MachineModuleInfo* MMI;
505
Dale Johannesendd947ea2008-08-07 01:30:15 +0000506 // GVSet - a set to keep track of which globals have been seen
Evan Cheng47c01a02008-11-07 09:02:17 +0000507 SmallPtrSet<const GlobalVariable*, 8> GVSet;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000508
Chris Lattnere7484012007-02-24 02:57:03 +0000509 public:
Chris Lattner9f2f1422007-12-06 01:08:09 +0000510 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
511 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000512 if (jit.getJITInfo().needsGOT()) {
513 MemMgr->AllocateGOT();
514 DOUT << "JIT is managing a GOT\n";
515 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000516
517 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000518 }
519 ~JITEmitter() {
520 delete MemMgr;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000521 if (ExceptionHandling) delete DE;
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000522 }
Evan Chenga044dfc2008-08-20 00:28:12 +0000523
524 /// classof - Methods for support type inquiry through isa, cast, and
525 /// dyn_cast:
526 ///
527 static inline bool classof(const JITEmitter*) { return true; }
528 static inline bool classof(const MachineCodeEmitter*) { return true; }
Chris Lattnere7484012007-02-24 02:57:03 +0000529
530 JITResolver &getJITResolver() { return Resolver; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000531
532 virtual void startFunction(MachineFunction &F);
Chris Lattner43b429b2006-05-02 18:27:26 +0000533 virtual bool finishFunction(MachineFunction &F);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000534
535 void emitConstantPool(MachineConstantPool *MCP);
536 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
Jim Laskeyb92767a2006-12-14 22:53:42 +0000537 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000538
Evan Chengce4a70b2008-11-08 08:02:53 +0000539 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000540 unsigned Alignment = 1);
Evan Chengce4a70b2008-11-08 08:02:53 +0000541 virtual void* finishGVStub(const GlobalValue *GV);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000542
Nuno Lopescef75272008-10-21 11:42:16 +0000543 /// allocateSpace - Reserves space in the current block if any, or
544 /// allocate a new one of the given size.
Evan Cheng5788d1a2008-12-10 02:32:19 +0000545 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000546
Chris Lattner5be478f2004-11-20 03:46:14 +0000547 virtual void addRelocation(const MachineRelocation &MR) {
548 Relocations.push_back(MR);
549 }
Chris Lattnerb4432f32006-05-03 17:10:41 +0000550
551 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
552 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
553 MBBLocations.resize((MBB->getNumber()+1)*2);
554 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Evan Cheng366cf292008-11-07 22:30:29 +0000555 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
556 << (void*) getCurrentPCValue() << "]\n";
Chris Lattnerb4432f32006-05-03 17:10:41 +0000557 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000558
Evan Cheng5788d1a2008-12-10 02:32:19 +0000559 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
560 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Cheng2a3e08b2008-01-05 02:26:58 +0000561
Evan Cheng5788d1a2008-12-10 02:32:19 +0000562 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Chris Lattnerb4432f32006-05-03 17:10:41 +0000563 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
564 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
565 return MBBLocations[MBB->getNumber()];
566 }
567
Chris Lattnere993cc22006-05-11 23:08:08 +0000568 /// deallocateMemForFunction - Deallocate all memory for the specified
569 /// function body.
570 void deallocateMemForFunction(Function *F) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000571 MemMgr->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +0000572 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000573
574 virtual void emitLabel(uint64_t LabelID) {
575 if (LabelLocations.size() <= LabelID)
576 LabelLocations.resize((LabelID+1)*2);
577 LabelLocations[LabelID] = getCurrentPCValue();
578 }
579
Evan Cheng5788d1a2008-12-10 02:32:19 +0000580 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000581 assert(LabelLocations.size() > (unsigned)LabelID &&
582 LabelLocations[LabelID] && "Label not emitted!");
583 return LabelLocations[LabelID];
584 }
585
586 virtual void setModuleInfo(MachineModuleInfo* Info) {
587 MMI = Info;
588 if (ExceptionHandling) DE->setModuleInfo(Info);
589 }
590
Jim Grosbachcce6c292008-10-03 16:17:20 +0000591 void setMemoryExecutable(void) {
592 MemMgr->setMemoryExecutable();
593 }
594
Chris Lattner54266522004-11-20 23:57:07 +0000595 private:
Chris Lattner5e225582004-11-21 03:37:42 +0000596 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng5594f122008-11-10 01:52:24 +0000597 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000598 bool NoNeedStub);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000599 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
600 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
601 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
602 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000603 };
604}
605
Chris Lattner166f2262004-11-22 22:00:25 +0000606void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
607 bool DoesntNeedStub) {
Chris Lattner54266522004-11-20 23:57:07 +0000608 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
609 /// FIXME: If we straightened things out, this could actually emit the
610 /// global immediately instead of queuing it for codegen later!
Chris Lattner54266522004-11-20 23:57:07 +0000611 return TheJIT->getOrEmitGlobalVariable(GV);
612 }
Chris Lattner18e04592008-06-25 20:21:35 +0000613 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikov19e861a2008-09-09 20:05:04 +0000614 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner54266522004-11-20 23:57:07 +0000615
616 // If we have already compiled the function, return a pointer to its body.
617 Function *F = cast<Function>(V);
Evan Cheng704bff92008-11-13 21:50:50 +0000618 void *ResultPtr;
Evan Cheng369e02d2008-12-10 01:33:59 +0000619 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
Evan Cheng704bff92008-11-13 21:50:50 +0000620 // Return the function stub if it's already created.
621 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
622 else
623 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
Chris Lattner54266522004-11-20 23:57:07 +0000624 if (ResultPtr) return ResultPtr;
625
Gabor Greifa99be512007-07-05 17:07:56 +0000626 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
Chris Lattner54266522004-11-20 23:57:07 +0000627 // If this is an external function pointer, we can force the JIT to
628 // 'compile' it, which really just adds it to the map.
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000629 if (DoesntNeedStub)
630 return TheJIT->getPointerToFunction(F);
631
Chris Lattnere7484012007-02-24 02:57:03 +0000632 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000633 }
634
Chris Lattner5e225582004-11-21 03:37:42 +0000635 // Okay, the function has not been compiled yet, if the target callback
636 // mechanism is capable of rewriting the instruction directly, prefer to do
637 // that instead of emitting a stub.
638 if (DoesntNeedStub)
Chris Lattnere7484012007-02-24 02:57:03 +0000639 return Resolver.AddCallbackAtLocation(F, Reference);
Chris Lattner5e225582004-11-21 03:37:42 +0000640
Chris Lattner54266522004-11-20 23:57:07 +0000641 // Otherwise, we have to emit a lazy resolving stub.
Chris Lattnere7484012007-02-24 02:57:03 +0000642 return Resolver.getFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000643}
644
Evan Cheng5594f122008-11-10 01:52:24 +0000645void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
Evan Chenge4d783d2008-11-10 23:26:16 +0000646 bool NoNeedStub) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000647 // Make sure GV is emitted first.
648 // FIXME: For now, if the GV is an external function we force the JIT to
Evan Cheng5594f122008-11-10 01:52:24 +0000649 // compile it so the indirect symbol will contain the fully resolved address.
Evan Chengbe8c03f2008-01-04 10:46:51 +0000650 void *GVAddress = getPointerToGlobal(V, Reference, true);
Evan Cheng5594f122008-11-10 01:52:24 +0000651 return Resolver.getGlobalValueIndirectSym(V, GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000652}
653
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000654static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
655 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
656 if (Constants.empty()) return 0;
657
658 MachineConstantPoolEntry CPE = Constants.back();
659 unsigned Size = CPE.Offset;
660 const Type *Ty = CPE.isMachineConstantPoolEntry()
661 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000662 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000663 return Size;
664}
665
666static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
667 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
668 if (JT.empty()) return 0;
669
670 unsigned NumEntries = 0;
671 for (unsigned i = 0, e = JT.size(); i != e; ++i)
672 NumEntries += JT[i].MBBs.size();
673
674 unsigned EntrySize = MJTI->getEntrySize();
675
676 return NumEntries * EntrySize;
677}
678
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000679static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000680 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000681 // Since we do not know where the buffer will be allocated, be pessimistic.
682 return Size + Alignment;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000683}
Evan Chengbe8c03f2008-01-04 10:46:51 +0000684
Dale Johannesendd947ea2008-08-07 01:30:15 +0000685/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
686/// into the running total Size.
687
688unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
689 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000690 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000691 size_t GVAlign =
692 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000693 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
Dale Johannesendd947ea2008-08-07 01:30:15 +0000694 DEBUG(GV->dump());
695 // Assume code section ends with worst possible alignment, so first
696 // variable needs maximal padding.
697 if (Size==0)
698 Size = 1;
699 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
700 Size += GVSize;
701 return Size;
702}
703
704/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
705/// but are referenced from the constant; put them in GVSet and add their
706/// size into the running total Size.
707
708unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
709 unsigned Size) {
710 // If its undefined, return the garbage.
711 if (isa<UndefValue>(C))
712 return Size;
713
714 // If the value is a ConstantExpr
715 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
716 Constant *Op0 = CE->getOperand(0);
717 switch (CE->getOpcode()) {
718 case Instruction::GetElementPtr:
719 case Instruction::Trunc:
720 case Instruction::ZExt:
721 case Instruction::SExt:
722 case Instruction::FPTrunc:
723 case Instruction::FPExt:
724 case Instruction::UIToFP:
725 case Instruction::SIToFP:
726 case Instruction::FPToUI:
727 case Instruction::FPToSI:
728 case Instruction::PtrToInt:
729 case Instruction::IntToPtr:
730 case Instruction::BitCast: {
731 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
732 break;
733 }
734 case Instruction::Add:
735 case Instruction::Sub:
736 case Instruction::Mul:
737 case Instruction::UDiv:
738 case Instruction::SDiv:
739 case Instruction::URem:
740 case Instruction::SRem:
741 case Instruction::And:
742 case Instruction::Or:
743 case Instruction::Xor: {
744 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
745 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
746 break;
747 }
748 default: {
749 cerr << "ConstantExpr not handled: " << *CE << "\n";
750 abort();
751 }
752 }
753 }
754
755 if (C->getType()->getTypeID() == Type::PointerTyID)
756 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
Evan Cheng47c01a02008-11-07 09:02:17 +0000757 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000758 Size = addSizeOfGlobal(GV, Size);
759
760 return Size;
761}
762
763/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
764/// but are referenced from the given initializer.
765
766unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
767 unsigned Size) {
768 if (!isa<UndefValue>(Init) &&
769 !isa<ConstantVector>(Init) &&
770 !isa<ConstantAggregateZero>(Init) &&
771 !isa<ConstantArray>(Init) &&
772 !isa<ConstantStruct>(Init) &&
773 Init->getType()->isFirstClassType())
774 Size = addSizeOfGlobalsInConstantVal(Init, Size);
775 return Size;
776}
777
778/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
779/// globals; then walk the initializers of those globals looking for more.
780/// If their size has not been considered yet, add it into the running total
781/// Size.
782
783unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
784 unsigned Size = 0;
785 GVSet.clear();
786
787 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
788 MBB != E; ++MBB) {
789 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
790 I != E; ++I) {
791 const TargetInstrDesc &Desc = I->getDesc();
792 const MachineInstr &MI = *I;
793 unsigned NumOps = Desc.getNumOperands();
794 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
795 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmand735b802008-10-03 15:45:36 +0000796 if (MO.isGlobal()) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000797 GlobalValue* V = MO.getGlobal();
798 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
799 if (!GV)
800 continue;
801 // If seen in previous function, it will have an entry here.
802 if (TheJIT->getPointerToGlobalIfAvailable(GV))
803 continue;
804 // If seen earlier in this function, it will have an entry here.
805 // FIXME: it should be possible to combine these tables, by
806 // assuming the addresses of the new globals in this module
807 // start at 0 (or something) and adjusting them after codegen
808 // complete. Another possibility is to grab a marker bit in GV.
Evan Cheng47c01a02008-11-07 09:02:17 +0000809 if (GVSet.insert(GV))
Dale Johannesendd947ea2008-08-07 01:30:15 +0000810 // A variable as yet unseen. Add in its size.
811 Size = addSizeOfGlobal(GV, Size);
812 }
813 }
814 }
815 }
Evan Chengeb5d95a2008-11-06 17:46:04 +0000816 DOUT << "JIT: About to look through initializers\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000817 // Look for more globals that are referenced only from initializers.
818 // GVSet.end is computed each time because the set can grow as we go.
Evan Cheng47c01a02008-11-07 09:02:17 +0000819 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000820 I != GVSet.end(); I++) {
821 const GlobalVariable* GV = *I;
822 if (GV->hasInitializer())
823 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
824 }
825
826 return Size;
827}
828
Chris Lattner166f2262004-11-22 22:00:25 +0000829void JITEmitter::startFunction(MachineFunction &F) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000830 DOUT << "JIT: Starting CodeGen of Function "
831 << F.getFunction()->getName() << "\n";
832
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000833 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000834 // Set the memory writable, if it's not already
835 MemMgr->setMemoryWritable();
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +0000836 if (MemMgr->NeedsExactSize()) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000837 DOUT << "JIT: ExactSize\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000838 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
839 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
840 MachineConstantPool *MCP = F.getConstantPool();
841
842 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000843 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000844
845 // Add the alignment of the constant pool
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000846 ActualSize = RoundUpToAlign(ActualSize,
847 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000848
849 // Add the constant pool size
850 ActualSize += GetConstantPoolSizeInBytes(MCP);
851
852 // Add the aligment of the jump table info
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000853 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000854
855 // Add the jump table size
856 ActualSize += GetJumpTableSizeInBytes(MJTI);
857
858 // Add the alignment for the function
Nicolas Geoffray580631a2008-04-20 23:39:44 +0000859 ActualSize = RoundUpToAlign(ActualSize,
860 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000861
862 // Add the function size
863 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000864
Evan Chengeb5d95a2008-11-06 17:46:04 +0000865 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000866 // Add the size of the globals that will be allocated after this function.
867 // These are all the ones referenced from this function that were not
868 // previously allocated.
869 ActualSize += GetSizeOfGlobalsInBytes(F);
Evan Chengeb5d95a2008-11-06 17:46:04 +0000870 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000871 }
872
Chris Lattner8907b4b2007-12-05 23:39:57 +0000873 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
874 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000875 BufferEnd = BufferBegin+ActualSize;
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000876
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000877 // Ensure the constant pool/jump table info is at least 4-byte aligned.
878 emitAlignment(16);
879
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000880 emitConstantPool(F.getConstantPool());
881 initJumpTableInfo(F.getJumpTableInfo());
882
883 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000884 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000885 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Evan Cheng55fc2802006-07-25 20:40:54 +0000886
Chris Lattnerb4432f32006-05-03 17:10:41 +0000887 MBBLocations.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000888}
889
Chris Lattner43b429b2006-05-02 18:27:26 +0000890bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000891 if (CurBufferPtr == BufferEnd) {
892 // FIXME: Allocate more space, then try again.
Bill Wendling832171c2006-12-07 20:04:42 +0000893 cerr << "JIT: Ran out of space for generated machine code!\n";
Chris Lattnere993cc22006-05-11 23:08:08 +0000894 abort();
895 }
896
Jim Laskeyb92767a2006-12-14 22:53:42 +0000897 emitJumpTableInfo(F.getJumpTableInfo());
Chris Lattnerb4432f32006-05-03 17:10:41 +0000898
Chris Lattnera8279532006-06-16 18:09:26 +0000899 // FnStart is the start of the text, not the start of the constant pool and
900 // other per-function data.
901 unsigned char *FnStart =
902 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000903
Chris Lattner5be478f2004-11-20 03:46:14 +0000904 if (!Relocations.empty()) {
Chris Lattnere884dc22005-07-20 16:29:20 +0000905 NumRelos += Relocations.size();
906
Chris Lattner5be478f2004-11-20 03:46:14 +0000907 // Resolve the relocations to concrete pointers.
908 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
909 MachineRelocation &MR = Relocations[i];
Evan Cheng92006052008-11-03 07:14:02 +0000910 void *ResultPtr = 0;
Evan Chengef5784e2008-10-29 23:54:46 +0000911 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +0000912 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +0000913 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
914 false);
Evan Chengd7398c92008-11-08 07:37:34 +0000915 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Evan Chengca66b082008-11-08 07:22:53 +0000916 << ResultPtr << "]\n";
Misha Brukmanf976c852005-04-21 22:55:34 +0000917
Evan Chengef5784e2008-10-29 23:54:46 +0000918 // If the target REALLY wants a stub for this function, emit it now.
919 if (!MR.doesntNeedStub())
920 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
921 } else if (MR.isGlobalValue()) {
922 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
923 BufferBegin+MR.getMachineCodeOffset(),
924 MR.doesntNeedStub());
Evan Cheng5594f122008-11-10 01:52:24 +0000925 } else if (MR.isIndirectSymbol()) {
926 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
Evan Chengbe8c03f2008-01-04 10:46:51 +0000927 BufferBegin+MR.getMachineCodeOffset(),
928 MR.doesntNeedStub());
Evan Chengef5784e2008-10-29 23:54:46 +0000929 } else if (MR.isBasicBlock()) {
930 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
931 } else if (MR.isConstantPoolIndex()) {
932 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
933 } else {
934 assert(MR.isJumpTableIndex());
935 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
936 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000937
Evan Chengef5784e2008-10-29 23:54:46 +0000938 MR.setResultPointer(ResultPtr);
939 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000940
Andrew Lenharth6a974612005-07-28 12:44:13 +0000941 // if we are managing the GOT and the relocation wants an index,
942 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000943 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000944 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000945 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000946 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000947 DOUT << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner8907b4b2007-12-05 23:39:57 +0000948 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Bill Wendling832171c2006-12-07 20:04:42 +0000949 << "\n";
Chris Lattner8907b4b2007-12-05 23:39:57 +0000950 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000951 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000952 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000953 }
954
Chris Lattner43b429b2006-05-02 18:27:26 +0000955 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000956 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000957 }
958
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000959 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000960 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000961 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000962 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000963 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner8907b4b2007-12-05 23:39:57 +0000964 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
965 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000966 }
967 }
968
Nuno Lopescef75272008-10-21 11:42:16 +0000969 unsigned char *FnEnd = CurBufferPtr;
970
971 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Evan Cheng5788d1a2008-12-10 02:32:19 +0000972
973 if (CurBufferPtr == BufferEnd) {
974 // FIXME: Allocate more space, then try again.
975 cerr << "JIT: Ran out of space for generated machine code!\n";
976 abort();
977 }
978
Nuno Lopescef75272008-10-21 11:42:16 +0000979 BufferBegin = CurBufferPtr = 0;
980 NumBytes += FnEnd-FnStart;
981
Evan Cheng55fc2802006-07-25 20:40:54 +0000982 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +0000983 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattner8ac66c12008-04-04 05:51:42 +0000984
985 // Add it to the JIT symbol table if the host wants it.
986 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
987 FnStart, FnEnd-FnStart);
Evan Cheng55fc2802006-07-25 20:40:54 +0000988
Bill Wendling832171c2006-12-07 20:04:42 +0000989 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
990 << "] Function: " << F.getFunction()->getName()
991 << ": " << (FnEnd-FnStart) << " bytes of text, "
992 << Relocations.size() << " relocations\n";
Chris Lattner5be478f2004-11-20 03:46:14 +0000993 Relocations.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +0000994
Evan Chengbc4707a2008-09-18 07:54:21 +0000995 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +0000996 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +0000997
Chris Lattnerc5633c22007-01-20 20:51:43 +0000998#ifndef NDEBUG
Evan Chenga7916f52008-11-05 23:44:08 +0000999 {
Evan Chenge7c35512008-11-12 08:22:43 +00001000 if (sys::hasDisassembler()) {
1001 DOUT << "JIT: Disassembled code:\n";
Evan Chengeb5d95a2008-11-06 17:46:04 +00001002 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Evan Chenge7c35512008-11-12 08:22:43 +00001003 } else {
1004 DOUT << "JIT: Binary code:\n";
Evan Chenga7916f52008-11-05 23:44:08 +00001005 DOUT << std::hex;
Evan Chenga7916f52008-11-05 23:44:08 +00001006 unsigned char* q = FnStart;
Evan Chenge7c35512008-11-12 08:22:43 +00001007 for (int i = 0; q < FnEnd; q += 4, ++i) {
1008 if (i == 4)
1009 i = 0;
1010 if (i == 0)
1011 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1012 << (long)(q - FnStart) << ": ";
1013 bool Done = false;
1014 for (int j = 3; j >= 0; --j) {
1015 if (q + j >= FnEnd)
1016 Done = true;
1017 else
1018 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1019 }
1020 if (Done)
1021 break;
1022 DOUT << ' ';
1023 if (i == 3)
Evan Cheng6863fb02008-11-06 01:18:29 +00001024 DOUT << '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001025 }
1026 DOUT << std::dec;
Evan Cheng6863fb02008-11-06 01:18:29 +00001027 DOUT<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +00001028 }
1029 }
Chris Lattnerc5633c22007-01-20 20:51:43 +00001030#endif
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001031 if (ExceptionHandling) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001032 uintptr_t ActualSize = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001033 SavedBufferBegin = BufferBegin;
1034 SavedBufferEnd = BufferEnd;
1035 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001036
Nicolas Geoffray5913e6c2008-04-20 17:44:19 +00001037 if (MemMgr->NeedsExactSize()) {
1038 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +00001039 }
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001040
1041 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1042 ActualSize);
1043 BufferEnd = BufferBegin+ActualSize;
1044 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner0fdaa0b2008-03-07 20:05:43 +00001045 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1046 FrameRegister);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001047 BufferBegin = SavedBufferBegin;
1048 BufferEnd = SavedBufferEnd;
1049 CurBufferPtr = SavedCurBufferPtr;
1050
1051 TheJIT->RegisterTable(FrameRegister);
1052 }
Evan Cheng252ddfb2008-09-02 08:14:01 +00001053
1054 if (MMI)
1055 MMI->EndFunction();
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +00001056
Chris Lattner43b429b2006-05-02 18:27:26 +00001057 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001058}
1059
Evan Cheng5788d1a2008-12-10 02:32:19 +00001060void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +00001061 if (BufferBegin)
1062 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1063
1064 // create a new memory block if there is no active one.
1065 // care must be taken so that BufferBegin is invalidated when a
1066 // block is trimmed
1067 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1068 BufferEnd = BufferBegin+Size;
1069 return CurBufferPtr;
1070}
1071
Chris Lattner166f2262004-11-22 22:00:25 +00001072void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001073 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001074 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001075
Chris Lattnerfa77d432006-02-09 04:22:52 +00001076 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001077 if (Constants.empty()) return;
1078
Evan Chengcd5731d2006-09-12 20:59:59 +00001079 MachineConstantPoolEntry CPE = Constants.back();
1080 unsigned Size = CPE.Offset;
1081 const Type *Ty = CPE.isMachineConstantPoolEntry()
Chris Lattner8a650092006-09-13 16:21:10 +00001082 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001083 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001084
Evan Cheng97b8c402008-04-12 00:22:01 +00001085 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1086 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001087 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001088
1089 if (ConstantPoolBase == 0) return; // Buffer overflow.
1090
Evan Cheng97b8c402008-04-12 00:22:01 +00001091 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1092 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1093
Chris Lattner239862c2006-02-09 04:49:59 +00001094 // Initialize the memory for all of the constant pool entries.
Chris Lattner3029f922006-02-09 04:46:04 +00001095 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner239862c2006-02-09 04:49:59 +00001096 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
Evan Chengcd5731d2006-09-12 20:59:59 +00001097 if (Constants[i].isMachineConstantPoolEntry()) {
1098 // FIXME: add support to lower machine constant pool values into bytes!
Bill Wendling832171c2006-12-07 20:04:42 +00001099 cerr << "Initialize memory with machine specific constant pool entry"
1100 << " has not been implemented!\n";
Evan Chengcd5731d2006-09-12 20:59:59 +00001101 abort();
1102 }
1103 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng97b8c402008-04-12 00:22:01 +00001104 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Chris Lattner1cc08382003-01-13 01:00:12 +00001105 }
1106}
1107
Nate Begeman37efe672006-04-22 18:53:45 +00001108void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001109 if (TheJIT->getJITInfo().hasCustomJumpTables())
1110 return;
1111
Nate Begeman37efe672006-04-22 18:53:45 +00001112 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1113 if (JT.empty()) return;
1114
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001115 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001116 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001117 NumEntries += JT[i].MBBs.size();
1118
1119 unsigned EntrySize = MJTI->getEntrySize();
1120
Nate Begeman37efe672006-04-22 18:53:45 +00001121 // Just allocate space for all the jump tables now. We will fix up the actual
1122 // MBB entries in the tables after we emit the code for each block, since then
1123 // we will know the final locations of the MBBs in memory.
1124 JumpTable = MJTI;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001125 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
Nate Begeman37efe672006-04-22 18:53:45 +00001126}
1127
Jim Laskeyb92767a2006-12-14 22:53:42 +00001128void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001129 if (TheJIT->getJITInfo().hasCustomJumpTables())
1130 return;
1131
Nate Begeman37efe672006-04-22 18:53:45 +00001132 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001133 if (JT.empty() || JumpTableBase == 0) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001134
Jim Laskeyb92767a2006-12-14 22:53:42 +00001135 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001136 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1137 // For each jump table, place the offset from the beginning of the table
1138 // to the target address.
1139 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001140
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001141 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1142 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1143 // Store the offset of the basic block for this jump table slot in the
1144 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001145 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001146 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001147 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001148 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1149 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001150 }
1151 } else {
1152 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1153
1154 // For each jump table, map each target in the jump table to the address of
1155 // an emitted MachineBasicBlock.
1156 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1157
1158 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1159 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1160 // Store the address of the basic block for this jump table slot in the
1161 // memory we allocated for the jump table in 'initJumpTableInfo'
1162 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1163 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1164 }
Nate Begeman37efe672006-04-22 18:53:45 +00001165 }
1166}
1167
Evan Chengce4a70b2008-11-08 08:02:53 +00001168void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1169 unsigned Alignment) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001170 SavedBufferBegin = BufferBegin;
1171 SavedBufferEnd = BufferEnd;
1172 SavedCurBufferPtr = CurBufferPtr;
1173
Evan Chengce4a70b2008-11-08 08:02:53 +00001174 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001175 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001176}
1177
Evan Chengce4a70b2008-11-08 08:02:53 +00001178void *JITEmitter::finishGVStub(const GlobalValue* GV) {
Chris Lattner43b429b2006-05-02 18:27:26 +00001179 NumBytes += getCurrentPCOffset();
1180 std::swap(SavedBufferBegin, BufferBegin);
1181 BufferEnd = SavedBufferEnd;
1182 CurBufferPtr = SavedCurBufferPtr;
1183 return SavedBufferBegin;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001184}
1185
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001186// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1187// in the constant pool that was last emitted with the 'emitConstantPool'
1188// method.
1189//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001190uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001191 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001192 "Invalid ConstantPoolIndex!");
Evan Cheng5788d1a2008-12-10 02:32:19 +00001193 return (uintptr_t)ConstantPoolBase +
Chris Lattner239862c2006-02-09 04:49:59 +00001194 ConstantPool->getConstants()[ConstantNum].Offset;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001195}
1196
Nate Begeman37efe672006-04-22 18:53:45 +00001197// getJumpTableEntryAddress - Return the address of the JumpTable with index
1198// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1199//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001200uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001201 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1202 assert(Index < JT.size() && "Invalid jump table index!");
1203
1204 unsigned Offset = 0;
1205 unsigned EntrySize = JumpTable->getEntrySize();
1206
1207 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001208 Offset += JT[i].MBBs.size();
1209
1210 Offset *= EntrySize;
Nate Begeman37efe672006-04-22 18:53:45 +00001211
Evan Cheng5788d1a2008-12-10 02:32:19 +00001212 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001213}
1214
Chris Lattnere993cc22006-05-11 23:08:08 +00001215//===----------------------------------------------------------------------===//
1216// Public interface to this file
1217//===----------------------------------------------------------------------===//
1218
Chris Lattner9f2f1422007-12-06 01:08:09 +00001219MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1220 return new JITEmitter(jit, JMM);
Chris Lattnere993cc22006-05-11 23:08:08 +00001221}
1222
Misha Brukmand69c1e62003-07-28 19:09:06 +00001223// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +00001224// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +00001225// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1226// need to resolve function(s) that are being mis-codegenerated, so we need to
1227// resolve their addresses at runtime, and this is the way to do it.
1228extern "C" {
1229 void *getPointerToNamedFunction(const char *Name) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001230 if (Function *F = TheJIT->FindFunctionNamed(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +00001231 return TheJIT->getPointerToFunction(F);
1232 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +00001233 }
1234}
Chris Lattnere993cc22006-05-11 23:08:08 +00001235
1236// getPointerToFunctionOrStub - If the specified function has been
1237// code-gen'd, return a pointer to the function. If not, compile it, or use
1238// a stub to implement lazy compilation if available.
1239//
1240void *JIT::getPointerToFunctionOrStub(Function *F) {
1241 // If we have already code generated the function, just return the address.
1242 if (void *Addr = getPointerToGlobalIfAvailable(F))
1243 return Addr;
1244
Chris Lattnere7484012007-02-24 02:57:03 +00001245 // Get a stub if the target supports it.
Evan Chenga044dfc2008-08-20 00:28:12 +00001246 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1247 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Chris Lattnere7484012007-02-24 02:57:03 +00001248 return JE->getJITResolver().getFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001249}
1250
1251/// freeMachineCodeForFunction - release machine code memory for given Function.
1252///
1253void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesendd947ea2008-08-07 01:30:15 +00001254
Chris Lattnere993cc22006-05-11 23:08:08 +00001255 // Delete translation for this from the ExecutionEngine, so it will get
1256 // retranslated next time it is used.
Chris Lattner8ac66c12008-04-04 05:51:42 +00001257 void *OldPtr = updateGlobalMapping(F, 0);
1258
1259 if (OldPtr)
1260 RemoveFunctionFromSymbolTable(OldPtr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001261
1262 // Free the actual memory for the function body and related stuff.
Evan Chenga044dfc2008-08-20 00:28:12 +00001263 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1264 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001265}
1266