blob: 4b2f012eafb25ee7bdb8c39c7a4153ea03f0017a [file] [log] [blame]
Chris Lattnerc5753052004-11-22 22:00:25 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner996fe012002-12-24 00:01:05 +00009//
Chris Lattner6cf7a432004-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 Lattner996fe012002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattneree937c82003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Chris Lattner9bcae072003-12-20 01:46:27 +000016#include "JIT.h"
Jeffrey Yasskin27c66922009-10-20 18:13:21 +000017#include "llvm/ADT/DenseMap.h"
Evan Cheng00203152008-11-07 09:02:17 +000018#include "llvm/ADT/SmallPtrSet.h"
Nate Begeman18d85e72009-02-18 08:31:02 +000019#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/CodeGen/JITCodeEmitter.h"
22#include "llvm/CodeGen/MachineCodeInfo.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineJumpTableInfo.h"
26#include "llvm/CodeGen/MachineModuleInfo.h"
27#include "llvm/CodeGen/MachineRelocation.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ExecutionEngine/GenericValue.h"
29#include "llvm/ExecutionEngine/JITEventListener.h"
30#include "llvm/ExecutionEngine/JITMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000036#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000037#include "llvm/IR/ValueMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Support/Debug.h"
39#include "llvm/Support/Disassembler.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/ManagedStatic.h"
42#include "llvm/Support/Memory.h"
43#include "llvm/Support/MutexGuard.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Support/raw_ostream.h"
45#include "llvm/Target/TargetInstrInfo.h"
46#include "llvm/Target/TargetJITInfo.h"
47#include "llvm/Target/TargetMachine.h"
48#include "llvm/Target/TargetOptions.h"
Andrew Lenharth09402182005-07-29 23:40:16 +000049#include <algorithm>
Evan Chengd1c5c7f2008-11-05 23:44:08 +000050#ifndef NDEBUG
51#include <iomanip>
52#endif
Chris Lattnerc0e1b072003-12-08 08:06:28 +000053using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chris Lattnerc346ecd2006-12-19 22:43:32 +000055STATISTIC(NumBytes, "Number of bytes of machine code compiled");
56STATISTIC(NumRelos, "Number of relocations applied");
Reid Kleckner4b3a3562009-07-23 21:46:56 +000057STATISTIC(NumRetries, "Number of retries with more memory");
Chris Lattner60d815a2004-11-20 23:57:07 +000058
Andrew Lenharth09402182005-07-29 23:40:16 +000059
Jeffrey Yasskin65234292009-12-22 23:47:23 +000060// A declaration may stop being a declaration once it's fully read from bitcode.
61// This function returns true if F is fully read and is still a declaration.
62static bool isNonGhostDeclaration(const Function *F) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000063 return F->isDeclaration() && !F->isMaterializable();
Jeffrey Yasskin65234292009-12-22 23:47:23 +000064}
65
Chris Lattner60d815a2004-11-20 23:57:07 +000066//===----------------------------------------------------------------------===//
67// JIT lazy compilation code.
68//
69namespace {
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +000070 class JITEmitter;
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +000071 class JITResolverState;
72
73 template<typename ValueTy>
74 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
75 typedef JITResolverState *ExtraData;
76 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
Craig Toppera2886c22012-02-07 05:05:23 +000077 llvm_unreachable("The JIT doesn't know how to handle a"
78 " RAUW on a value it has emitted.");
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +000079 }
80 };
81
82 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
83 typedef JITResolverState *ExtraData;
84 static void onDelete(JITResolverState *JRS, Function *F);
85 };
86
Reid Spencer79876f52005-07-12 15:51:55 +000087 class JITResolverState {
Nick Lewyckyf44a5bf2009-04-27 05:09:44 +000088 public:
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +000089 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +000090 FunctionToLazyStubMapTy;
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +000091 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +000092 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
93 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
Nick Lewyckyf44a5bf2009-04-27 05:09:44 +000094 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spencer79876f52005-07-12 15:51:55 +000095 private:
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +000096 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
97 /// particular function so that we can reuse them if necessary.
98 FunctionToLazyStubMapTy FunctionToLazyStubMap;
Reid Spencer79876f52005-07-12 15:51:55 +000099
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000100 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
101 /// site corresponds to, and vice versa.
102 CallSiteToFunctionMapTy CallSiteToFunctionMap;
103 FunctionToCallSitesMapTy FunctionToCallSitesMap;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000104
Evan Cheng0d9db402008-11-10 01:52:24 +0000105 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000106 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckyf44a5bf2009-04-27 05:09:44 +0000107 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000108
Benjamin Kramerd0b767f2012-06-16 21:55:52 +0000109#ifndef NDEBUG
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000110 /// Instance of the JIT this ResolverState serves.
111 JIT *TheJIT;
Benjamin Kramerd0b767f2012-06-16 21:55:52 +0000112#endif
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000113
Reid Spencer79876f52005-07-12 15:51:55 +0000114 public:
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000115 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
Benjamin Kramerd0b767f2012-06-16 21:55:52 +0000116 FunctionToCallSitesMap(this) {
117#ifndef NDEBUG
118 TheJIT = jit;
119#endif
120 }
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000121
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000122 FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
123 const MutexGuard& locked) {
Reid Spencer79876f52005-07-12 15:51:55 +0000124 assert(locked.holds(TheJIT->lock));
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000125 return FunctionToLazyStubMap;
Reid Spencer79876f52005-07-12 15:51:55 +0000126 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000127
Jim Grosbachc91fa6d2011-03-16 01:21:55 +0000128 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
129 assert(lck.holds(TheJIT->lock));
Evan Cheng0d9db402008-11-10 01:52:24 +0000130 return GlobalToIndirectSymMap;
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000131 }
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000132
Jay Foad3b422a12011-04-13 12:46:01 +0000133 std::pair<void *, Function *> LookupFunctionFromCallSite(
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000134 const MutexGuard &locked, void *CallSite) const {
135 assert(locked.holds(TheJIT->lock));
136
Jim Grosbachc91fa6d2011-03-16 01:21:55 +0000137 // The address given to us for the stub may not be exactly right, it
138 // might be a little bit after the stub. As such, use upper_bound to
139 // find it.
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000140 CallSiteToFunctionMapTy::const_iterator I =
141 CallSiteToFunctionMap.upper_bound(CallSite);
142 assert(I != CallSiteToFunctionMap.begin() &&
143 "This is not a known call site!");
144 --I;
145 return *I;
146 }
147
148 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
149 assert(locked.holds(TheJIT->lock));
150
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000151 bool Inserted = CallSiteToFunctionMap.insert(
152 std::make_pair(CallSite, F)).second;
153 (void)Inserted;
154 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000155 FunctionToCallSitesMap[F].insert(CallSite);
156 }
157
Jeffrey Yasskin950e0fb2010-03-04 00:32:33 +0000158 void EraseAllCallSitesForPrelocked(Function *F);
159
160 // Erases _all_ call sites regardless of their function. This is used to
161 // unregister the stub addresses from the StubToResolverMap in
162 // ~JITResolver().
163 void EraseAllCallSitesPrelocked();
Reid Spencer79876f52005-07-12 15:51:55 +0000164 };
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000165
Chris Lattner60d815a2004-11-20 23:57:07 +0000166 /// JITResolver - Keep track of, and resolve, call sites for functions that
167 /// have not yet been compiled.
168 class JITResolver {
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000169 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000170 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
Nick Lewyckyf44a5bf2009-04-27 05:09:44 +0000171 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
172
Chris Lattner65f66382004-11-21 03:37:42 +0000173 /// LazyResolverFn - The target lazy resolver function that we actually
174 /// rewrite instructions to use.
175 TargetJITInfo::LazyResolverFn LazyResolverFn;
176
Reid Spencer79876f52005-07-12 15:51:55 +0000177 JITResolverState state;
Chris Lattner60d815a2004-11-20 23:57:07 +0000178
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000179 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
180 /// for external functions. TODO: Of course, external functions don't need
181 /// a lazy stub. It's actually here to make it more likely that far calls
182 /// succeed, but no single stub can guarantee that. I'll remove this in a
183 /// subsequent checkin when I actually fix far calls.
Chris Lattnered5189d2005-04-18 01:44:27 +0000184 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000185
Evan Cheng1fb8aed2009-03-13 07:51:59 +0000186 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000187 std::map<void*, unsigned> revGOTMap;
188 unsigned nextGOTIndex;
189
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000190 JITEmitter &JE;
191
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000192 /// Instance of JIT corresponding to this Resolver.
193 JIT *TheJIT;
194
Chris Lattner60d815a2004-11-20 23:57:07 +0000195 public:
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000196 explicit JITResolver(JIT &jit, JITEmitter &je)
Benjamin Kramerd0b767f2012-06-16 21:55:52 +0000197 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
Chris Lattner05858a92007-02-24 02:57:03 +0000198 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
Chris Lattner65f66382004-11-21 03:37:42 +0000199 }
Chris Lattner60d815a2004-11-20 23:57:07 +0000200
Jeffrey Yasskin950e0fb2010-03-04 00:32:33 +0000201 ~JITResolver();
202
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000203 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
204 /// lazy-compilation stub if it has already been created.
205 void *getLazyFunctionStubIfAvailable(Function *F);
Evan Chengbf9a0552008-11-13 21:50:50 +0000206
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000207 /// getLazyFunctionStub - This returns a pointer to a function's
208 /// lazy-compilation stub, creating one on demand as needed.
209 void *getLazyFunctionStub(Function *F);
Chris Lattner60d815a2004-11-20 23:57:07 +0000210
Chris Lattnered5189d2005-04-18 01:44:27 +0000211 /// getExternalFunctionStub - Return a stub for the function at the
212 /// specified address, created lazily on demand.
213 void *getExternalFunctionStub(void *FnAddr);
214
Evan Cheng0d9db402008-11-10 01:52:24 +0000215 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Cheng132de192008-11-05 01:50:32 +0000216 /// specified GV address.
Evan Cheng0d9db402008-11-10 01:52:24 +0000217 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000218
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000219 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000220 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000221 /// contents of the slots or the memory associated with the GOT.
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000222 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000223
Chris Lattner60d815a2004-11-20 23:57:07 +0000224 /// JITCompilerFn - This function is called to resolve a stub to a compiled
225 /// address. If the LLVM Function corresponding to the stub has not yet
226 /// been compiled, this function compiles it first.
227 static void *JITCompilerFn(void *Stub);
228 };
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000229
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000230 class StubToResolverMapTy {
231 /// Map a stub address to a specific instance of a JITResolver so that
232 /// lazily-compiled functions can find the right resolver to use.
233 ///
234 /// Guarded by Lock.
235 std::map<void*, JITResolver*> Map;
236
237 /// Guards Map from concurrent accesses.
238 mutable sys::Mutex Lock;
239
240 public:
241 /// Registers a Stub to be resolved by Resolver.
242 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
243 MutexGuard guard(Lock);
244 Map.insert(std::make_pair(Stub, Resolver));
245 }
246 /// Unregisters the Stub when it's invalidated.
247 void UnregisterStubResolver(void *Stub) {
248 MutexGuard guard(Lock);
249 Map.erase(Stub);
250 }
251 /// Returns the JITResolver instance that owns the Stub.
252 JITResolver *getResolverFromStub(void *Stub) const {
253 MutexGuard guard(Lock);
254 // The address given to us for the stub may not be exactly right, it might
255 // be a little bit after the stub. As such, use upper_bound to find it.
256 // This is the same trick as in LookupFunctionFromCallSite from
257 // JITResolverState.
258 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
259 assert(I != Map.begin() && "This is not a known stub!");
260 --I;
261 return I->second;
262 }
Jeffrey Yasskin950e0fb2010-03-04 00:32:33 +0000263 /// True if any stubs refer to the given resolver. Only used in an assert().
264 /// O(N)
265 bool ResolverHasStubs(JITResolver* Resolver) const {
266 MutexGuard guard(Lock);
267 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
268 E = Map.end(); I != E; ++I) {
269 if (I->second == Resolver)
270 return true;
271 }
272 return false;
273 }
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000274 };
275 /// This needs to be static so that a lazy call stub can access it with no
276 /// context except the address of the stub.
277 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
278
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000279 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
280 /// used to output functions to memory for execution.
281 class JITEmitter : public JITCodeEmitter {
282 JITMemoryManager *MemMgr;
283
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +0000284 // When outputting a function stub in the context of some other function, we
285 // save BufferBegin/BufferEnd/CurBufferPtr here.
286 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
287
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000288 // When reattempting to JIT a function after running out of space, we store
289 // the estimated size of the function we're trying to JIT here, so we can
290 // ask the memory manager for at least this much space. When we
291 // successfully emit the function, we reset this back to zero.
292 uintptr_t SizeEstimate;
293
294 /// Relocations - These are the relocations that the function needs, as
295 /// emitted.
296 std::vector<MachineRelocation> Relocations;
Eric Christophercb5e2272009-11-12 03:12:18 +0000297
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000298 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
299 /// It is filled in by the StartMachineBasicBlock callback and queried by
300 /// the getMachineBasicBlockAddress callback.
301 std::vector<uintptr_t> MBBLocations;
302
303 /// ConstantPool - The constant pool for the current function.
304 ///
305 MachineConstantPool *ConstantPool;
306
307 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
308 ///
309 void *ConstantPoolBase;
310
311 /// ConstPoolAddresses - Addresses of individual constant pool entries.
312 ///
313 SmallVector<uintptr_t, 8> ConstPoolAddresses;
314
315 /// JumpTable - The jump tables for the current function.
316 ///
317 MachineJumpTableInfo *JumpTable;
Eric Christophercb5e2272009-11-12 03:12:18 +0000318
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000319 /// JumpTableBase - A pointer to the first entry in the jump table.
320 ///
321 void *JumpTableBase;
322
323 /// Resolver - This contains info about the currently resolved functions.
324 JITResolver Resolver;
325
Eric Christophercb5e2272009-11-12 03:12:18 +0000326 /// LabelLocations - This vector is a mapping from Label ID's to their
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000327 /// address.
Chris Lattner34adc8d2010-03-14 01:41:15 +0000328 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000329
330 /// MMI - Machine module info for exception informations
331 MachineModuleInfo* MMI;
332
Eric Christophercb5e2272009-11-12 03:12:18 +0000333 // CurFn - The llvm function being emitted. Only valid during
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000334 // finishFunction().
335 const Function *CurFn;
336
337 /// Information about emitted code, which is passed to the
338 /// JITEventListeners. This is reset in startFunction and used in
339 /// finishFunction.
340 JITEvent_EmittedFunctionDetails EmissionDetails;
341
342 struct EmittedCode {
343 void *FunctionBody; // Beginning of the function's allocation.
344 void *Code; // The address the function's code actually starts at.
345 void *ExceptionTable;
346 EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
347 };
348 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
349 typedef JITEmitter *ExtraData;
350 static void onDelete(JITEmitter *, const Function*);
351 static void onRAUW(JITEmitter *, const Function*, const Function*);
352 };
353 ValueMap<const Function *, EmittedCode,
354 EmittedFunctionConfig> EmittedFunctions;
355
Nicolas Geoffray99bfbca2010-04-14 22:06:37 +0000356 DebugLoc PrevDL;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000357
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000358 /// Instance of the JIT
359 JIT *TheJIT;
360
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000361 public:
362 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
363 : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
Rafael Espindola9a383402013-05-07 20:53:59 +0000364 EmittedFunctions(this), TheJIT(&jit) {
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000365 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
366 if (jit.getJITInfo().needsGOT()) {
367 MemMgr->AllocateGOT();
David Greene85814ac2010-01-05 01:23:36 +0000368 DEBUG(dbgs() << "JIT is managing a GOT\n");
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000369 }
370
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000371 }
Eric Christophercb5e2272009-11-12 03:12:18 +0000372 ~JITEmitter() {
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000373 delete MemMgr;
374 }
375
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000376 JITResolver &getJITResolver() { return Resolver; }
377
Craig Topperb51ff602014-03-08 07:51:20 +0000378 void startFunction(MachineFunction &F) override;
379 bool finishFunction(MachineFunction &F) override;
Eric Christophercb5e2272009-11-12 03:12:18 +0000380
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000381 void emitConstantPool(MachineConstantPool *MCP);
382 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
383 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Eric Christophercb5e2272009-11-12 03:12:18 +0000384
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +0000385 void startGVStub(const GlobalValue* GV,
386 unsigned StubSize, unsigned Alignment = 1);
387 void startGVStub(void *Buffer, unsigned StubSize);
388 void finishGVStub();
Craig Topperb51ff602014-03-08 07:51:20 +0000389 void *allocIndirectGV(const GlobalValue *GV, const uint8_t *Buffer,
390 size_t Size, unsigned Alignment) override;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000391
392 /// allocateSpace - Reserves space in the current block if any, or
393 /// allocate a new one of the given size.
Craig Topperb51ff602014-03-08 07:51:20 +0000394 void *allocateSpace(uintptr_t Size, unsigned Alignment) override;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000395
396 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
397 /// this method does not allocate memory in the current output buffer,
398 /// because a global may live longer than the current function.
Craig Topperb51ff602014-03-08 07:51:20 +0000399 void *allocateGlobal(uintptr_t Size, unsigned Alignment) override;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000400
Craig Topperb51ff602014-03-08 07:51:20 +0000401 void addRelocation(const MachineRelocation &MR) override {
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000402 Relocations.push_back(MR);
403 }
Eric Christophercb5e2272009-11-12 03:12:18 +0000404
Craig Topperb51ff602014-03-08 07:51:20 +0000405 void StartMachineBasicBlock(MachineBasicBlock *MBB) override {
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000406 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
407 MBBLocations.resize((MBB->getNumber()+1)*2);
408 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Chris Lattnerb6df00c2010-07-11 23:07:28 +0000409 if (MBB->hasAddressTaken())
410 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
411 (void*)getCurrentPCValue());
David Greene85814ac2010-01-05 01:23:36 +0000412 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000413 << (void*) getCurrentPCValue() << "]\n");
414 }
415
Craig Topperb51ff602014-03-08 07:51:20 +0000416 uintptr_t getConstantPoolEntryAddress(unsigned Entry) const override;
417 uintptr_t getJumpTableEntryAddress(unsigned Entry) const override;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000418
Craig Topperb51ff602014-03-08 07:51:20 +0000419 uintptr_t
420 getMachineBasicBlockAddress(MachineBasicBlock *MBB) const override {
Eric Christophercb5e2272009-11-12 03:12:18 +0000421 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000422 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
423 return MBBLocations[MBB->getNumber()];
424 }
425
426 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
427 /// given function. Increase the minimum allocation size so that we get
428 /// more memory next time.
429 void retryWithMoreMemory(MachineFunction &F);
430
431 /// deallocateMemForFunction - Deallocate all memory for the specified
432 /// function body.
433 void deallocateMemForFunction(const Function *F);
434
Craig Topperb51ff602014-03-08 07:51:20 +0000435 void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) override;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000436
Craig Topperb51ff602014-03-08 07:51:20 +0000437 void emitLabel(MCSymbol *Label) override {
Chris Lattner34adc8d2010-03-14 01:41:15 +0000438 LabelLocations[Label] = getCurrentPCValue();
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000439 }
440
Craig Topperb51ff602014-03-08 07:51:20 +0000441 DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() override {
Bill Wendling929f3c02010-04-16 08:46:10 +0000442 return &LabelLocations;
443 }
444
Craig Topperb51ff602014-03-08 07:51:20 +0000445 uintptr_t getLabelAddress(MCSymbol *Label) const override {
Chris Lattner34adc8d2010-03-14 01:41:15 +0000446 assert(LabelLocations.count(Label) && "Label not emitted!");
447 return LabelLocations.find(Label)->second;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000448 }
Eric Christophercb5e2272009-11-12 03:12:18 +0000449
Craig Topperb51ff602014-03-08 07:51:20 +0000450 void setModuleInfo(MachineModuleInfo* Info) override {
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000451 MMI = Info;
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000452 }
453
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000454 private:
Jeffrey Yasskindb5f24c2009-11-07 08:51:52 +0000455 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
456 bool MayNeedFarStub);
457 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000458 };
Chris Lattner60d815a2004-11-20 23:57:07 +0000459}
460
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000461void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
Jeffrey Yasskin950e0fb2010-03-04 00:32:33 +0000462 JRS->EraseAllCallSitesForPrelocked(F);
463}
464
Jeffrey Yasskin950e0fb2010-03-04 00:32:33 +0000465void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
466 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
467 if (F2C == FunctionToCallSitesMap.end())
468 return;
469 StubToResolverMapTy &S2RMap = *StubToResolverMap;
470 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
471 E = F2C->second.end(); I != E; ++I) {
472 S2RMap.UnregisterStubResolver(*I);
473 bool Erased = CallSiteToFunctionMap.erase(*I);
474 (void)Erased;
475 assert(Erased && "Missing call site->function mapping");
476 }
477 FunctionToCallSitesMap.erase(F2C);
478}
479
480void JITResolverState::EraseAllCallSitesPrelocked() {
481 StubToResolverMapTy &S2RMap = *StubToResolverMap;
482 for (CallSiteToFunctionMapTy::const_iterator
483 I = CallSiteToFunctionMap.begin(),
484 E = CallSiteToFunctionMap.end(); I != E; ++I) {
485 S2RMap.UnregisterStubResolver(I->first);
486 }
487 CallSiteToFunctionMap.clear();
488 FunctionToCallSitesMap.clear();
489}
490
491JITResolver::~JITResolver() {
492 // No need to lock because we're in the destructor, and state isn't shared.
493 state.EraseAllCallSitesPrelocked();
494 assert(!StubToResolverMap->ResolverHasStubs(this) &&
495 "Resolver destroyed with stubs still alive.");
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000496}
497
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000498/// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
Evan Chengbf9a0552008-11-13 21:50:50 +0000499/// if it has already been created.
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000500void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
Evan Chengbf9a0552008-11-13 21:50:50 +0000501 MutexGuard locked(TheJIT->lock);
502
503 // If we already have a stub for this function, recycle it.
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000504 return state.getFunctionToLazyStubMap(locked).lookup(F);
Evan Chengbf9a0552008-11-13 21:50:50 +0000505}
506
Chris Lattner60d815a2004-11-20 23:57:07 +0000507/// getFunctionStub - This returns a pointer to a function stub, creating
508/// one on demand as needed.
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000509void *JITResolver::getLazyFunctionStub(Function *F) {
Reid Spencer79876f52005-07-12 15:51:55 +0000510 MutexGuard locked(TheJIT->lock);
511
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000512 // If we already have a lazy stub for this function, recycle it.
513 void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
Chris Lattner60d815a2004-11-20 23:57:07 +0000514 if (Stub) return Stub;
515
Jeffrey Yasskin4567db42009-10-27 20:30:28 +0000516 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
517 // must resolve the symbol now.
518 void *Actual = TheJIT->isCompilingLazily()
519 ? (void *)(intptr_t)LazyResolverFn : (void *)0;
520
Nate Begeman52b696c2009-03-07 06:41:19 +0000521 // If this is an external declaration, attempt to resolve the address now
522 // to place in the stub.
Jeffrey Yasskin65234292009-12-22 23:47:23 +0000523 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
Chris Lattner50c2e112004-11-22 07:24:43 +0000524 Actual = TheJIT->getPointerToFunction(F);
Misha Brukman10468d82005-04-21 22:55:34 +0000525
Dan Gohmand32ec012009-01-05 05:32:42 +0000526 // If we resolved the symbol to a null address (eg. a weak external)
Jeffrey Yasskin8483f122009-11-09 22:34:19 +0000527 // don't emit a stub. Return a null pointer to the application.
528 if (!Actual) return 0;
Dan Gohmand32ec012009-01-05 05:32:42 +0000529 }
530
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000531 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +0000532 JE.startGVStub(F, SL.Size, SL.Alignment);
Nate Begeman52b696c2009-03-07 06:41:19 +0000533 // Codegen a new stub, calling the lazy resolver or the actual address of the
534 // external function, if it was resolved.
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000535 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +0000536 JE.finishGVStub();
Chris Lattner50c2e112004-11-22 07:24:43 +0000537
Chris Lattner71819be2006-06-01 17:29:22 +0000538 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattner50c2e112004-11-22 07:24:43 +0000539 // If we are getting the stub for an external function, we really want the
540 // address of the stub in the GlobalAddressMap for the JIT, not the address
541 // of the external function.
542 TheJIT->updateGlobalMapping(F, Stub);
543 }
Chris Lattner60d815a2004-11-20 23:57:07 +0000544
David Greene85814ac2010-01-05 01:23:36 +0000545 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000546 << F->getName() << "'\n");
Chris Lattner9de8e222004-11-21 03:44:32 +0000547
Jeffrey Yasskin950e0fb2010-03-04 00:32:33 +0000548 if (TheJIT->isCompilingLazily()) {
549 // Register this JITResolver as the one corresponding to this call site so
550 // JITCompilerFn will be able to find it.
551 StubToResolverMap->RegisterStubResolver(Stub, this);
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000552
Jeffrey Yasskin950e0fb2010-03-04 00:32:33 +0000553 // Finally, keep track of the stub-to-Function mapping so that the
554 // JITCompilerFn knows which function to compile!
555 state.AddCallSite(locked, Stub, F);
556 } else if (!Actual) {
557 // If we are JIT'ing non-lazily but need to call a function that does not
558 // exist yet, add it to the JIT's work list so that we can fill in the
559 // stub address later.
560 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
561 "'Actual' should have been set above.");
562 TheJIT->addPendingFunction(F);
563 }
Jeffrey Yasskind162dba2009-10-13 21:32:57 +0000564
Chris Lattner60d815a2004-11-20 23:57:07 +0000565 return Stub;
566}
567
Evan Cheng0d9db402008-11-10 01:52:24 +0000568/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000569/// GV address.
Evan Cheng0d9db402008-11-10 01:52:24 +0000570void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000571 MutexGuard locked(TheJIT->lock);
572
573 // If we already have a stub for this global variable, recycle it.
Evan Cheng0d9db402008-11-10 01:52:24 +0000574 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
575 if (IndirectSym) return IndirectSym;
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000576
Evan Chengb172c662008-11-10 23:26:16 +0000577 // Otherwise, codegen a new indirect symbol.
Evan Cheng0d9db402008-11-10 01:52:24 +0000578 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000579 JE);
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000580
David Greene85814ac2010-01-05 01:23:36 +0000581 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000582 << "] for GV '" << GV->getName() << "'\n");
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000583
Evan Cheng0d9db402008-11-10 01:52:24 +0000584 return IndirectSym;
Evan Cheng49ff8ec2008-01-04 10:46:51 +0000585}
586
Chris Lattnered5189d2005-04-18 01:44:27 +0000587/// getExternalFunctionStub - Return a stub for the function at the
588/// specified address, created lazily on demand.
589void *JITResolver::getExternalFunctionStub(void *FnAddr) {
590 // If we already have a stub for this function, recycle it.
591 void *&Stub = ExternalFnToStubMap[FnAddr];
592 if (Stub) return Stub;
593
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000594 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +0000595 JE.startGVStub(0, SL.Size, SL.Alignment);
Jeffrey Yasskinba78dcd2009-11-07 00:00:10 +0000596 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +0000597 JE.finishGVStub();
Evan Chengf6acb342006-07-25 20:40:54 +0000598
David Greene85814ac2010-01-05 01:23:36 +0000599 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000600 << "] for external function at '" << FnAddr << "'\n");
Chris Lattnered5189d2005-04-18 01:44:27 +0000601 return Stub;
602}
603
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000604unsigned JITResolver::getGOTIndexForAddr(void* addr) {
605 unsigned idx = revGOTMap[addr];
606 if (!idx) {
607 idx = ++nextGOTIndex;
608 revGOTMap[addr] = idx;
David Greene85814ac2010-01-05 01:23:36 +0000609 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000610 << addr << "]\n");
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000611 }
612 return idx;
613}
Chris Lattnered5189d2005-04-18 01:44:27 +0000614
Chris Lattner60d815a2004-11-20 23:57:07 +0000615/// JITCompilerFn - This function is called when a lazy compilation stub has
616/// been entered. It looks up which function this stub corresponds to, compiles
617/// it if necessary, then returns the resultant function pointer.
618void *JITResolver::JITCompilerFn(void *Stub) {
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000619 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
620 assert(JR && "Unable to find the corresponding JITResolver to the call site");
Eric Christophercb5e2272009-11-12 03:12:18 +0000621
Nicolas Geoffray74056ae2008-10-03 07:27:08 +0000622 Function* F = 0;
623 void* ActualPtr = 0;
Misha Brukman10468d82005-04-21 22:55:34 +0000624
Nicolas Geoffray74056ae2008-10-03 07:27:08 +0000625 {
626 // Only lock for getting the Function. The call getPointerToFunction made
627 // in this function might trigger function materializing, which requires
628 // JIT lock to be unlocked.
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000629 MutexGuard locked(JR->TheJIT->lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000630
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000631 // The address given to us for the stub may not be exactly right, it might
632 // be a little bit after the stub. As such, use upper_bound to find it.
Jay Foad3b422a12011-04-13 12:46:01 +0000633 std::pair<void*, Function*> I =
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000634 JR->state.LookupFunctionFromCallSite(locked, Stub);
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000635 F = I.second;
636 ActualPtr = I.first;
Nicolas Geoffray74056ae2008-10-03 07:27:08 +0000637 }
Chris Lattner60d815a2004-11-20 23:57:07 +0000638
Evan Chenga1a3cc12007-06-30 00:10:37 +0000639 // If we have already code generated the function, just return the address.
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000640 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
Eric Christophercb5e2272009-11-12 03:12:18 +0000641
Evan Chenga1a3cc12007-06-30 00:10:37 +0000642 if (!Result) {
643 // Otherwise we don't have it, do lazy compilation now.
Eric Christophercb5e2272009-11-12 03:12:18 +0000644
Evan Chenga1a3cc12007-06-30 00:10:37 +0000645 // If lazy compilation is disabled, emit a useful error message and abort.
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000646 if (!JR->TheJIT->isCompilingLazily()) {
Jim Grosbachc91fa6d2011-03-16 01:21:55 +0000647 report_fatal_error("LLVM JIT requested to do lazy compilation of"
648 " function '"
Torok Edwinccb29cd2009-07-11 13:10:19 +0000649 + F->getName() + "' when lazy compiles are disabled!");
Evan Chenga1a3cc12007-06-30 00:10:37 +0000650 }
Eric Christophercb5e2272009-11-12 03:12:18 +0000651
David Greene85814ac2010-01-05 01:23:36 +0000652 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000653 << "' In stub ptr = " << Stub << " actual ptr = "
654 << ActualPtr << "\n");
Duncan Sandsa41634e2011-08-12 14:54:45 +0000655 (void)ActualPtr;
Chris Lattner60d815a2004-11-20 23:57:07 +0000656
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000657 Result = JR->TheJIT->getPointerToFunction(F);
Evan Chenga1a3cc12007-06-30 00:10:37 +0000658 }
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000659
660 // Reacquire the lock to update the GOT map.
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000661 MutexGuard locked(JR->TheJIT->lock);
Chris Lattner60d815a2004-11-20 23:57:07 +0000662
Jeffrey Yasskin7d2edad2009-10-19 18:49:59 +0000663 // We might like to remove the call site from the CallSiteToFunction map, but
664 // we can't do that! Multiple threads could be stuck, waiting to acquire the
665 // lock above. As soon as the 1st function finishes compiling the function,
666 // the next one will be released, and needs to be able to find the function it
667 // needs to call.
Chris Lattner60d815a2004-11-20 23:57:07 +0000668
669 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000670
Jeff Cohen546fd592005-07-30 18:33:25 +0000671 // What we will do is set the compiled function address to map to the
672 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000673 // if they see it still using the stub address.
674 // Note: this is done so the Resolver doesn't have to manage GOT memory
675 // Do this without allocating map space if the target isn't using a GOT
Jeffrey Yasskine0913882010-02-11 01:07:39 +0000676 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
677 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000678
Chris Lattner60d815a2004-11-20 23:57:07 +0000679 return Result;
680}
Chris Lattnerf26be842003-08-14 18:35:27 +0000681
Chris Lattner318d3ef2008-04-04 05:51:42 +0000682//===----------------------------------------------------------------------===//
Chris Lattnerc5753052004-11-22 22:00:25 +0000683// JITEmitter code.
Chris Lattner60d815a2004-11-20 23:57:07 +0000684//
Chris Lattnerc5753052004-11-22 22:00:25 +0000685void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
Jeffrey Yasskindb5f24c2009-11-07 08:51:52 +0000686 bool MayNeedFarStub) {
Nate Begeman18d85e72009-02-18 08:31:02 +0000687 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner60d815a2004-11-20 23:57:07 +0000688 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begeman18d85e72009-02-18 08:31:02 +0000689
Chris Lattner58ecfbd2008-06-25 20:21:35 +0000690 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Rafael Espindola65481d72014-03-26 06:14:40 +0000691 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Chris Lattner60d815a2004-11-20 23:57:07 +0000692
693 // If we have already compiled the function, return a pointer to its body.
694 Function *F = cast<Function>(V);
Eric Christophercb5e2272009-11-12 03:12:18 +0000695
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000696 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
Eric Christophercb5e2272009-11-12 03:12:18 +0000697 if (FnStub) {
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +0000698 // Return the function stub if it's already created. We do this first so
699 // that we're returning the same address for the function as any previous
700 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
701 // close enough to call.
Eric Christophercb5e2272009-11-12 03:12:18 +0000702 return FnStub;
Nate Begeman359df742009-03-05 06:34:37 +0000703 }
Eric Christophercb5e2272009-11-12 03:12:18 +0000704
Jeffrey Yasskin34fb6832009-11-19 23:42:58 +0000705 // If we know the target can handle arbitrary-distance calls, try to
706 // return a direct pointer.
707 if (!MayNeedFarStub) {
708 // If we have code, go ahead and return that.
709 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
710 if (ResultPtr) return ResultPtr;
Chris Lattner60d815a2004-11-20 23:57:07 +0000711
Jeffrey Yasskin34fb6832009-11-19 23:42:58 +0000712 // If this is an external function pointer, we can force the JIT to
713 // 'compile' it, which really just adds it to the map.
Jeffrey Yasskin65234292009-12-22 23:47:23 +0000714 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
Jeffrey Yasskin34fb6832009-11-19 23:42:58 +0000715 return TheJIT->getPointerToFunction(F);
716 }
Chris Lattner50c2e112004-11-22 07:24:43 +0000717
Jeffrey Yasskinc3b7d1e2010-03-04 19:45:09 +0000718 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
719 // so. Note that it's possible to return null from getLazyFunctionStub in the
720 // case of a weak extern that fails to resolve.
721 return Resolver.getLazyFunctionStub(F);
Chris Lattner60d815a2004-11-20 23:57:07 +0000722}
723
Jeffrey Yasskindb5f24c2009-11-07 08:51:52 +0000724void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
Nate Begeman359df742009-03-05 06:34:37 +0000725 // Make sure GV is emitted first, and create a stub containing the fully
726 // resolved address.
Jeffrey Yasskindb5f24c2009-11-07 08:51:52 +0000727 void *GVAddress = getPointerToGlobal(V, Reference, false);
Nate Begeman359df742009-03-05 06:34:37 +0000728 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
Nate Begeman359df742009-03-05 06:34:37 +0000729 return StubAddr;
730}
731
Devang Pateleb43b172009-10-06 03:04:58 +0000732void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
Chris Lattner915c5f92010-04-02 19:42:39 +0000733 if (DL.isUnknown()) return;
734 if (!BeforePrintingInsn) return;
Jim Grosbachc91fa6d2011-03-16 01:21:55 +0000735
Chris Lattner8f3adc92010-07-22 21:17:55 +0000736 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
Nicolas Geoffray99bfbca2010-04-14 22:06:37 +0000737
738 if (DL.getScope(Context) != 0 && PrevDL != DL) {
Chris Lattner915c5f92010-04-02 19:42:39 +0000739 JITEvent_EmittedFunctionDetails::LineStart NextLine;
740 NextLine.Address = getCurrentPCValue();
741 NextLine.Loc = DL;
742 EmissionDetails.LineStarts.push_back(NextLine);
Jeffrey Yasskinefad8e42009-07-16 21:07:26 +0000743 }
Chris Lattner915c5f92010-04-02 19:42:39 +0000744
Nicolas Geoffray99bfbca2010-04-14 22:06:37 +0000745 PrevDL = DL;
Jeffrey Yasskinefad8e42009-07-16 21:07:26 +0000746}
747
Evan Cheng1fb8aed2009-03-13 07:51:59 +0000748static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000749 const DataLayout *TD) {
Nicolas Geoffray85a9f192008-04-18 20:59:31 +0000750 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
751 if (Constants.empty()) return 0;
752
Evan Cheng1fb8aed2009-03-13 07:51:59 +0000753 unsigned Size = 0;
754 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
755 MachineConstantPoolEntry CPE = Constants[i];
756 unsigned AlignMask = CPE.getAlignment() - 1;
757 Size = (Size + AlignMask) & ~AlignMask;
Chris Lattner229907c2011-07-18 04:54:35 +0000758 Type *Ty = CPE.getType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000759 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1fb8aed2009-03-13 07:51:59 +0000760 }
Nicolas Geoffray85a9f192008-04-18 20:59:31 +0000761 return Size;
762}
763
Chris Lattnerc5753052004-11-22 22:00:25 +0000764void JITEmitter::startFunction(MachineFunction &F) {
David Greene85814ac2010-01-05 01:23:36 +0000765 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
Craig Toppera538d832012-08-22 06:07:19 +0000766 << F.getName() << "\n");
Evan Cheng972fd1a2008-11-06 17:46:04 +0000767
Nicolas Geoffray85a9f192008-04-18 20:59:31 +0000768 uintptr_t ActualSize = 0;
Jim Grosbachb22ef712008-10-03 16:17:20 +0000769 // Set the memory writable, if it's not already
770 MemMgr->setMemoryWritable();
Jim Grosbachc91fa6d2011-03-16 01:21:55 +0000771
Chris Lattner8f3adc92010-07-22 21:17:55 +0000772 if (SizeEstimate > 0) {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000773 // SizeEstimate will be non-zero on reallocation attempts.
774 ActualSize = SizeEstimate;
Nicolas Geoffray85a9f192008-04-18 20:59:31 +0000775 }
776
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000777 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
778 ActualSize);
Chris Lattner873ef132006-05-11 23:08:08 +0000779 BufferEnd = BufferBegin+ActualSize;
Jeffrey Yasskin27c66922009-10-20 18:13:21 +0000780 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
781
Evan Chenge03ca9b2006-11-16 20:04:54 +0000782 // Ensure the constant pool/jump table info is at least 4-byte aligned.
783 emitAlignment(16);
784
Chris Lattnerb8065a92006-05-02 23:22:24 +0000785 emitConstantPool(F.getConstantPool());
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000786 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
787 initJumpTableInfo(MJTI);
Chris Lattnerb8065a92006-05-02 23:22:24 +0000788
789 // About to start emitting the machine code for the function.
Chris Lattner37c39b92006-05-03 01:03:20 +0000790 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerb8065a92006-05-02 23:22:24 +0000791 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Jeffrey Yasskinbf43f652009-10-27 00:03:05 +0000792 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
Evan Chengf6acb342006-07-25 20:40:54 +0000793
Chris Lattner1d8ee1f2006-05-03 17:10:41 +0000794 MBBLocations.clear();
Jeffrey Yasskinefad8e42009-07-16 21:07:26 +0000795
796 EmissionDetails.MF = &F;
797 EmissionDetails.LineStarts.clear();
Chris Lattner996fe012002-12-24 00:01:05 +0000798}
799
Chris Lattnerc9aa3712006-05-02 18:27:26 +0000800bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattner873ef132006-05-11 23:08:08 +0000801 if (CurBufferPtr == BufferEnd) {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000802 // We must call endFunctionBody before retrying, because
803 // deallocateMemForFunction requires it.
804 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
805 retryWithMoreMemory(F);
806 return true;
Chris Lattner873ef132006-05-11 23:08:08 +0000807 }
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000808
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000809 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
810 emitJumpTableInfo(MJTI);
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000811
Chris Lattnere7962662006-06-16 18:09:26 +0000812 // FnStart is the start of the text, not the start of the constant pool and
813 // other per-function data.
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000814 uint8_t *FnStart =
815 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattner996fe012002-12-24 00:01:05 +0000816
Argyrios Kyrtzidis30481e22009-04-30 23:01:58 +0000817 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +0000818 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis30481e22009-04-30 23:01:58 +0000819
Chris Lattner6cf7a432004-11-20 03:46:14 +0000820 if (!Relocations.empty()) {
Nate Begeman359df742009-03-05 06:34:37 +0000821 CurFn = F.getFunction();
Chris Lattner05732c82005-07-20 16:29:20 +0000822 NumRelos += Relocations.size();
823
Chris Lattner6cf7a432004-11-20 03:46:14 +0000824 // Resolve the relocations to concrete pointers.
825 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
826 MachineRelocation &MR = Relocations[i];
Evan Cheng3a9aead2008-11-03 07:14:02 +0000827 void *ResultPtr = 0;
Evan Cheng4421a112008-10-29 23:54:46 +0000828 if (!MR.letTargetResolve()) {
Evan Cheng1b889b12008-11-08 07:37:34 +0000829 if (MR.isExternalSymbol()) {
Dan Gohmand32ec012009-01-05 05:32:42 +0000830 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
831 false);
David Greene85814ac2010-01-05 01:23:36 +0000832 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Eric Christophercb5e2272009-11-12 03:12:18 +0000833 << ResultPtr << "]\n");
Misha Brukman10468d82005-04-21 22:55:34 +0000834
Evan Cheng4421a112008-10-29 23:54:46 +0000835 // If the target REALLY wants a stub for this function, emit it now.
Jeffrey Yasskindb5f24c2009-11-07 08:51:52 +0000836 if (MR.mayNeedFarStub()) {
Jeffrey Yasskin8483f122009-11-09 22:34:19 +0000837 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
Nate Begeman664cf272009-03-11 07:03:43 +0000838 }
Evan Cheng4421a112008-10-29 23:54:46 +0000839 } else if (MR.isGlobalValue()) {
840 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
841 BufferBegin+MR.getMachineCodeOffset(),
Jeffrey Yasskindb5f24c2009-11-07 08:51:52 +0000842 MR.mayNeedFarStub());
Evan Cheng0d9db402008-11-10 01:52:24 +0000843 } else if (MR.isIndirectSymbol()) {
Jeffrey Yasskindb5f24c2009-11-07 08:51:52 +0000844 ResultPtr = getPointerToGVIndirectSym(
845 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
Evan Cheng4421a112008-10-29 23:54:46 +0000846 } else if (MR.isBasicBlock()) {
847 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
848 } else if (MR.isConstantPoolIndex()) {
Jim Grosbachc91fa6d2011-03-16 01:21:55 +0000849 ResultPtr =
850 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Evan Cheng4421a112008-10-29 23:54:46 +0000851 } else {
852 assert(MR.isJumpTableIndex());
853 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
854 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000855
Evan Cheng4421a112008-10-29 23:54:46 +0000856 MR.setResultPointer(ResultPtr);
857 }
Andrew Lenharth940b07c2005-07-22 20:48:12 +0000858
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000859 // if we are managing the GOT and the relocation wants an index,
860 // give it one
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000861 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattner05858a92007-02-24 02:57:03 +0000862 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000863 MR.setGOTIndex(idx);
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000864 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
David Greene85814ac2010-01-05 01:23:36 +0000865 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000866 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
867 << "\n");
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000868 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000869 }
Andrew Lenharth940b07c2005-07-22 20:48:12 +0000870 }
Chris Lattner6cf7a432004-11-20 03:46:14 +0000871 }
872
Nate Begeman359df742009-03-05 06:34:37 +0000873 CurFn = 0;
Chris Lattnerc9aa3712006-05-02 18:27:26 +0000874 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000875 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner6cf7a432004-11-20 03:46:14 +0000876 }
877
Chris Lattner005d7172006-05-03 18:55:56 +0000878 // Update the GOT entry for F to point to the new code.
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000879 if (MemMgr->isManagingGOT()) {
Chris Lattner05858a92007-02-24 02:57:03 +0000880 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000881 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
David Greene85814ac2010-01-05 01:23:36 +0000882 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000883 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
884 << "\n");
Chris Lattner55d8c3f2007-12-05 23:39:57 +0000885 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth3444cf52005-07-28 12:44:13 +0000886 }
887 }
888
Argyrios Kyrtzidis30481e22009-04-30 23:01:58 +0000889 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
890 // global variables that were referenced in the relocations.
891 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng0b773192008-12-10 02:32:19 +0000892
893 if (CurBufferPtr == BufferEnd) {
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000894 retryWithMoreMemory(F);
895 return true;
896 } else {
897 // Now that we've succeeded in emitting the function, reset the
898 // SizeEstimate back down to zero.
899 SizeEstimate = 0;
Evan Cheng0b773192008-12-10 02:32:19 +0000900 }
901
Nuno Lopes94844e22008-10-21 11:42:16 +0000902 BufferBegin = CurBufferPtr = 0;
903 NumBytes += FnEnd-FnStart;
904
Evan Chengf6acb342006-07-25 20:40:54 +0000905 // Invalidate the icache if necessary.
Chris Lattnerd3406fc2008-06-25 17:18:44 +0000906 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000907
Jeffrey Yasskin0b08f3d2009-06-25 02:04:04 +0000908 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
Jeffrey Yasskinefad8e42009-07-16 21:07:26 +0000909 EmissionDetails);
Evan Chengf6acb342006-07-25 20:40:54 +0000910
Nicolas Geoffray99bfbca2010-04-14 22:06:37 +0000911 // Reset the previous debug location.
912 PrevDL = DebugLoc();
913
David Greene85814ac2010-01-05 01:23:36 +0000914 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
Craig Toppera538d832012-08-22 06:07:19 +0000915 << "] Function: " << F.getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000916 << ": " << (FnEnd-FnStart) << " bytes of text, "
917 << Relocations.size() << " relocations\n");
Argyrios Kyrtzidisc65c5252009-05-18 21:06:40 +0000918
Chris Lattner6cf7a432004-11-20 03:46:14 +0000919 Relocations.clear();
Evan Cheng1fb8aed2009-03-13 07:51:59 +0000920 ConstPoolAddresses.clear();
Anton Korobeynikov3e956972007-01-19 17:25:17 +0000921
Evan Cheng5cc53c32008-09-18 07:54:21 +0000922 // Mark code region readable and executable if it's not so already.
Jim Grosbachb22ef712008-10-03 16:17:20 +0000923 MemMgr->setMemoryExecutable();
Evan Cheng5cc53c32008-09-18 07:54:21 +0000924
Bill Wendling47d74202010-04-18 00:52:08 +0000925 DEBUG({
926 if (sys::hasDisassembler()) {
927 dbgs() << "JIT: Disassembled code:\n";
928 dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
929 (uintptr_t)FnStart);
930 } else {
931 dbgs() << "JIT: Binary code:\n";
932 uint8_t* q = FnStart;
933 for (int i = 0; q < FnEnd; q += 4, ++i) {
934 if (i == 4)
935 i = 0;
936 if (i == 0)
937 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
938 bool Done = false;
939 for (int j = 3; j >= 0; --j) {
940 if (q + j >= FnEnd)
941 Done = true;
942 else
943 dbgs() << (unsigned short)q[j];
944 }
945 if (Done)
946 break;
947 dbgs() << ' ';
948 if (i == 3)
949 dbgs() << '\n';
Evan Chenge4df8752008-11-12 08:22:43 +0000950 }
Bill Wendling47d74202010-04-18 00:52:08 +0000951 dbgs()<< '\n';
Evan Chengd1c5c7f2008-11-05 23:44:08 +0000952 }
Bill Wendling47d74202010-04-18 00:52:08 +0000953 });
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000954
Evan Cheng52b18122008-09-02 08:14:01 +0000955 if (MMI)
956 MMI->EndFunction();
Eric Christophercb5e2272009-11-12 03:12:18 +0000957
Chris Lattnerc9aa3712006-05-02 18:27:26 +0000958 return false;
Chris Lattner996fe012002-12-24 00:01:05 +0000959}
960
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000961void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
David Greene85814ac2010-01-05 01:23:36 +0000962 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000963 Relocations.clear(); // Clear the old relocations or we'll reapply them.
964 ConstPoolAddresses.clear();
965 ++NumRetries;
966 deallocateMemForFunction(F.getFunction());
967 // Try again with at least twice as much free space.
968 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
Chris Lattnerb6df00c2010-07-11 23:07:28 +0000969
970 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
971 if (MBB->hasAddressTaken())
972 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
973 }
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000974}
975
Nate Begeman359df742009-03-05 06:34:37 +0000976/// deallocateMemForFunction - Deallocate all memory for the specified
977/// function body. Also drop any references the function has to stubs.
Jeffrey Yasskinbf43f652009-10-27 00:03:05 +0000978/// May be called while the Function is being destroyed inside ~Value().
Reid Kleckner4b3a3562009-07-23 21:46:56 +0000979void JITEmitter::deallocateMemForFunction(const Function *F) {
Jeffrey Yasskinbf43f652009-10-27 00:03:05 +0000980 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
981 Emitted = EmittedFunctions.find(F);
Jeffrey Yasskin27c66922009-10-20 18:13:21 +0000982 if (Emitted != EmittedFunctions.end()) {
983 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
Jeffrey Yasskinbf43f652009-10-27 00:03:05 +0000984 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
985
Jeffrey Yasskin27c66922009-10-20 18:13:21 +0000986 EmittedFunctions.erase(Emitted);
987 }
Nate Begeman359df742009-03-05 06:34:37 +0000988}
989
990
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000991void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopes94844e22008-10-21 11:42:16 +0000992 if (BufferBegin)
Bruno Cardoso Lopesa194c3a2009-05-30 20:51:52 +0000993 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopes94844e22008-10-21 11:42:16 +0000994
995 // create a new memory block if there is no active one.
996 // care must be taken so that BufferBegin is invalidated when a
997 // block is trimmed
998 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
999 BufferEnd = BufferBegin+Size;
1000 return CurBufferPtr;
1001}
1002
Nick Lewycky50f02cb2011-12-02 22:16:29 +00001003void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
Jeffrey Yasskin70415d92009-07-08 21:59:57 +00001004 // Delegate this call through the memory manager.
1005 return MemMgr->allocateGlobal(Size, Alignment);
1006}
1007
Chris Lattnerc5753052004-11-22 22:00:25 +00001008void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng00203152008-11-07 09:02:17 +00001009 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach25896042008-10-30 23:44:39 +00001010 return;
Evan Cheng00203152008-11-07 09:02:17 +00001011
Chris Lattnerba972642006-02-09 04:22:52 +00001012 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner98e72b42003-11-30 04:23:21 +00001013 if (Constants.empty()) return;
1014
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001015 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
Evan Cheng1fb8aed2009-03-13 07:51:59 +00001016 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng213ea6b2008-04-12 00:22:01 +00001017 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner729ffe92006-02-09 04:49:59 +00001018 ConstantPool = MCP;
Chris Lattnerb8065a92006-05-02 23:22:24 +00001019
1020 if (ConstantPoolBase == 0) return; // Buffer overflow.
1021
David Greene85814ac2010-01-05 01:23:36 +00001022 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001023 << "] (size: " << Size << ", alignment: " << Align << ")\n");
Evan Cheng213ea6b2008-04-12 00:22:01 +00001024
Chris Lattner729ffe92006-02-09 04:49:59 +00001025 // Initialize the memory for all of the constant pool entries.
Evan Cheng1fb8aed2009-03-13 07:51:59 +00001026 unsigned Offset = 0;
Chris Lattnerf6190822006-02-09 04:46:04 +00001027 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1fb8aed2009-03-13 07:51:59 +00001028 MachineConstantPoolEntry CPE = Constants[i];
1029 unsigned AlignMask = CPE.getAlignment() - 1;
1030 Offset = (Offset + AlignMask) & ~AlignMask;
1031
1032 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1033 ConstPoolAddresses.push_back(CAddr);
1034 if (CPE.isMachineConstantPoolEntry()) {
Evan Cheng3228e752006-09-12 20:59:59 +00001035 // FIXME: add support to lower machine constant pool values into bytes!
Chris Lattner2104b8d2010-04-07 22:58:41 +00001036 report_fatal_error("Initialize memory with machine specific constant pool"
Torok Edwinccb29cd2009-07-11 13:10:19 +00001037 "entry has not been implemented!");
Evan Cheng3228e752006-09-12 20:59:59 +00001038 }
Evan Cheng1fb8aed2009-03-13 07:51:59 +00001039 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
David Greene85814ac2010-01-05 01:23:36 +00001040 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1041 dbgs().write_hex(CAddr) << "]\n");
Evan Cheng1fb8aed2009-03-13 07:51:59 +00001042
Chris Lattner229907c2011-07-18 04:54:35 +00001043 Type *Ty = CPE.Val.ConstVal->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001044 Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
Chris Lattner4ba3bbb2003-01-13 01:00:12 +00001045 }
1046}
1047
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001048void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng00203152008-11-07 09:02:17 +00001049 if (TheJIT->getJITInfo().hasCustomJumpTables())
1050 return;
Richard Osborne6d3e92d2010-03-11 14:58:16 +00001051 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1052 return;
Evan Cheng00203152008-11-07 09:02:17 +00001053
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001054 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1055 if (JT.empty()) return;
Eric Christophercb5e2272009-11-12 03:12:18 +00001056
Chris Lattnerb8065a92006-05-02 23:22:24 +00001057 unsigned NumEntries = 0;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001058 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerb8065a92006-05-02 23:22:24 +00001059 NumEntries += JT[i].MBBs.size();
1060
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001061 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
Chris Lattnerb8065a92006-05-02 23:22:24 +00001062
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001063 // Just allocate space for all the jump tables now. We will fix up the actual
1064 // MBB entries in the tables after we emit the code for each block, since then
1065 // we will know the final locations of the MBBs in memory.
1066 JumpTable = MJTI;
Chris Lattnerb6db2c62010-01-25 23:26:13 +00001067 JumpTableBase = allocateSpace(NumEntries * EntrySize,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001068 MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001069}
1070
Jim Laskey39589552006-12-14 22:53:42 +00001071void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng00203152008-11-07 09:02:17 +00001072 if (TheJIT->getJITInfo().hasCustomJumpTables())
1073 return;
1074
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001075 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Chris Lattnerb8065a92006-05-02 23:22:24 +00001076 if (JT.empty() || JumpTableBase == 0) return;
Eric Christophercb5e2272009-11-12 03:12:18 +00001077
Jim Grosbachc91fa6d2011-03-16 01:21:55 +00001078
Chris Lattner7a260702010-01-26 03:47:15 +00001079 switch (MJTI->getEntryKind()) {
Richard Osborne6d3e92d2010-03-11 14:58:16 +00001080 case MachineJumpTableInfo::EK_Inline:
1081 return;
Chris Lattner7a260702010-01-26 03:47:15 +00001082 case MachineJumpTableInfo::EK_BlockAddress: {
1083 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1084 // .word LBB123
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001085 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
Chris Lattner7a260702010-01-26 03:47:15 +00001086 "Cross JIT'ing?");
Jim Grosbachc91fa6d2011-03-16 01:21:55 +00001087
Chris Lattner7a260702010-01-26 03:47:15 +00001088 // For each jump table, map each target in the jump table to the address of
1089 // an emitted MachineBasicBlock.
1090 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
Jim Grosbachc91fa6d2011-03-16 01:21:55 +00001091
Chris Lattner7a260702010-01-26 03:47:15 +00001092 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1093 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1094 // Store the address of the basic block for this jump table slot in the
1095 // memory we allocated for the jump table in 'initJumpTableInfo'
1096 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1097 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1098 }
1099 break;
1100 }
Jim Grosbachc91fa6d2011-03-16 01:21:55 +00001101
Chris Lattner5fc41602010-01-26 04:05:28 +00001102 case MachineJumpTableInfo::EK_Custom32:
Chris Lattner7a260702010-01-26 03:47:15 +00001103 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1104 case MachineJumpTableInfo::EK_LabelDifference32: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001105 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
Jim Laskey70323a82006-12-14 19:17:33 +00001106 // For each jump table, place the offset from the beginning of the table
1107 // to the target address.
1108 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner0574e472006-05-03 00:13:06 +00001109
Jim Laskey70323a82006-12-14 19:17:33 +00001110 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1111 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1112 // Store the offset of the basic block for this jump table slot in the
1113 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng0b773192008-12-10 02:32:19 +00001114 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng880b0802008-01-05 02:26:58 +00001115 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng0b773192008-12-10 02:32:19 +00001116 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Chris Lattner7a260702010-01-26 03:47:15 +00001117 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
Evan Cheng880b0802008-01-05 02:26:58 +00001118 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1119 }
Jim Laskey70323a82006-12-14 19:17:33 +00001120 }
Chris Lattner7a260702010-01-26 03:47:15 +00001121 break;
1122 }
Akira Hatanakaf0b08442012-02-03 04:33:00 +00001123 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
Craig Toppera2886c22012-02-07 05:05:23 +00001124 llvm_unreachable(
Akira Hatanakaf0b08442012-02-03 04:33:00 +00001125 "JT Info emission not implemented for GPRel64BlockAddress yet.");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001126 }
1127}
1128
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +00001129void JITEmitter::startGVStub(const GlobalValue* GV,
Jeffrey Yasskin19b48372009-11-23 22:49:00 +00001130 unsigned StubSize, unsigned Alignment) {
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +00001131 SavedBufferBegin = BufferBegin;
1132 SavedBufferEnd = BufferEnd;
1133 SavedCurBufferPtr = CurBufferPtr;
Eric Christophercb5e2272009-11-12 03:12:18 +00001134
Evan Chengb31a7172008-11-08 08:02:53 +00001135 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattnerc9aa3712006-05-02 18:27:26 +00001136 BufferEnd = BufferBegin+StubSize+1;
Chris Lattnerfdbd98b2003-05-09 03:30:07 +00001137}
1138
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +00001139void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1140 SavedBufferBegin = BufferBegin;
1141 SavedBufferEnd = BufferEnd;
1142 SavedCurBufferPtr = CurBufferPtr;
Eric Christophercb5e2272009-11-12 03:12:18 +00001143
Bruno Cardoso Lopes8a1be5e2009-06-04 00:15:51 +00001144 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begeman18d85e72009-02-18 08:31:02 +00001145 BufferEnd = BufferBegin+StubSize+1;
1146}
1147
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +00001148void JITEmitter::finishGVStub() {
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +00001149 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
Chris Lattnerc9aa3712006-05-02 18:27:26 +00001150 NumBytes += getCurrentPCOffset();
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +00001151 BufferBegin = SavedBufferBegin;
1152 BufferEnd = SavedBufferEnd;
1153 CurBufferPtr = SavedCurBufferPtr;
1154}
1155
1156void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1157 const uint8_t *Buffer, size_t Size,
1158 unsigned Alignment) {
1159 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1160 memcpy(IndGV, Buffer, Size);
1161 return IndGV;
Chris Lattner6b689e32003-06-01 23:24:36 +00001162}
1163
Chris Lattner6b689e32003-06-01 23:24:36 +00001164// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1165// in the constant pool that was last emitted with the 'emitConstantPool'
1166// method.
1167//
Evan Cheng0b773192008-12-10 02:32:19 +00001168uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner729ffe92006-02-09 04:49:59 +00001169 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman5191b4b2005-04-22 04:08:30 +00001170 "Invalid ConstantPoolIndex!");
Evan Cheng1fb8aed2009-03-13 07:51:59 +00001171 return ConstPoolAddresses[ConstantNum];
Chris Lattner6b689e32003-06-01 23:24:36 +00001172}
1173
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001174// getJumpTableEntryAddress - Return the address of the JumpTable with index
1175// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1176//
Evan Cheng0b773192008-12-10 02:32:19 +00001177uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001178 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1179 assert(Index < JT.size() && "Invalid jump table index!");
Eric Christophercb5e2272009-11-12 03:12:18 +00001180
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001181 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
Eric Christophercb5e2272009-11-12 03:12:18 +00001182
Chris Lattnerb6db2c62010-01-25 23:26:13 +00001183 unsigned Offset = 0;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001184 for (unsigned i = 0; i < Index; ++i)
Jim Laskey70323a82006-12-14 19:17:33 +00001185 Offset += JT[i].MBBs.size();
Eric Christophercb5e2272009-11-12 03:12:18 +00001186
Jim Laskey70323a82006-12-14 19:17:33 +00001187 Offset *= EntrySize;
Eric Christophercb5e2272009-11-12 03:12:18 +00001188
Evan Cheng0b773192008-12-10 02:32:19 +00001189 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001190}
1191
Jeffrey Yasskinbf43f652009-10-27 00:03:05 +00001192void JITEmitter::EmittedFunctionConfig::onDelete(
1193 JITEmitter *Emitter, const Function *F) {
1194 Emitter->deallocateMemForFunction(F);
1195}
1196void JITEmitter::EmittedFunctionConfig::onRAUW(
1197 JITEmitter *, const Function*, const Function*) {
1198 llvm_unreachable("The JIT doesn't know how to handle a"
1199 " RAUW on a value it has emitted.");
1200}
1201
1202
Chris Lattner873ef132006-05-11 23:08:08 +00001203//===----------------------------------------------------------------------===//
1204// Public interface to this file
1205//===----------------------------------------------------------------------===//
1206
Reid Kleckner9a10db82009-09-20 23:52:43 +00001207JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1208 TargetMachine &tm) {
1209 return new JITEmitter(jit, JMM, tm);
Chris Lattner873ef132006-05-11 23:08:08 +00001210}
1211
Chris Lattner873ef132006-05-11 23:08:08 +00001212// getPointerToFunctionOrStub - If the specified function has been
1213// code-gen'd, return a pointer to the function. If not, compile it, or use
1214// a stub to implement lazy compilation if available.
1215//
1216void *JIT::getPointerToFunctionOrStub(Function *F) {
1217 // If we have already code generated the function, just return the address.
1218 if (void *Addr = getPointerToGlobalIfAvailable(F))
1219 return Addr;
Eric Christophercb5e2272009-11-12 03:12:18 +00001220
Chris Lattner05858a92007-02-24 02:57:03 +00001221 // Get a stub if the target supports it.
Sean Silvabead14e2012-10-11 23:30:38 +00001222 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +00001223 return JE->getJITResolver().getLazyFunctionStub(F);
Chris Lattner873ef132006-05-11 23:08:08 +00001224}
1225
Nate Begeman18d85e72009-02-18 08:31:02 +00001226void JIT::updateFunctionStub(Function *F) {
1227 // Get the empty stub we generated earlier.
Sean Silvabead14e2012-10-11 23:30:38 +00001228 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +00001229 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1230 void *Addr = getPointerToGlobalIfAvailable(F);
Jeffrey Yasskin2b73a4e2009-12-17 21:35:29 +00001231 assert(Addr != Stub && "Function must have non-stub address to be updated.");
Nate Begeman18d85e72009-02-18 08:31:02 +00001232
1233 // Tell the target jit info to rewrite the stub at the specified address,
1234 // rather than creating a new one.
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +00001235 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +00001236 JE->startGVStub(Stub, layout.Size);
Jeffrey Yasskinf2ad5712009-11-23 23:35:19 +00001237 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
Jeffrey Yasskine0d8e142009-12-15 22:42:46 +00001238 JE->finishGVStub();
Nate Begeman18d85e72009-02-18 08:31:02 +00001239}
1240
Chris Lattner873ef132006-05-11 23:08:08 +00001241/// freeMachineCodeForFunction - release machine code memory for given Function.
1242///
1243void JIT::freeMachineCodeForFunction(Function *F) {
1244 // Delete translation for this from the ExecutionEngine, so it will get
1245 // retranslated next time it is used.
Jeffrey Yasskinbf43f652009-10-27 00:03:05 +00001246 updateGlobalMapping(F, 0);
Chris Lattner873ef132006-05-11 23:08:08 +00001247
1248 // Free the actual memory for the function body and related stuff.
Sean Silvabead14e2012-10-11 23:30:38 +00001249 static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);
Chris Lattner873ef132006-05-11 23:08:08 +00001250}