blob: ccaa72a6108dcb60e48a41dcb3c4a94e14d968df [file] [log] [blame]
Eric Christopherbb498ca2011-04-22 03:07:06 +00001//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
Daniel Dunbar6aec2982010-11-17 16:06:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "MCJIT.h"
11#include "llvm/ExecutionEngine/GenericValue.h"
Andrew Kaylor776054d2012-11-06 18:51:59 +000012#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000013#include "llvm/ExecutionEngine/JITMemoryManager.h"
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000014#include "llvm/ExecutionEngine/MCJIT.h"
15#include "llvm/ExecutionEngine/ObjectBuffer.h"
16#include "llvm/ExecutionEngine/ObjectImage.h"
Andrew Kaylord2755af2013-04-29 17:49:40 +000017#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Function.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000021#include "llvm/MC/MCAsmInfo.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000022#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Support/ErrorHandling.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000024#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylorea708d12012-08-07 18:33:00 +000025#include "llvm/Support/MutexGuard.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000026
27using namespace llvm;
28
29namespace {
30
31static struct RegisterJIT {
32 RegisterJIT() { MCJIT::Register(); }
33} JITRegistrator;
34
35}
36
37extern "C" void LLVMLinkInMCJIT() {
38}
39
40ExecutionEngine *MCJIT::createJIT(Module *M,
41 std::string *ErrorStr,
42 JITMemoryManager *JMM,
Daniel Dunbar6aec2982010-11-17 16:06:43 +000043 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000044 TargetMachine *TM) {
Daniel Dunbar6aec2982010-11-17 16:06:43 +000045 // Try to register the program as a source of symbols to resolve against.
46 //
47 // FIXME: Don't do this here.
48 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
49
Andrew Kaylord2755af2013-04-29 17:49:40 +000050 return new MCJIT(M, TM, JMM ? JMM : new SectionMemoryManager(), GVsWithCode);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000051}
52
Jim Grosbach8005bcd2012-08-21 15:42:49 +000053MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
54 bool AllocateGVsWithCode)
Filip Pizlo0e1327e2013-05-01 22:58:00 +000055 : ExecutionEngine(m), TM(tm), Ctx(0),
56 MemMgr(MM ? MM : new SectionMemoryManager()), Dyld(MemMgr),
Andrew Kaylor1c489452013-04-25 21:02:36 +000057 IsLoaded(false), M(m), ObjCache(0) {
Jim Grosbach31649e62011-03-18 22:48:41 +000058
Micah Villmow3574eca2012-10-08 16:38:25 +000059 setDataLayout(TM->getDataLayout());
Andrew Kaylorea708d12012-08-07 18:33:00 +000060}
61
62MCJIT::~MCJIT() {
Andrew Kaylor776054d2012-11-06 18:51:59 +000063 if (LoadedObject)
Andrew Kaylora0828922012-11-06 19:06:46 +000064 NotifyFreeingObject(*LoadedObject.get());
Andrew Kaylorea708d12012-08-07 18:33:00 +000065 delete MemMgr;
66 delete TM;
67}
68
Andrew Kaylor1c489452013-04-25 21:02:36 +000069void MCJIT::setObjectCache(ObjectCache* NewCache) {
70 ObjCache = NewCache;
71}
72
73ObjectBufferStream* MCJIT::emitObject(Module *m) {
Andrew Kaylorea708d12012-08-07 18:33:00 +000074 /// Currently, MCJIT only supports a single module and the module passed to
75 /// this function call is expected to be the contained module. The module
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000076 /// is passed as a parameter here to prepare for multiple module support in
Andrew Kaylorea708d12012-08-07 18:33:00 +000077 /// the future.
78 assert(M == m);
79
80 // Get a thread lock to make sure we aren't trying to compile multiple times
81 MutexGuard locked(lock);
82
83 // FIXME: Track compilation state on a per-module basis when multiple modules
84 // are supported.
85 // Re-compilation is not supported
Andrew Kaylor1c489452013-04-25 21:02:36 +000086 assert(!IsLoaded);
Andrew Kaylorea708d12012-08-07 18:33:00 +000087
88 PassManager PM;
89
Micah Villmow3574eca2012-10-08 16:38:25 +000090 PM.add(new DataLayout(*TM->getDataLayout()));
Jim Grosbach31649e62011-03-18 22:48:41 +000091
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000092 // The RuntimeDyld will take ownership of this shortly
Andrew Kaylor1c489452013-04-25 21:02:36 +000093 OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000094
Jim Grosbach31649e62011-03-18 22:48:41 +000095 // Turn the machine code intermediate representation into bytes in memory
96 // that may be executed.
Andrew Kaylor1c489452013-04-25 21:02:36 +000097 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
Jim Grosbach31649e62011-03-18 22:48:41 +000098 report_fatal_error("Target does not support MC emission!");
99 }
100
101 // Initialize passes.
Andrew Kaylorea708d12012-08-07 18:33:00 +0000102 PM.run(*m);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000103 // Flush the output buffer to get the generated code into memory
Andrew Kaylor1c489452013-04-25 21:02:36 +0000104 CompiledObject->flush();
105
106 // If we have an object cache, tell it about the new object.
107 // Note that we're using the compiled image, not the loaded image (as below).
108 if (ObjCache) {
109 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
110 // to create a temporary object here and delete it after the call.
111 OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
112 ObjCache->notifyObjectCompiled(m, MB.get());
113 }
114
115 return CompiledObject.take();
116}
117
118void MCJIT::loadObject(Module *M) {
119
120 // Get a thread lock to make sure we aren't trying to load multiple times
121 MutexGuard locked(lock);
122
123 // FIXME: Track compilation state on a per-module basis when multiple modules
124 // are supported.
125 // Re-compilation is not supported
126 if (IsLoaded)
127 return;
128
129 OwningPtr<ObjectBuffer> ObjectToLoad;
130 // Try to load the pre-compiled object from cache if possible
131 if (0 != ObjCache) {
132 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObjectCopy(M));
133 if (0 != PreCompiledObject.get())
134 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
135 }
136
137 // If the cache did not contain a suitable object, compile the object
138 if (!ObjectToLoad) {
139 ObjectToLoad.reset(emitObject(M));
140 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
141 }
Jim Grosbachf9229102011-03-22 01:06:42 +0000142
143 // Load the object into the dynamic linker.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000144 // handing off ownership of the buffer
Andrew Kaylor1c489452013-04-25 21:02:36 +0000145 LoadedObject.reset(Dyld.loadObject(ObjectToLoad.take()));
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000146 if (!LoadedObject)
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000147 report_fatal_error(Dyld.getErrorString());
Andrew Kaylorea708d12012-08-07 18:33:00 +0000148
Jim Grosbach69e81322011-04-13 15:28:10 +0000149 // Resolve any relocations.
150 Dyld.resolveRelocations();
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000151
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000152 // FIXME: Make this optional, maybe even move it to a JIT event listener
153 LoadedObject->registerWithDebugger();
154
Andrew Kaylor776054d2012-11-06 18:51:59 +0000155 NotifyObjectEmitted(*LoadedObject);
156
Andrew Kaylorea708d12012-08-07 18:33:00 +0000157 // FIXME: Add support for per-module compilation state
Andrew Kaylor1c489452013-04-25 21:02:36 +0000158 IsLoaded = true;
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000159}
160
Andrew Kaylor28989882012-11-05 20:57:16 +0000161// FIXME: Add a parameter to identify which object is being finalized when
162// MCJIT supports multiple modules.
Andrew Kaylor53608a32012-11-15 23:50:01 +0000163// FIXME: Provide a way to separate code emission, relocations and page
164// protection in the interface.
Andrew Kaylor28989882012-11-05 20:57:16 +0000165void MCJIT::finalizeObject() {
166 // If the module hasn't been compiled, just do that.
Andrew Kaylor1c489452013-04-25 21:02:36 +0000167 if (!IsLoaded) {
168 // If the call to Dyld.resolveRelocations() is removed from loadObject()
Andrew Kaylor28989882012-11-05 20:57:16 +0000169 // we'll need to do that here.
Andrew Kaylor1c489452013-04-25 21:02:36 +0000170 loadObject(M);
Andrew Kaylor53608a32012-11-15 23:50:01 +0000171
172 // Set page permissions.
173 MemMgr->applyPermissions();
174
Andrew Kaylor28989882012-11-05 20:57:16 +0000175 return;
176 }
177
178 // Resolve any relocations.
179 Dyld.resolveRelocations();
Andrew Kaylor53608a32012-11-15 23:50:01 +0000180
181 // Set page permissions.
182 MemMgr->applyPermissions();
Andrew Kaylor28989882012-11-05 20:57:16 +0000183}
184
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000185void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
186 report_fatal_error("not yet implemented");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000187}
188
189void *MCJIT::getPointerToFunction(Function *F) {
Jim Grosbach35ed8422012-09-05 16:50:40 +0000190 // FIXME: This should really return a uint64_t since it's a pointer in the
191 // target address space, not our local address space. That's part of the
192 // ExecutionEngine interface, though. Fix that when the old JIT finally
193 // dies.
194
Andrew Kaylorea708d12012-08-07 18:33:00 +0000195 // FIXME: Add support for per-module compilation state
Andrew Kaylor1c489452013-04-25 21:02:36 +0000196 if (!IsLoaded)
197 loadObject(M);
Andrew Kaylorea708d12012-08-07 18:33:00 +0000198
Jim Grosbach34714a02011-03-22 18:05:27 +0000199 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
200 bool AbortOnFailure = !F->hasExternalWeakLinkage();
201 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
202 addGlobalMapping(F, Addr);
203 return Addr;
204 }
205
Andrew Kaylorea708d12012-08-07 18:33:00 +0000206 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000207 // FIXME: Should we be using the mangler for this? Probably.
Jim Grosbach35ed8422012-09-05 16:50:40 +0000208 //
209 // This is the accessor for the target address, so make sure to check the
210 // load address of the symbol, not the local address.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000211 StringRef BaseName = F->getName();
212 if (BaseName[0] == '\1')
Jim Grosbach35ed8422012-09-05 16:50:40 +0000213 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
214 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
Jim Grosbachc0ceedb2011-05-19 00:45:05 +0000215 + BaseName).str());
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000216}
217
218void *MCJIT::recompileAndRelinkFunction(Function *F) {
219 report_fatal_error("not yet implemented");
220}
221
222void MCJIT::freeMachineCodeForFunction(Function *F) {
223 report_fatal_error("not yet implemented");
224}
225
226GenericValue MCJIT::runFunction(Function *F,
227 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000228 assert(F && "Function *F was null at entry to run()");
229
Jim Grosbach31649e62011-03-18 22:48:41 +0000230 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000231 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000232 FunctionType *FTy = F->getFunctionType();
233 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-03-22 18:05:27 +0000234
235 assert((FTy->getNumParams() == ArgValues.size() ||
236 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
237 "Wrong number of arguments passed into function!");
238 assert(FTy->getNumParams() == ArgValues.size() &&
239 "This doesn't support passing arguments through varargs (yet)!");
240
241 // Handle some common cases first. These cases correspond to common `main'
242 // prototypes.
243 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
244 switch (ArgValues.size()) {
245 case 3:
246 if (FTy->getParamType(0)->isIntegerTy(32) &&
247 FTy->getParamType(1)->isPointerTy() &&
248 FTy->getParamType(2)->isPointerTy()) {
249 int (*PF)(int, char **, const char **) =
250 (int(*)(int, char **, const char **))(intptr_t)FPtr;
251
252 // Call the function.
253 GenericValue rv;
254 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
255 (char **)GVTOP(ArgValues[1]),
256 (const char **)GVTOP(ArgValues[2])));
257 return rv;
258 }
259 break;
260 case 2:
261 if (FTy->getParamType(0)->isIntegerTy(32) &&
262 FTy->getParamType(1)->isPointerTy()) {
263 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
264
265 // Call the function.
266 GenericValue rv;
267 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
268 (char **)GVTOP(ArgValues[1])));
269 return rv;
270 }
271 break;
272 case 1:
273 if (FTy->getNumParams() == 1 &&
274 FTy->getParamType(0)->isIntegerTy(32)) {
275 GenericValue rv;
276 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
277 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
278 return rv;
279 }
280 break;
281 }
282 }
283
284 // Handle cases where no arguments are passed first.
285 if (ArgValues.empty()) {
286 GenericValue rv;
287 switch (RetTy->getTypeID()) {
288 default: llvm_unreachable("Unknown return type for function call!");
289 case Type::IntegerTyID: {
290 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
291 if (BitWidth == 1)
292 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
293 else if (BitWidth <= 8)
294 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
295 else if (BitWidth <= 16)
296 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
297 else if (BitWidth <= 32)
298 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
299 else if (BitWidth <= 64)
300 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
301 else
302 llvm_unreachable("Integer types > 64 bits not supported");
303 return rv;
304 }
305 case Type::VoidTyID:
306 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
307 return rv;
308 case Type::FloatTyID:
309 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
310 return rv;
311 case Type::DoubleTyID:
312 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
313 return rv;
314 case Type::X86_FP80TyID:
315 case Type::FP128TyID:
316 case Type::PPC_FP128TyID:
317 llvm_unreachable("long double not supported yet");
Jim Grosbach34714a02011-03-22 18:05:27 +0000318 case Type::PointerTyID:
319 return PTOGV(((void*(*)())(intptr_t)FPtr)());
320 }
321 }
322
Craig Topper85814382012-02-07 05:05:23 +0000323 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000324}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000325
326void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000327 bool AbortOnFailure) {
Andrew Kaylorea708d12012-08-07 18:33:00 +0000328 // FIXME: Add support for per-module compilation state
Andrew Kaylor1c489452013-04-25 21:02:36 +0000329 if (!IsLoaded)
330 loadObject(M);
Andrew Kaylorea708d12012-08-07 18:33:00 +0000331
Danil Malyshev30b9e322012-03-28 21:46:36 +0000332 if (!isSymbolSearchingDisabled() && MemMgr) {
333 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
334 if (ptr)
335 return ptr;
336 }
337
338 /// If a LazyFunctionCreator is installed, use it to get/create the function.
339 if (LazyFunctionCreator)
340 if (void *RP = LazyFunctionCreator(Name))
341 return RP;
342
343 if (AbortOnFailure) {
344 report_fatal_error("Program used external function '"+Name+
Eli Bendersky5fe01982012-04-29 12:40:47 +0000345 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000346 }
347 return 0;
348}
Andrew Kaylor776054d2012-11-06 18:51:59 +0000349
350void MCJIT::RegisterJITEventListener(JITEventListener *L) {
351 if (L == NULL)
352 return;
353 MutexGuard locked(lock);
354 EventListeners.push_back(L);
355}
356void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
357 if (L == NULL)
358 return;
359 MutexGuard locked(lock);
360 SmallVector<JITEventListener*, 2>::reverse_iterator I=
361 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
362 if (I != EventListeners.rend()) {
363 std::swap(*I, EventListeners.back());
364 EventListeners.pop_back();
365 }
366}
367void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
368 MutexGuard locked(lock);
369 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
370 EventListeners[I]->NotifyObjectEmitted(Obj);
371 }
372}
373void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
374 MutexGuard locked(lock);
375 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
376 EventListeners[I]->NotifyFreeingObject(Obj);
377 }
378}