blob: cd7a500f511573451b458fd77d5a6097496d12d7 [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 Lattner4d326fa2003-12-20 01:46:27 +000015#include "JIT.h"
Jeffrey Yasskin1e861322009-10-20 18:13:21 +000016#include "llvm/ADT/DenseMap.h"
Evan Cheng47c01a02008-11-07 09:02:17 +000017#include "llvm/ADT/SmallPtrSet.h"
Nate Begemand6b7a242009-02-18 08:31:02 +000018#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/CodeGen/JITCodeEmitter.h"
21#include "llvm/CodeGen/MachineCodeInfo.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
25#include "llvm/CodeGen/MachineModuleInfo.h"
26#include "llvm/CodeGen/MachineRelocation.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/ExecutionEngine/GenericValue.h"
28#include "llvm/ExecutionEngine/JITEventListener.h"
29#include "llvm/ExecutionEngine/JITMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
Stephen Hines36b56882014-04-23 16:57:46 -070032#include "llvm/IR/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000033#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Module.h"
Stephen Hines36b56882014-04-23 16:57:46 -070035#include "llvm/IR/ValueHandle.h"
36#include "llvm/IR/ValueMap.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/Support/Debug.h"
38#include "llvm/Support/Disassembler.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/ManagedStatic.h"
41#include "llvm/Support/Memory.h"
42#include "llvm/Support/MutexGuard.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetJITInfo.h"
46#include "llvm/Target/TargetMachine.h"
47#include "llvm/Target/TargetOptions.h"
Andrew Lenhartha00269b2005-07-29 23:40:16 +000048#include <algorithm>
Evan Chenga7916f52008-11-05 23:44:08 +000049#ifndef NDEBUG
50#include <iomanip>
51#endif
Chris Lattnerc19aade2003-12-08 08:06:28 +000052using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000053
Stephen Hinesdce4a402014-05-29 02:49:00 -070054#define DEBUG_TYPE "jit"
55
Chris Lattner36343732006-12-19 22:43:32 +000056STATISTIC(NumBytes, "Number of bytes of machine code compiled");
57STATISTIC(NumRelos, "Number of relocations applied");
Reid Kleckner10b4fc52009-07-23 21:46:56 +000058STATISTIC(NumRetries, "Number of retries with more memory");
Chris Lattner54266522004-11-20 23:57:07 +000059
Andrew Lenhartha00269b2005-07-29 23:40:16 +000060
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +000061// A declaration may stop being a declaration once it's fully read from bitcode.
62// This function returns true if F is fully read and is still a declaration.
63static bool isNonGhostDeclaration(const Function *F) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000064 return F->isDeclaration() && !F->isMaterializable();
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +000065}
66
Chris Lattner54266522004-11-20 23:57:07 +000067//===----------------------------------------------------------------------===//
68// JIT lazy compilation code.
69//
70namespace {
Jeffrey Yasskine637c192009-11-07 00:00:10 +000071 class JITEmitter;
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000072 class JITResolverState;
73
74 template<typename ValueTy>
75 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
76 typedef JITResolverState *ExtraData;
77 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
Craig Topper85814382012-02-07 05:05:23 +000078 llvm_unreachable("The JIT doesn't know how to handle a"
79 " RAUW on a value it has emitted.");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000080 }
81 };
82
83 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
84 typedef JITResolverState *ExtraData;
85 static void onDelete(JITResolverState *JRS, Function *F);
86 };
87
Reid Spenceree448632005-07-12 15:51:55 +000088 class JITResolverState {
Nick Lewyckye2bcf132009-04-27 05:09:44 +000089 public:
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000090 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
Jeffrey Yasskin108c8382009-11-23 23:35:19 +000091 FunctionToLazyStubMapTy;
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +000092 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000093 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
94 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
Nick Lewyckye2bcf132009-04-27 05:09:44 +000095 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
Reid Spenceree448632005-07-12 15:51:55 +000096 private:
Jeffrey Yasskin108c8382009-11-23 23:35:19 +000097 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
98 /// particular function so that we can reuse them if necessary.
99 FunctionToLazyStubMapTy FunctionToLazyStubMap;
Reid Spenceree448632005-07-12 15:51:55 +0000100
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000101 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
102 /// site corresponds to, and vice versa.
103 CallSiteToFunctionMapTy CallSiteToFunctionMap;
104 FunctionToCallSitesMapTy FunctionToCallSitesMap;
Jeff Cohen00b168892005-07-27 06:12:32 +0000105
Evan Cheng5594f122008-11-10 01:52:24 +0000106 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
Evan Chengbe8c03f2008-01-04 10:46:51 +0000107 /// particular GlobalVariable so that we can reuse them if necessary.
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000108 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000109
Benjamin Kramere04690e2012-06-16 21:55:52 +0000110#ifndef NDEBUG
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000111 /// Instance of the JIT this ResolverState serves.
112 JIT *TheJIT;
Benjamin Kramere04690e2012-06-16 21:55:52 +0000113#endif
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000114
Reid Spenceree448632005-07-12 15:51:55 +0000115 public:
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000116 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
Benjamin Kramere04690e2012-06-16 21:55:52 +0000117 FunctionToCallSitesMap(this) {
118#ifndef NDEBUG
119 TheJIT = jit;
120#endif
121 }
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000122
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000123 FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
124 const MutexGuard& locked) {
Reid Spenceree448632005-07-12 15:51:55 +0000125 assert(locked.holds(TheJIT->lock));
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000126 return FunctionToLazyStubMap;
Reid Spenceree448632005-07-12 15:51:55 +0000127 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000128
Jim Grosbach124d0332011-03-16 01:21:55 +0000129 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
130 assert(lck.holds(TheJIT->lock));
Evan Cheng5594f122008-11-10 01:52:24 +0000131 return GlobalToIndirectSymMap;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000132 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000133
Jay Foad5b240172011-04-13 12:46:01 +0000134 std::pair<void *, Function *> LookupFunctionFromCallSite(
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000135 const MutexGuard &locked, void *CallSite) const {
136 assert(locked.holds(TheJIT->lock));
137
Jim Grosbach124d0332011-03-16 01:21:55 +0000138 // The address given to us for the stub may not be exactly right, it
139 // might be a little bit after the stub. As such, use upper_bound to
140 // find it.
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000141 CallSiteToFunctionMapTy::const_iterator I =
142 CallSiteToFunctionMap.upper_bound(CallSite);
143 assert(I != CallSiteToFunctionMap.begin() &&
144 "This is not a known call site!");
145 --I;
146 return *I;
147 }
148
149 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
150 assert(locked.holds(TheJIT->lock));
151
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000152 bool Inserted = CallSiteToFunctionMap.insert(
153 std::make_pair(CallSite, F)).second;
154 (void)Inserted;
155 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000156 FunctionToCallSitesMap[F].insert(CallSite);
157 }
158
Jeffrey Yasskin8e98d122010-03-04 00:32:33 +0000159 void EraseAllCallSitesForPrelocked(Function *F);
160
161 // Erases _all_ call sites regardless of their function. This is used to
162 // unregister the stub addresses from the StubToResolverMap in
163 // ~JITResolver().
164 void EraseAllCallSitesPrelocked();
Reid Spenceree448632005-07-12 15:51:55 +0000165 };
Jeff Cohen00b168892005-07-27 06:12:32 +0000166
Chris Lattner54266522004-11-20 23:57:07 +0000167 /// JITResolver - Keep track of, and resolve, call sites for functions that
168 /// have not yet been compiled.
169 class JITResolver {
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000170 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000171 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
Nick Lewyckye2bcf132009-04-27 05:09:44 +0000172 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
173
Chris Lattner5e225582004-11-21 03:37:42 +0000174 /// LazyResolverFn - The target lazy resolver function that we actually
175 /// rewrite instructions to use.
176 TargetJITInfo::LazyResolverFn LazyResolverFn;
177
Reid Spenceree448632005-07-12 15:51:55 +0000178 JITResolverState state;
Chris Lattner54266522004-11-20 23:57:07 +0000179
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000180 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
181 /// for external functions. TODO: Of course, external functions don't need
182 /// a lazy stub. It's actually here to make it more likely that far calls
183 /// succeed, but no single stub can guarantee that. I'll remove this in a
184 /// subsequent checkin when I actually fix far calls.
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000185 std::map<void*, void*> ExternalFnToStubMap;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000186
Evan Cheng1606e8e2009-03-13 07:51:59 +0000187 /// revGOTMap - map addresses to indexes in the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000188 std::map<void*, unsigned> revGOTMap;
189 unsigned nextGOTIndex;
190
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000191 JITEmitter &JE;
192
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000193 /// Instance of JIT corresponding to this Resolver.
194 JIT *TheJIT;
195
Chris Lattner54266522004-11-20 23:57:07 +0000196 public:
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000197 explicit JITResolver(JIT &jit, JITEmitter &je)
Benjamin Kramere04690e2012-06-16 21:55:52 +0000198 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
Chris Lattnere7484012007-02-24 02:57:03 +0000199 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
Chris Lattner5e225582004-11-21 03:37:42 +0000200 }
Chris Lattner54266522004-11-20 23:57:07 +0000201
Jeffrey Yasskin8e98d122010-03-04 00:32:33 +0000202 ~JITResolver();
203
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000204 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
205 /// lazy-compilation stub if it has already been created.
206 void *getLazyFunctionStubIfAvailable(Function *F);
Evan Cheng704bff92008-11-13 21:50:50 +0000207
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000208 /// getLazyFunctionStub - This returns a pointer to a function's
209 /// lazy-compilation stub, creating one on demand as needed.
210 void *getLazyFunctionStub(Function *F);
Chris Lattner54266522004-11-20 23:57:07 +0000211
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000212 /// getExternalFunctionStub - Return a stub for the function at the
213 /// specified address, created lazily on demand.
214 void *getExternalFunctionStub(void *FnAddr);
215
Evan Cheng5594f122008-11-10 01:52:24 +0000216 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
Evan Chengc96a8e72008-11-05 01:50:32 +0000217 /// specified GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000218 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000219
Andrew Lenharth6a974612005-07-28 12:44:13 +0000220 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattner8907b4b2007-12-05 23:39:57 +0000221 /// an address. This function only manages slots, it does not manage the
Andrew Lenharth6a974612005-07-28 12:44:13 +0000222 /// contents of the slots or the memory associated with the GOT.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000223 unsigned getGOTIndexForAddr(void *addr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000224
Chris Lattner54266522004-11-20 23:57:07 +0000225 /// JITCompilerFn - This function is called to resolve a stub to a compiled
226 /// address. If the LLVM Function corresponding to the stub has not yet
227 /// been compiled, this function compiles it first.
228 static void *JITCompilerFn(void *Stub);
229 };
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000230
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000231 class StubToResolverMapTy {
232 /// Map a stub address to a specific instance of a JITResolver so that
233 /// lazily-compiled functions can find the right resolver to use.
234 ///
235 /// Guarded by Lock.
236 std::map<void*, JITResolver*> Map;
237
238 /// Guards Map from concurrent accesses.
239 mutable sys::Mutex Lock;
240
241 public:
242 /// Registers a Stub to be resolved by Resolver.
243 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
244 MutexGuard guard(Lock);
245 Map.insert(std::make_pair(Stub, Resolver));
246 }
247 /// Unregisters the Stub when it's invalidated.
248 void UnregisterStubResolver(void *Stub) {
249 MutexGuard guard(Lock);
250 Map.erase(Stub);
251 }
252 /// Returns the JITResolver instance that owns the Stub.
253 JITResolver *getResolverFromStub(void *Stub) const {
254 MutexGuard guard(Lock);
255 // The address given to us for the stub may not be exactly right, it might
256 // be a little bit after the stub. As such, use upper_bound to find it.
257 // This is the same trick as in LookupFunctionFromCallSite from
258 // JITResolverState.
259 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
260 assert(I != Map.begin() && "This is not a known stub!");
261 --I;
262 return I->second;
263 }
Jeffrey Yasskin8e98d122010-03-04 00:32:33 +0000264 /// True if any stubs refer to the given resolver. Only used in an assert().
265 /// O(N)
266 bool ResolverHasStubs(JITResolver* Resolver) const {
267 MutexGuard guard(Lock);
268 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
269 E = Map.end(); I != E; ++I) {
270 if (I->second == Resolver)
271 return true;
272 }
273 return false;
274 }
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000275 };
276 /// This needs to be static so that a lazy call stub can access it with no
277 /// context except the address of the stub.
278 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
279
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000280 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
281 /// used to output functions to memory for execution.
282 class JITEmitter : public JITCodeEmitter {
283 JITMemoryManager *MemMgr;
284
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +0000285 // When outputting a function stub in the context of some other function, we
286 // save BufferBegin/BufferEnd/CurBufferPtr here.
287 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
288
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000289 // When reattempting to JIT a function after running out of space, we store
290 // the estimated size of the function we're trying to JIT here, so we can
291 // ask the memory manager for at least this much space. When we
292 // successfully emit the function, we reset this back to zero.
293 uintptr_t SizeEstimate;
294
295 /// Relocations - These are the relocations that the function needs, as
296 /// emitted.
297 std::vector<MachineRelocation> Relocations;
Eric Christopher116664a2009-11-12 03:12:18 +0000298
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000299 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
300 /// It is filled in by the StartMachineBasicBlock callback and queried by
301 /// the getMachineBasicBlockAddress callback.
302 std::vector<uintptr_t> MBBLocations;
303
304 /// ConstantPool - The constant pool for the current function.
305 ///
306 MachineConstantPool *ConstantPool;
307
308 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
309 ///
310 void *ConstantPoolBase;
311
312 /// ConstPoolAddresses - Addresses of individual constant pool entries.
313 ///
314 SmallVector<uintptr_t, 8> ConstPoolAddresses;
315
316 /// JumpTable - The jump tables for the current function.
317 ///
318 MachineJumpTableInfo *JumpTable;
Eric Christopher116664a2009-11-12 03:12:18 +0000319
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000320 /// JumpTableBase - A pointer to the first entry in the jump table.
321 ///
322 void *JumpTableBase;
323
324 /// Resolver - This contains info about the currently resolved functions.
325 JITResolver Resolver;
326
Eric Christopher116664a2009-11-12 03:12:18 +0000327 /// LabelLocations - This vector is a mapping from Label ID's to their
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000328 /// address.
Chris Lattner16112732010-03-14 01:41:15 +0000329 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000330
331 /// MMI - Machine module info for exception informations
332 MachineModuleInfo* MMI;
333
Eric Christopher116664a2009-11-12 03:12:18 +0000334 // CurFn - The llvm function being emitted. Only valid during
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000335 // finishFunction().
336 const Function *CurFn;
337
338 /// Information about emitted code, which is passed to the
339 /// JITEventListeners. This is reset in startFunction and used in
340 /// finishFunction.
341 JITEvent_EmittedFunctionDetails EmissionDetails;
342
343 struct EmittedCode {
344 void *FunctionBody; // Beginning of the function's allocation.
345 void *Code; // The address the function's code actually starts at.
346 void *ExceptionTable;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700347 EmittedCode() : FunctionBody(nullptr), Code(nullptr),
348 ExceptionTable(nullptr) {}
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000349 };
350 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
351 typedef JITEmitter *ExtraData;
352 static void onDelete(JITEmitter *, const Function*);
353 static void onRAUW(JITEmitter *, const Function*, const Function*);
354 };
355 ValueMap<const Function *, EmittedCode,
356 EmittedFunctionConfig> EmittedFunctions;
357
Nicolas Geoffray4eb37392010-04-14 22:06:37 +0000358 DebugLoc PrevDL;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000359
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000360 /// Instance of the JIT
361 JIT *TheJIT;
362
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000363 public:
364 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700365 : SizeEstimate(0), Resolver(jit, *this), MMI(nullptr), CurFn(nullptr),
Rafael Espindolae4496542013-05-07 20:53:59 +0000366 EmittedFunctions(this), TheJIT(&jit) {
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000367 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
368 if (jit.getJITInfo().needsGOT()) {
369 MemMgr->AllocateGOT();
David Greenec9ec9932010-01-05 01:23:36 +0000370 DEBUG(dbgs() << "JIT is managing a GOT\n");
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000371 }
372
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000373 }
Eric Christopher116664a2009-11-12 03:12:18 +0000374 ~JITEmitter() {
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000375 delete MemMgr;
376 }
377
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000378 JITResolver &getJITResolver() { return Resolver; }
379
Stephen Hines36b56882014-04-23 16:57:46 -0700380 void startFunction(MachineFunction &F) override;
381 bool finishFunction(MachineFunction &F) override;
Eric Christopher116664a2009-11-12 03:12:18 +0000382
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000383 void emitConstantPool(MachineConstantPool *MCP);
384 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
385 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
Eric Christopher116664a2009-11-12 03:12:18 +0000386
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +0000387 void startGVStub(const GlobalValue* GV,
388 unsigned StubSize, unsigned Alignment = 1);
389 void startGVStub(void *Buffer, unsigned StubSize);
390 void finishGVStub();
Stephen Hines36b56882014-04-23 16:57:46 -0700391 void *allocIndirectGV(const GlobalValue *GV, const uint8_t *Buffer,
392 size_t Size, unsigned Alignment) override;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000393
394 /// allocateSpace - Reserves space in the current block if any, or
395 /// allocate a new one of the given size.
Stephen Hines36b56882014-04-23 16:57:46 -0700396 void *allocateSpace(uintptr_t Size, unsigned Alignment) override;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000397
398 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
399 /// this method does not allocate memory in the current output buffer,
400 /// because a global may live longer than the current function.
Stephen Hines36b56882014-04-23 16:57:46 -0700401 void *allocateGlobal(uintptr_t Size, unsigned Alignment) override;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000402
Stephen Hines36b56882014-04-23 16:57:46 -0700403 void addRelocation(const MachineRelocation &MR) override {
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000404 Relocations.push_back(MR);
405 }
Eric Christopher116664a2009-11-12 03:12:18 +0000406
Stephen Hines36b56882014-04-23 16:57:46 -0700407 void StartMachineBasicBlock(MachineBasicBlock *MBB) override {
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000408 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
409 MBBLocations.resize((MBB->getNumber()+1)*2);
410 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
Chris Lattner68feb222010-07-11 23:07:28 +0000411 if (MBB->hasAddressTaken())
412 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
413 (void*)getCurrentPCValue());
David Greenec9ec9932010-01-05 01:23:36 +0000414 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000415 << (void*) getCurrentPCValue() << "]\n");
416 }
417
Stephen Hines36b56882014-04-23 16:57:46 -0700418 uintptr_t getConstantPoolEntryAddress(unsigned Entry) const override;
419 uintptr_t getJumpTableEntryAddress(unsigned Entry) const override;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000420
Stephen Hines36b56882014-04-23 16:57:46 -0700421 uintptr_t
422 getMachineBasicBlockAddress(MachineBasicBlock *MBB) const override {
Eric Christopher116664a2009-11-12 03:12:18 +0000423 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000424 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
425 return MBBLocations[MBB->getNumber()];
426 }
427
428 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
429 /// given function. Increase the minimum allocation size so that we get
430 /// more memory next time.
431 void retryWithMoreMemory(MachineFunction &F);
432
433 /// deallocateMemForFunction - Deallocate all memory for the specified
434 /// function body.
435 void deallocateMemForFunction(const Function *F);
436
Stephen Hines36b56882014-04-23 16:57:46 -0700437 void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) override;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000438
Stephen Hines36b56882014-04-23 16:57:46 -0700439 void emitLabel(MCSymbol *Label) override {
Chris Lattner16112732010-03-14 01:41:15 +0000440 LabelLocations[Label] = getCurrentPCValue();
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000441 }
442
Stephen Hines36b56882014-04-23 16:57:46 -0700443 DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() override {
Bill Wendling47639fc2010-04-16 08:46:10 +0000444 return &LabelLocations;
445 }
446
Stephen Hines36b56882014-04-23 16:57:46 -0700447 uintptr_t getLabelAddress(MCSymbol *Label) const override {
Chris Lattner16112732010-03-14 01:41:15 +0000448 assert(LabelLocations.count(Label) && "Label not emitted!");
449 return LabelLocations.find(Label)->second;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000450 }
Eric Christopher116664a2009-11-12 03:12:18 +0000451
Stephen Hines36b56882014-04-23 16:57:46 -0700452 void setModuleInfo(MachineModuleInfo* Info) override {
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000453 MMI = Info;
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000454 }
455
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000456 private:
Jeffrey Yasskin2d274412009-11-07 08:51:52 +0000457 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
458 bool MayNeedFarStub);
459 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000460 };
Chris Lattner54266522004-11-20 23:57:07 +0000461}
462
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000463void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
Jeffrey Yasskin8e98d122010-03-04 00:32:33 +0000464 JRS->EraseAllCallSitesForPrelocked(F);
465}
466
Jeffrey Yasskin8e98d122010-03-04 00:32:33 +0000467void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
468 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
469 if (F2C == FunctionToCallSitesMap.end())
470 return;
471 StubToResolverMapTy &S2RMap = *StubToResolverMap;
472 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
473 E = F2C->second.end(); I != E; ++I) {
474 S2RMap.UnregisterStubResolver(*I);
475 bool Erased = CallSiteToFunctionMap.erase(*I);
476 (void)Erased;
477 assert(Erased && "Missing call site->function mapping");
478 }
479 FunctionToCallSitesMap.erase(F2C);
480}
481
482void JITResolverState::EraseAllCallSitesPrelocked() {
483 StubToResolverMapTy &S2RMap = *StubToResolverMap;
484 for (CallSiteToFunctionMapTy::const_iterator
485 I = CallSiteToFunctionMap.begin(),
486 E = CallSiteToFunctionMap.end(); I != E; ++I) {
487 S2RMap.UnregisterStubResolver(I->first);
488 }
489 CallSiteToFunctionMap.clear();
490 FunctionToCallSitesMap.clear();
491}
492
493JITResolver::~JITResolver() {
494 // No need to lock because we're in the destructor, and state isn't shared.
495 state.EraseAllCallSitesPrelocked();
496 assert(!StubToResolverMap->ResolverHasStubs(this) &&
497 "Resolver destroyed with stubs still alive.");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000498}
499
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000500/// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
Evan Cheng704bff92008-11-13 21:50:50 +0000501/// if it has already been created.
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000502void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
Evan Cheng704bff92008-11-13 21:50:50 +0000503 MutexGuard locked(TheJIT->lock);
504
505 // If we already have a stub for this function, recycle it.
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000506 return state.getFunctionToLazyStubMap(locked).lookup(F);
Evan Cheng704bff92008-11-13 21:50:50 +0000507}
508
Chris Lattner54266522004-11-20 23:57:07 +0000509/// getFunctionStub - This returns a pointer to a function stub, creating
510/// one on demand as needed.
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000511void *JITResolver::getLazyFunctionStub(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000512 MutexGuard locked(TheJIT->lock);
513
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000514 // If we already have a lazy stub for this function, recycle it.
515 void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
Chris Lattner54266522004-11-20 23:57:07 +0000516 if (Stub) return Stub;
517
Jeffrey Yasskindc857242009-10-27 20:30:28 +0000518 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
519 // must resolve the symbol now.
520 void *Actual = TheJIT->isCompilingLazily()
Stephen Hinesdce4a402014-05-29 02:49:00 -0700521 ? (void *)(intptr_t)LazyResolverFn : (void *)nullptr;
Jeffrey Yasskindc857242009-10-27 20:30:28 +0000522
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000523 // If this is an external declaration, attempt to resolve the address now
524 // to place in the stub.
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000525 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000526 Actual = TheJIT->getPointerToFunction(F);
Misha Brukmanf976c852005-04-21 22:55:34 +0000527
Dan Gohman69f93782009-01-05 05:32:42 +0000528 // If we resolved the symbol to a null address (eg. a weak external)
Jeffrey Yasskin6f348e42009-11-09 22:34:19 +0000529 // don't emit a stub. Return a null pointer to the application.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700530 if (!Actual) return nullptr;
Dan Gohman69f93782009-01-05 05:32:42 +0000531 }
532
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000533 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +0000534 JE.startGVStub(F, SL.Size, SL.Alignment);
Nate Begemanb9c6c9b2009-03-07 06:41:19 +0000535 // Codegen a new stub, calling the lazy resolver or the actual address of the
536 // external function, if it was resolved.
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000537 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +0000538 JE.finishGVStub();
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000539
Chris Lattner870286a2006-06-01 17:29:22 +0000540 if (Actual != (void*)(intptr_t)LazyResolverFn) {
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000541 // If we are getting the stub for an external function, we really want the
542 // address of the stub in the GlobalAddressMap for the JIT, not the address
543 // of the external function.
544 TheJIT->updateGlobalMapping(F, Stub);
545 }
Chris Lattner54266522004-11-20 23:57:07 +0000546
David Greenec9ec9932010-01-05 01:23:36 +0000547 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000548 << F->getName() << "'\n");
Chris Lattnercb479412004-11-21 03:44:32 +0000549
Jeffrey Yasskin8e98d122010-03-04 00:32:33 +0000550 if (TheJIT->isCompilingLazily()) {
551 // Register this JITResolver as the one corresponding to this call site so
552 // JITCompilerFn will be able to find it.
553 StubToResolverMap->RegisterStubResolver(Stub, this);
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000554
Jeffrey Yasskin8e98d122010-03-04 00:32:33 +0000555 // Finally, keep track of the stub-to-Function mapping so that the
556 // JITCompilerFn knows which function to compile!
557 state.AddCallSite(locked, Stub, F);
558 } else if (!Actual) {
559 // If we are JIT'ing non-lazily but need to call a function that does not
560 // exist yet, add it to the JIT's work list so that we can fill in the
561 // stub address later.
562 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
563 "'Actual' should have been set above.");
564 TheJIT->addPendingFunction(F);
565 }
Jeffrey Yasskine5f87982009-10-13 21:32:57 +0000566
Chris Lattner54266522004-11-20 23:57:07 +0000567 return Stub;
568}
569
Evan Cheng5594f122008-11-10 01:52:24 +0000570/// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
Evan Chengbe8c03f2008-01-04 10:46:51 +0000571/// GV address.
Evan Cheng5594f122008-11-10 01:52:24 +0000572void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
Evan Chengbe8c03f2008-01-04 10:46:51 +0000573 MutexGuard locked(TheJIT->lock);
574
575 // If we already have a stub for this global variable, recycle it.
Evan Cheng5594f122008-11-10 01:52:24 +0000576 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
577 if (IndirectSym) return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000578
Evan Chenge4d783d2008-11-10 23:26:16 +0000579 // Otherwise, codegen a new indirect symbol.
Evan Cheng5594f122008-11-10 01:52:24 +0000580 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
Jeffrey Yasskine637c192009-11-07 00:00:10 +0000581 JE);
Evan Chengbe8c03f2008-01-04 10:46:51 +0000582
David Greenec9ec9932010-01-05 01:23:36 +0000583 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000584 << "] for GV '" << GV->getName() << "'\n");
Evan Chengbe8c03f2008-01-04 10:46:51 +0000585
Evan Cheng5594f122008-11-10 01:52:24 +0000586 return IndirectSym;
Evan Chengbe8c03f2008-01-04 10:46:51 +0000587}
588
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000589/// getExternalFunctionStub - Return a stub for the function at the
590/// specified address, created lazily on demand.
591void *JITResolver::getExternalFunctionStub(void *FnAddr) {
592 // If we already have a stub for this function, recycle it.
593 void *&Stub = ExternalFnToStubMap[FnAddr];
594 if (Stub) return Stub;
595
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000596 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700597 JE.startGVStub(nullptr, SL.Size, SL.Alignment);
598 Stub = TheJIT->getJITInfo().emitFunctionStub(nullptr, FnAddr, JE);
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +0000599 JE.finishGVStub();
Evan Cheng55fc2802006-07-25 20:40:54 +0000600
David Greenec9ec9932010-01-05 01:23:36 +0000601 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000602 << "] for external function at '" << FnAddr << "'\n");
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000603 return Stub;
604}
605
Andrew Lenharth6a974612005-07-28 12:44:13 +0000606unsigned JITResolver::getGOTIndexForAddr(void* addr) {
607 unsigned idx = revGOTMap[addr];
608 if (!idx) {
609 idx = ++nextGOTIndex;
610 revGOTMap[addr] = idx;
David Greenec9ec9932010-01-05 01:23:36 +0000611 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000612 << addr << "]\n");
Andrew Lenharth6a974612005-07-28 12:44:13 +0000613 }
614 return idx;
615}
Chris Lattnerd91ff7c2005-04-18 01:44:27 +0000616
Chris Lattner54266522004-11-20 23:57:07 +0000617/// JITCompilerFn - This function is called when a lazy compilation stub has
618/// been entered. It looks up which function this stub corresponds to, compiles
619/// it if necessary, then returns the resultant function pointer.
620void *JITResolver::JITCompilerFn(void *Stub) {
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000621 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
622 assert(JR && "Unable to find the corresponding JITResolver to the call site");
Eric Christopher116664a2009-11-12 03:12:18 +0000623
Stephen Hinesdce4a402014-05-29 02:49:00 -0700624 Function* F = nullptr;
625 void* ActualPtr = nullptr;
Misha Brukmanf976c852005-04-21 22:55:34 +0000626
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000627 {
628 // Only lock for getting the Function. The call getPointerToFunction made
629 // in this function might trigger function materializing, which requires
630 // JIT lock to be unlocked.
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000631 MutexGuard locked(JR->TheJIT->lock);
Reid Spenceree448632005-07-12 15:51:55 +0000632
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000633 // The address given to us for the stub may not be exactly right, it might
634 // be a little bit after the stub. As such, use upper_bound to find it.
Jay Foad5b240172011-04-13 12:46:01 +0000635 std::pair<void*, Function*> I =
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000636 JR->state.LookupFunctionFromCallSite(locked, Stub);
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000637 F = I.second;
638 ActualPtr = I.first;
Nicolas Geoffraydcb31e12008-10-03 07:27:08 +0000639 }
Chris Lattner54266522004-11-20 23:57:07 +0000640
Evan Cheng9da60f92007-06-30 00:10:37 +0000641 // If we have already code generated the function, just return the address.
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000642 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
Eric Christopher116664a2009-11-12 03:12:18 +0000643
Evan Cheng9da60f92007-06-30 00:10:37 +0000644 if (!Result) {
645 // Otherwise we don't have it, do lazy compilation now.
Eric Christopher116664a2009-11-12 03:12:18 +0000646
Evan Cheng9da60f92007-06-30 00:10:37 +0000647 // If lazy compilation is disabled, emit a useful error message and abort.
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000648 if (!JR->TheJIT->isCompilingLazily()) {
Jim Grosbach124d0332011-03-16 01:21:55 +0000649 report_fatal_error("LLVM JIT requested to do lazy compilation of"
650 " function '"
Torok Edwin7d696d82009-07-11 13:10:19 +0000651 + F->getName() + "' when lazy compiles are disabled!");
Evan Cheng9da60f92007-06-30 00:10:37 +0000652 }
Eric Christopher116664a2009-11-12 03:12:18 +0000653
David Greenec9ec9932010-01-05 01:23:36 +0000654 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000655 << "' In stub ptr = " << Stub << " actual ptr = "
656 << ActualPtr << "\n");
Duncan Sands1f6a3292011-08-12 14:54:45 +0000657 (void)ActualPtr;
Chris Lattner54266522004-11-20 23:57:07 +0000658
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000659 Result = JR->TheJIT->getPointerToFunction(F);
Evan Cheng9da60f92007-06-30 00:10:37 +0000660 }
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000661
662 // Reacquire the lock to update the GOT map.
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000663 MutexGuard locked(JR->TheJIT->lock);
Chris Lattner54266522004-11-20 23:57:07 +0000664
Jeffrey Yasskinebbcef92009-10-19 18:49:59 +0000665 // We might like to remove the call site from the CallSiteToFunction map, but
666 // we can't do that! Multiple threads could be stuck, waiting to acquire the
667 // lock above. As soon as the 1st function finishes compiling the function,
668 // the next one will be released, and needs to be able to find the function it
669 // needs to call.
Chris Lattner54266522004-11-20 23:57:07 +0000670
671 // FIXME: We could rewrite all references to this stub if we knew them.
Andrew Lenharth6a974612005-07-28 12:44:13 +0000672
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000673 // What we will do is set the compiled function address to map to the
674 // same GOT entry as the stub so that later clients may update the GOT
Andrew Lenharth6a974612005-07-28 12:44:13 +0000675 // if they see it still using the stub address.
676 // Note: this is done so the Resolver doesn't have to manage GOT memory
677 // Do this without allocating map space if the target isn't using a GOT
Jeffrey Yasskin40966a72010-02-11 01:07:39 +0000678 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
679 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
Andrew Lenharth6a974612005-07-28 12:44:13 +0000680
Chris Lattner54266522004-11-20 23:57:07 +0000681 return Result;
682}
Chris Lattner688506d2003-08-14 18:35:27 +0000683
Chris Lattner8ac66c12008-04-04 05:51:42 +0000684//===----------------------------------------------------------------------===//
Chris Lattner166f2262004-11-22 22:00:25 +0000685// JITEmitter code.
Chris Lattner54266522004-11-20 23:57:07 +0000686//
Chris Lattner166f2262004-11-22 22:00:25 +0000687void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
Jeffrey Yasskin2d274412009-11-07 08:51:52 +0000688 bool MayNeedFarStub) {
Nate Begemand6b7a242009-02-18 08:31:02 +0000689 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Chris Lattner54266522004-11-20 23:57:07 +0000690 return TheJIT->getOrEmitGlobalVariable(GV);
Nate Begemand6b7a242009-02-18 08:31:02 +0000691
Chris Lattner18e04592008-06-25 20:21:35 +0000692 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700693 return TheJIT->getPointerToGlobal(GA->getAliasee());
Chris Lattner54266522004-11-20 23:57:07 +0000694
695 // If we have already compiled the function, return a pointer to its body.
696 Function *F = cast<Function>(V);
Eric Christopher116664a2009-11-12 03:12:18 +0000697
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000698 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
Eric Christopher116664a2009-11-12 03:12:18 +0000699 if (FnStub) {
Jeffrey Yasskin108c8382009-11-23 23:35:19 +0000700 // Return the function stub if it's already created. We do this first so
701 // that we're returning the same address for the function as any previous
702 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
703 // close enough to call.
Eric Christopher116664a2009-11-12 03:12:18 +0000704 return FnStub;
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000705 }
Eric Christopher116664a2009-11-12 03:12:18 +0000706
Jeffrey Yasskine03a39b2009-11-19 23:42:58 +0000707 // If we know the target can handle arbitrary-distance calls, try to
708 // return a direct pointer.
709 if (!MayNeedFarStub) {
710 // If we have code, go ahead and return that.
711 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
712 if (ResultPtr) return ResultPtr;
Chris Lattner54266522004-11-20 23:57:07 +0000713
Jeffrey Yasskine03a39b2009-11-19 23:42:58 +0000714 // If this is an external function pointer, we can force the JIT to
715 // 'compile' it, which really just adds it to the map.
Jeffrey Yasskinc5818fb2009-12-22 23:47:23 +0000716 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
Jeffrey Yasskine03a39b2009-11-19 23:42:58 +0000717 return TheJIT->getPointerToFunction(F);
718 }
Chris Lattnerb43dbdc2004-11-22 07:24:43 +0000719
Jeffrey Yasskin39c75f22010-03-04 19:45:09 +0000720 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
721 // so. Note that it's possible to return null from getLazyFunctionStub in the
722 // case of a weak extern that fails to resolve.
723 return Resolver.getLazyFunctionStub(F);
Chris Lattner54266522004-11-20 23:57:07 +0000724}
725
Jeffrey Yasskin2d274412009-11-07 08:51:52 +0000726void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000727 // Make sure GV is emitted first, and create a stub containing the fully
728 // resolved address.
Jeffrey Yasskin2d274412009-11-07 08:51:52 +0000729 void *GVAddress = getPointerToGlobal(V, Reference, false);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000730 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000731 return StubAddr;
732}
733
Devang Patel02c04232009-10-06 03:04:58 +0000734void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
Chris Lattnerde4845c2010-04-02 19:42:39 +0000735 if (DL.isUnknown()) return;
736 if (!BeforePrintingInsn) return;
Jim Grosbach124d0332011-03-16 01:21:55 +0000737
Chris Lattner134d8ee2010-07-22 21:17:55 +0000738 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
Nicolas Geoffray4eb37392010-04-14 22:06:37 +0000739
Stephen Hinesdce4a402014-05-29 02:49:00 -0700740 if (DL.getScope(Context) != nullptr && PrevDL != DL) {
Chris Lattnerde4845c2010-04-02 19:42:39 +0000741 JITEvent_EmittedFunctionDetails::LineStart NextLine;
742 NextLine.Address = getCurrentPCValue();
743 NextLine.Loc = DL;
744 EmissionDetails.LineStarts.push_back(NextLine);
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000745 }
Chris Lattnerde4845c2010-04-02 19:42:39 +0000746
Nicolas Geoffray4eb37392010-04-14 22:06:37 +0000747 PrevDL = DL;
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000748}
749
Evan Cheng1606e8e2009-03-13 07:51:59 +0000750static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
Micah Villmow3574eca2012-10-08 16:38:25 +0000751 const DataLayout *TD) {
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000752 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
753 if (Constants.empty()) return 0;
754
Evan Cheng1606e8e2009-03-13 07:51:59 +0000755 unsigned Size = 0;
756 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
757 MachineConstantPoolEntry CPE = Constants[i];
758 unsigned AlignMask = CPE.getAlignment() - 1;
759 Size = (Size + AlignMask) & ~AlignMask;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000760 Type *Ty = CPE.getType();
Duncan Sands777d2302009-05-09 07:06:46 +0000761 Size += TD->getTypeAllocSize(Ty);
Evan Cheng1606e8e2009-03-13 07:51:59 +0000762 }
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000763 return Size;
764}
765
Chris Lattner166f2262004-11-22 22:00:25 +0000766void JITEmitter::startFunction(MachineFunction &F) {
David Greenec9ec9932010-01-05 01:23:36 +0000767 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
Craig Topper96601ca2012-08-22 06:07:19 +0000768 << F.getName() << "\n");
Evan Chengeb5d95a2008-11-06 17:46:04 +0000769
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000770 uintptr_t ActualSize = 0;
Jim Grosbachcce6c292008-10-03 16:17:20 +0000771 // Set the memory writable, if it's not already
772 MemMgr->setMemoryWritable();
Jim Grosbach124d0332011-03-16 01:21:55 +0000773
Chris Lattner134d8ee2010-07-22 21:17:55 +0000774 if (SizeEstimate > 0) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000775 // SizeEstimate will be non-zero on reallocation attempts.
776 ActualSize = SizeEstimate;
Nicolas Geoffraydc17ab22008-04-18 20:59:31 +0000777 }
778
Chris Lattner8907b4b2007-12-05 23:39:57 +0000779 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
780 ActualSize);
Chris Lattnere993cc22006-05-11 23:08:08 +0000781 BufferEnd = BufferBegin+ActualSize;
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000782 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
783
Evan Cheng9a1e9b92006-11-16 20:04:54 +0000784 // Ensure the constant pool/jump table info is at least 4-byte aligned.
785 emitAlignment(16);
786
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000787 emitConstantPool(F.getConstantPool());
Chris Lattner071c62f2010-01-25 23:26:13 +0000788 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
789 initJumpTableInfo(MJTI);
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000790
791 // About to start emitting the machine code for the function.
Chris Lattner0eb4d6b2006-05-03 01:03:20 +0000792 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
Chris Lattnerf75f9be2006-05-02 23:22:24 +0000793 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000794 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
Evan Cheng55fc2802006-07-25 20:40:54 +0000795
Chris Lattnerb4432f32006-05-03 17:10:41 +0000796 MBBLocations.clear();
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000797
798 EmissionDetails.MF = &F;
799 EmissionDetails.LineStarts.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000800}
801
Chris Lattner43b429b2006-05-02 18:27:26 +0000802bool JITEmitter::finishFunction(MachineFunction &F) {
Chris Lattnere993cc22006-05-11 23:08:08 +0000803 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000804 // We must call endFunctionBody before retrying, because
805 // deallocateMemForFunction requires it.
806 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
807 retryWithMoreMemory(F);
808 return true;
Chris Lattnere993cc22006-05-11 23:08:08 +0000809 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000810
Chris Lattner071c62f2010-01-25 23:26:13 +0000811 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
812 emitJumpTableInfo(MJTI);
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000813
Chris Lattnera8279532006-06-16 18:09:26 +0000814 // FnStart is the start of the text, not the start of the constant pool and
815 // other per-function data.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000816 uint8_t *FnStart =
817 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000818
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000819 // FnEnd is the end of the function's machine code.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000820 uint8_t *FnEnd = CurBufferPtr;
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000821
Chris Lattner5be478f2004-11-20 03:46:14 +0000822 if (!Relocations.empty()) {
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000823 CurFn = F.getFunction();
Chris Lattnere884dc22005-07-20 16:29:20 +0000824 NumRelos += Relocations.size();
825
Chris Lattner5be478f2004-11-20 03:46:14 +0000826 // Resolve the relocations to concrete pointers.
827 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
828 MachineRelocation &MR = Relocations[i];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700829 void *ResultPtr = nullptr;
Evan Chengef5784e2008-10-29 23:54:46 +0000830 if (!MR.letTargetResolve()) {
Evan Chengd7398c92008-11-08 07:37:34 +0000831 if (MR.isExternalSymbol()) {
Dan Gohman69f93782009-01-05 05:32:42 +0000832 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
833 false);
David Greenec9ec9932010-01-05 01:23:36 +0000834 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
Eric Christopher116664a2009-11-12 03:12:18 +0000835 << ResultPtr << "]\n");
Misha Brukmanf976c852005-04-21 22:55:34 +0000836
Evan Chengef5784e2008-10-29 23:54:46 +0000837 // If the target REALLY wants a stub for this function, emit it now.
Jeffrey Yasskin2d274412009-11-07 08:51:52 +0000838 if (MR.mayNeedFarStub()) {
Jeffrey Yasskin6f348e42009-11-09 22:34:19 +0000839 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
Nate Begeman841c6a42009-03-11 07:03:43 +0000840 }
Evan Chengef5784e2008-10-29 23:54:46 +0000841 } else if (MR.isGlobalValue()) {
842 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
843 BufferBegin+MR.getMachineCodeOffset(),
Jeffrey Yasskin2d274412009-11-07 08:51:52 +0000844 MR.mayNeedFarStub());
Evan Cheng5594f122008-11-10 01:52:24 +0000845 } else if (MR.isIndirectSymbol()) {
Jeffrey Yasskin2d274412009-11-07 08:51:52 +0000846 ResultPtr = getPointerToGVIndirectSym(
847 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
Evan Chengef5784e2008-10-29 23:54:46 +0000848 } else if (MR.isBasicBlock()) {
849 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
850 } else if (MR.isConstantPoolIndex()) {
Jim Grosbach124d0332011-03-16 01:21:55 +0000851 ResultPtr =
852 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Evan Chengef5784e2008-10-29 23:54:46 +0000853 } else {
854 assert(MR.isJumpTableIndex());
855 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
856 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000857
Evan Chengef5784e2008-10-29 23:54:46 +0000858 MR.setResultPointer(ResultPtr);
859 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000860
Andrew Lenharth6a974612005-07-28 12:44:13 +0000861 // if we are managing the GOT and the relocation wants an index,
862 // give it one
Chris Lattner8907b4b2007-12-05 23:39:57 +0000863 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000864 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
Andrew Lenharth6a974612005-07-28 12:44:13 +0000865 MR.setGOTIndex(idx);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000866 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
David Greenec9ec9932010-01-05 01:23:36 +0000867 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000868 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
869 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000870 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000871 }
Andrew Lenharth16ec33c2005-07-22 20:48:12 +0000872 }
Chris Lattner5be478f2004-11-20 03:46:14 +0000873 }
874
Stephen Hinesdce4a402014-05-29 02:49:00 -0700875 CurFn = nullptr;
Chris Lattner43b429b2006-05-02 18:27:26 +0000876 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattner8907b4b2007-12-05 23:39:57 +0000877 Relocations.size(), MemMgr->getGOTBase());
Chris Lattner5be478f2004-11-20 03:46:14 +0000878 }
879
Chris Lattnerd2d5c762006-05-03 18:55:56 +0000880 // Update the GOT entry for F to point to the new code.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000881 if (MemMgr->isManagingGOT()) {
Chris Lattnere7484012007-02-24 02:57:03 +0000882 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000883 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
David Greenec9ec9932010-01-05 01:23:36 +0000884 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000885 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
886 << "\n");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000887 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Andrew Lenharth6a974612005-07-28 12:44:13 +0000888 }
889 }
890
Argyrios Kyrtzidis19fee412009-04-30 23:01:58 +0000891 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
892 // global variables that were referenced in the relocations.
893 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
Evan Cheng5788d1a2008-12-10 02:32:19 +0000894
895 if (CurBufferPtr == BufferEnd) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000896 retryWithMoreMemory(F);
897 return true;
898 } else {
899 // Now that we've succeeded in emitting the function, reset the
900 // SizeEstimate back down to zero.
901 SizeEstimate = 0;
Evan Cheng5788d1a2008-12-10 02:32:19 +0000902 }
903
Stephen Hinesdce4a402014-05-29 02:49:00 -0700904 BufferBegin = CurBufferPtr = nullptr;
Nuno Lopescef75272008-10-21 11:42:16 +0000905 NumBytes += FnEnd-FnStart;
906
Evan Cheng55fc2802006-07-25 20:40:54 +0000907 // Invalidate the icache if necessary.
Chris Lattnerbc52cad2008-06-25 17:18:44 +0000908 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000909
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000910 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
Jeffrey Yasskin32360a72009-07-16 21:07:26 +0000911 EmissionDetails);
Evan Cheng55fc2802006-07-25 20:40:54 +0000912
Nicolas Geoffray4eb37392010-04-14 22:06:37 +0000913 // Reset the previous debug location.
914 PrevDL = DebugLoc();
915
David Greenec9ec9932010-01-05 01:23:36 +0000916 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
Craig Topper96601ca2012-08-22 06:07:19 +0000917 << "] Function: " << F.getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000918 << ": " << (FnEnd-FnStart) << " bytes of text, "
919 << Relocations.size() << " relocations\n");
Argyrios Kyrtzidisb3a847d2009-05-18 21:06:40 +0000920
Chris Lattner5be478f2004-11-20 03:46:14 +0000921 Relocations.clear();
Evan Cheng1606e8e2009-03-13 07:51:59 +0000922 ConstPoolAddresses.clear();
Anton Korobeynikov8cd4c3e2007-01-19 17:25:17 +0000923
Evan Chengbc4707a2008-09-18 07:54:21 +0000924 // Mark code region readable and executable if it's not so already.
Jim Grosbachcce6c292008-10-03 16:17:20 +0000925 MemMgr->setMemoryExecutable();
Evan Chengbc4707a2008-09-18 07:54:21 +0000926
Bill Wendling69c128f2010-04-18 00:52:08 +0000927 DEBUG({
928 if (sys::hasDisassembler()) {
929 dbgs() << "JIT: Disassembled code:\n";
930 dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
931 (uintptr_t)FnStart);
932 } else {
933 dbgs() << "JIT: Binary code:\n";
934 uint8_t* q = FnStart;
935 for (int i = 0; q < FnEnd; q += 4, ++i) {
936 if (i == 4)
937 i = 0;
938 if (i == 0)
939 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
940 bool Done = false;
941 for (int j = 3; j >= 0; --j) {
942 if (q + j >= FnEnd)
943 Done = true;
944 else
945 dbgs() << (unsigned short)q[j];
946 }
947 if (Done)
948 break;
949 dbgs() << ' ';
950 if (i == 3)
951 dbgs() << '\n';
Evan Chenge7c35512008-11-12 08:22:43 +0000952 }
Bill Wendling69c128f2010-04-18 00:52:08 +0000953 dbgs()<< '\n';
Evan Chenga7916f52008-11-05 23:44:08 +0000954 }
Bill Wendling69c128f2010-04-18 00:52:08 +0000955 });
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000956
Evan Cheng252ddfb2008-09-02 08:14:01 +0000957 if (MMI)
958 MMI->EndFunction();
Eric Christopher116664a2009-11-12 03:12:18 +0000959
Chris Lattner43b429b2006-05-02 18:27:26 +0000960 return false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000961}
962
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000963void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
David Greenec9ec9932010-01-05 01:23:36 +0000964 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000965 Relocations.clear(); // Clear the old relocations or we'll reapply them.
966 ConstPoolAddresses.clear();
967 ++NumRetries;
968 deallocateMemForFunction(F.getFunction());
969 // Try again with at least twice as much free space.
970 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
Chris Lattner68feb222010-07-11 23:07:28 +0000971
972 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
973 if (MBB->hasAddressTaken())
974 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
975 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000976}
977
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000978/// deallocateMemForFunction - Deallocate all memory for the specified
979/// function body. Also drop any references the function has to stubs.
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000980/// May be called while the Function is being destroyed inside ~Value().
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000981void JITEmitter::deallocateMemForFunction(const Function *F) {
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000982 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
983 Emitted = EmittedFunctions.find(F);
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000984 if (Emitted != EmittedFunctions.end()) {
985 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +0000986 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
987
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000988 EmittedFunctions.erase(Emitted);
989 }
Nate Begeman50cd6fd2009-03-05 06:34:37 +0000990}
991
992
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000993void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +0000994 if (BufferBegin)
Bruno Cardoso Lopesa3f99f92009-05-30 20:51:52 +0000995 return JITCodeEmitter::allocateSpace(Size, Alignment);
Nuno Lopescef75272008-10-21 11:42:16 +0000996
997 // create a new memory block if there is no active one.
998 // care must be taken so that BufferBegin is invalidated when a
999 // block is trimmed
1000 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1001 BufferEnd = BufferBegin+Size;
1002 return CurBufferPtr;
1003}
1004
Nick Lewycky8a8d4792011-12-02 22:16:29 +00001005void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
Jeffrey Yasskin489393d2009-07-08 21:59:57 +00001006 // Delegate this call through the memory manager.
1007 return MemMgr->allocateGlobal(Size, Alignment);
1008}
1009
Chris Lattner166f2262004-11-22 22:00:25 +00001010void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001011 if (TheJIT->getJITInfo().hasCustomConstantPool())
Jim Grosbach8fe95352008-10-30 23:44:39 +00001012 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001013
Chris Lattnerfa77d432006-02-09 04:22:52 +00001014 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +00001015 if (Constants.empty()) return;
1016
Micah Villmow3574eca2012-10-08 16:38:25 +00001017 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
Evan Cheng1606e8e2009-03-13 07:51:59 +00001018 unsigned Align = MCP->getConstantPoolAlignment();
Evan Cheng97b8c402008-04-12 00:22:01 +00001019 ConstantPoolBase = allocateSpace(Size, Align);
Chris Lattner239862c2006-02-09 04:49:59 +00001020 ConstantPool = MCP;
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001021
Stephen Hinesdce4a402014-05-29 02:49:00 -07001022 if (!ConstantPoolBase) return; // Buffer overflow.
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001023
David Greenec9ec9932010-01-05 01:23:36 +00001024 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001025 << "] (size: " << Size << ", alignment: " << Align << ")\n");
Evan Cheng97b8c402008-04-12 00:22:01 +00001026
Chris Lattner239862c2006-02-09 04:49:59 +00001027 // Initialize the memory for all of the constant pool entries.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001028 unsigned Offset = 0;
Chris Lattner3029f922006-02-09 04:46:04 +00001029 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Evan Cheng1606e8e2009-03-13 07:51:59 +00001030 MachineConstantPoolEntry CPE = Constants[i];
1031 unsigned AlignMask = CPE.getAlignment() - 1;
1032 Offset = (Offset + AlignMask) & ~AlignMask;
1033
1034 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1035 ConstPoolAddresses.push_back(CAddr);
1036 if (CPE.isMachineConstantPoolEntry()) {
Evan Chengcd5731d2006-09-12 20:59:59 +00001037 // FIXME: add support to lower machine constant pool values into bytes!
Chris Lattner75361b62010-04-07 22:58:41 +00001038 report_fatal_error("Initialize memory with machine specific constant pool"
Torok Edwin7d696d82009-07-11 13:10:19 +00001039 "entry has not been implemented!");
Evan Chengcd5731d2006-09-12 20:59:59 +00001040 }
Evan Cheng1606e8e2009-03-13 07:51:59 +00001041 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
David Greenec9ec9932010-01-05 01:23:36 +00001042 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1043 dbgs().write_hex(CAddr) << "]\n");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001044
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001045 Type *Ty = CPE.Val.ConstVal->getType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001046 Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
Chris Lattner1cc08382003-01-13 01:00:12 +00001047 }
1048}
1049
Nate Begeman37efe672006-04-22 18:53:45 +00001050void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001051 if (TheJIT->getJITInfo().hasCustomJumpTables())
1052 return;
Richard Osborne95da6052010-03-11 14:58:16 +00001053 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1054 return;
Evan Cheng47c01a02008-11-07 09:02:17 +00001055
Nate Begeman37efe672006-04-22 18:53:45 +00001056 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1057 if (JT.empty()) return;
Eric Christopher116664a2009-11-12 03:12:18 +00001058
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001059 unsigned NumEntries = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001060 for (unsigned i = 0, e = JT.size(); i != e; ++i)
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001061 NumEntries += JT[i].MBBs.size();
1062
Micah Villmow3574eca2012-10-08 16:38:25 +00001063 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
Chris Lattnerf75f9be2006-05-02 23:22:24 +00001064
Nate Begeman37efe672006-04-22 18:53:45 +00001065 // Just allocate space for all the jump tables now. We will fix up the actual
1066 // MBB entries in the tables after we emit the code for each block, since then
1067 // we will know the final locations of the MBBs in memory.
1068 JumpTable = MJTI;
Chris Lattner071c62f2010-01-25 23:26:13 +00001069 JumpTableBase = allocateSpace(NumEntries * EntrySize,
Micah Villmow3574eca2012-10-08 16:38:25 +00001070 MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
Nate Begeman37efe672006-04-22 18:53:45 +00001071}
1072
Jim Laskeyb92767a2006-12-14 22:53:42 +00001073void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
Evan Cheng47c01a02008-11-07 09:02:17 +00001074 if (TheJIT->getJITInfo().hasCustomJumpTables())
1075 return;
1076
Nate Begeman37efe672006-04-22 18:53:45 +00001077 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001078 if (JT.empty() || !JumpTableBase) return;
Eric Christopher116664a2009-11-12 03:12:18 +00001079
Jim Grosbach124d0332011-03-16 01:21:55 +00001080
Chris Lattner13af11a2010-01-26 03:47:15 +00001081 switch (MJTI->getEntryKind()) {
Richard Osborne95da6052010-03-11 14:58:16 +00001082 case MachineJumpTableInfo::EK_Inline:
1083 return;
Chris Lattner13af11a2010-01-26 03:47:15 +00001084 case MachineJumpTableInfo::EK_BlockAddress: {
1085 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1086 // .word LBB123
Micah Villmow3574eca2012-10-08 16:38:25 +00001087 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
Chris Lattner13af11a2010-01-26 03:47:15 +00001088 "Cross JIT'ing?");
Jim Grosbach124d0332011-03-16 01:21:55 +00001089
Chris Lattner13af11a2010-01-26 03:47:15 +00001090 // For each jump table, map each target in the jump table to the address of
1091 // an emitted MachineBasicBlock.
1092 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
Jim Grosbach124d0332011-03-16 01:21:55 +00001093
Chris Lattner13af11a2010-01-26 03:47:15 +00001094 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1095 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1096 // Store the address of the basic block for this jump table slot in the
1097 // memory we allocated for the jump table in 'initJumpTableInfo'
1098 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1099 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1100 }
1101 break;
1102 }
Jim Grosbach124d0332011-03-16 01:21:55 +00001103
Chris Lattner85fe0782010-01-26 04:05:28 +00001104 case MachineJumpTableInfo::EK_Custom32:
Chris Lattner13af11a2010-01-26 03:47:15 +00001105 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1106 case MachineJumpTableInfo::EK_LabelDifference32: {
Micah Villmow3574eca2012-10-08 16:38:25 +00001107 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001108 // For each jump table, place the offset from the beginning of the table
1109 // to the target address.
1110 int *SlotPtr = (int*)JumpTableBase;
Chris Lattner32ca55f2006-05-03 00:13:06 +00001111
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001112 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1113 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1114 // Store the offset of the basic block for this jump table slot in the
1115 // memory we allocated for the jump table in 'initJumpTableInfo'
Evan Cheng5788d1a2008-12-10 02:32:19 +00001116 uintptr_t Base = (uintptr_t)SlotPtr;
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001117 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Evan Cheng5788d1a2008-12-10 02:32:19 +00001118 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
Chris Lattner13af11a2010-01-26 03:47:15 +00001119 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
Evan Cheng2a3e08b2008-01-05 02:26:58 +00001120 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1121 }
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001122 }
Chris Lattner13af11a2010-01-26 03:47:15 +00001123 break;
1124 }
Akira Hatanaka6c2cf8b2012-02-03 04:33:00 +00001125 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
Craig Topper85814382012-02-07 05:05:23 +00001126 llvm_unreachable(
Akira Hatanaka6c2cf8b2012-02-03 04:33:00 +00001127 "JT Info emission not implemented for GPRel64BlockAddress yet.");
Nate Begeman37efe672006-04-22 18:53:45 +00001128 }
1129}
1130
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +00001131void JITEmitter::startGVStub(const GlobalValue* GV,
Jeffrey Yasskin0261d792009-11-23 22:49:00 +00001132 unsigned StubSize, unsigned Alignment) {
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +00001133 SavedBufferBegin = BufferBegin;
1134 SavedBufferEnd = BufferEnd;
1135 SavedCurBufferPtr = CurBufferPtr;
Eric Christopher116664a2009-11-12 03:12:18 +00001136
Evan Chengce4a70b2008-11-08 08:02:53 +00001137 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
Chris Lattner43b429b2006-05-02 18:27:26 +00001138 BufferEnd = BufferBegin+StubSize+1;
Chris Lattner6125fdd2003-05-09 03:30:07 +00001139}
1140
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +00001141void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1142 SavedBufferBegin = BufferBegin;
1143 SavedBufferEnd = BufferEnd;
1144 SavedCurBufferPtr = CurBufferPtr;
Eric Christopher116664a2009-11-12 03:12:18 +00001145
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +00001146 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
Nate Begemand6b7a242009-02-18 08:31:02 +00001147 BufferEnd = BufferBegin+StubSize+1;
1148}
1149
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +00001150void JITEmitter::finishGVStub() {
Jeffrey Yasskin108c8382009-11-23 23:35:19 +00001151 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
Chris Lattner43b429b2006-05-02 18:27:26 +00001152 NumBytes += getCurrentPCOffset();
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +00001153 BufferBegin = SavedBufferBegin;
1154 BufferEnd = SavedBufferEnd;
1155 CurBufferPtr = SavedCurBufferPtr;
1156}
1157
1158void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1159 const uint8_t *Buffer, size_t Size,
1160 unsigned Alignment) {
1161 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1162 memcpy(IndGV, Buffer, Size);
1163 return IndGV;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001164}
1165
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001166// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1167// in the constant pool that was last emitted with the 'emitConstantPool'
1168// method.
1169//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001170uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
Chris Lattner239862c2006-02-09 04:49:59 +00001171 assert(ConstantNum < ConstantPool->getConstants().size() &&
Misha Brukman3c944972005-04-22 04:08:30 +00001172 "Invalid ConstantPoolIndex!");
Evan Cheng1606e8e2009-03-13 07:51:59 +00001173 return ConstPoolAddresses[ConstantNum];
Chris Lattnerbba1b6d2003-06-01 23:24:36 +00001174}
1175
Nate Begeman37efe672006-04-22 18:53:45 +00001176// getJumpTableEntryAddress - Return the address of the JumpTable with index
1177// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1178//
Evan Cheng5788d1a2008-12-10 02:32:19 +00001179uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman37efe672006-04-22 18:53:45 +00001180 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1181 assert(Index < JT.size() && "Invalid jump table index!");
Eric Christopher116664a2009-11-12 03:12:18 +00001182
Micah Villmow3574eca2012-10-08 16:38:25 +00001183 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
Eric Christopher116664a2009-11-12 03:12:18 +00001184
Chris Lattner071c62f2010-01-25 23:26:13 +00001185 unsigned Offset = 0;
Nate Begeman37efe672006-04-22 18:53:45 +00001186 for (unsigned i = 0; i < Index; ++i)
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001187 Offset += JT[i].MBBs.size();
Eric Christopher116664a2009-11-12 03:12:18 +00001188
Jim Laskeyacd80ac2006-12-14 19:17:33 +00001189 Offset *= EntrySize;
Eric Christopher116664a2009-11-12 03:12:18 +00001190
Evan Cheng5788d1a2008-12-10 02:32:19 +00001191 return (uintptr_t)((char *)JumpTableBase + Offset);
Nate Begeman37efe672006-04-22 18:53:45 +00001192}
1193
Jeffrey Yasskin7a9034c2009-10-27 00:03:05 +00001194void JITEmitter::EmittedFunctionConfig::onDelete(
1195 JITEmitter *Emitter, const Function *F) {
1196 Emitter->deallocateMemForFunction(F);
1197}
1198void JITEmitter::EmittedFunctionConfig::onRAUW(
1199 JITEmitter *, const Function*, const Function*) {
1200 llvm_unreachable("The JIT doesn't know how to handle a"
1201 " RAUW on a value it has emitted.");
1202}
1203
1204
Chris Lattnere993cc22006-05-11 23:08:08 +00001205//===----------------------------------------------------------------------===//
1206// Public interface to this file
1207//===----------------------------------------------------------------------===//
1208
Reid Kleckner27632172009-09-20 23:52:43 +00001209JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1210 TargetMachine &tm) {
1211 return new JITEmitter(jit, JMM, tm);
Chris Lattnere993cc22006-05-11 23:08:08 +00001212}
1213
Chris Lattnere993cc22006-05-11 23:08:08 +00001214// getPointerToFunctionOrStub - If the specified function has been
1215// code-gen'd, return a pointer to the function. If not, compile it, or use
1216// a stub to implement lazy compilation if available.
1217//
1218void *JIT::getPointerToFunctionOrStub(Function *F) {
1219 // If we have already code generated the function, just return the address.
1220 if (void *Addr = getPointerToGlobalIfAvailable(F))
1221 return Addr;
Eric Christopher116664a2009-11-12 03:12:18 +00001222
Chris Lattnere7484012007-02-24 02:57:03 +00001223 // Get a stub if the target supports it.
Sean Silva8ac19952012-10-11 23:30:38 +00001224 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
Jeffrey Yasskin108c8382009-11-23 23:35:19 +00001225 return JE->getJITResolver().getLazyFunctionStub(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001226}
1227
Nate Begemand6b7a242009-02-18 08:31:02 +00001228void JIT::updateFunctionStub(Function *F) {
1229 // Get the empty stub we generated earlier.
Sean Silva8ac19952012-10-11 23:30:38 +00001230 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
Jeffrey Yasskin108c8382009-11-23 23:35:19 +00001231 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1232 void *Addr = getPointerToGlobalIfAvailable(F);
Jeffrey Yasskinaad0d522009-12-17 21:35:29 +00001233 assert(Addr != Stub && "Function must have non-stub address to be updated.");
Nate Begemand6b7a242009-02-18 08:31:02 +00001234
1235 // Tell the target jit info to rewrite the stub at the specified address,
1236 // rather than creating a new one.
Jeffrey Yasskin108c8382009-11-23 23:35:19 +00001237 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +00001238 JE->startGVStub(Stub, layout.Size);
Jeffrey Yasskin108c8382009-11-23 23:35:19 +00001239 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
Jeffrey Yasskin32d7e6e2009-12-15 22:42:46 +00001240 JE->finishGVStub();
Nate Begemand6b7a242009-02-18 08:31:02 +00001241}
1242
Chris Lattnere993cc22006-05-11 23:08:08 +00001243/// freeMachineCodeForFunction - release machine code memory for given Function.
1244///
1245void JIT::freeMachineCodeForFunction(Function *F) {
1246 // Delete translation for this from the ExecutionEngine, so it will get
1247 // retranslated next time it is used.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001248 updateGlobalMapping(F, nullptr);
Chris Lattnere993cc22006-05-11 23:08:08 +00001249
1250 // Free the actual memory for the function body and related stuff.
Sean Silva8ac19952012-10-11 23:30:38 +00001251 static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);
Chris Lattnere993cc22006-05-11 23:08:08 +00001252}