blob: 49b67275615cb1d63aa00b9dafd04bd29ef7480f [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"
Stephen Hines36b56882014-04-23 16:57:46 -070021#include "llvm/IR/Mangler.h"
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000022#include "llvm/IR/Module.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000023#include "llvm/MC/MCAsmInfo.h"
Stephen Hines36b56882014-04-23 16:57:46 -070024#include "llvm/Object/Archive.h"
25#include "llvm/PassManager.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000026#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/Support/ErrorHandling.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000028#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylorea708d12012-08-07 18:33:00 +000029#include "llvm/Support/MutexGuard.h"
Stephen Hines36b56882014-04-23 16:57:46 -070030#include "llvm/Target/TargetLowering.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000031
32using namespace llvm;
33
34namespace {
35
36static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
38} JITRegistrator;
39
40}
41
42extern "C" void LLVMLinkInMCJIT() {
43}
44
45ExecutionEngine *MCJIT::createJIT(Module *M,
46 std::string *ErrorStr,
Filip Pizlo13a3cf12013-05-14 19:29:00 +000047 RTDyldMemoryManager *MemMgr,
Daniel Dunbar6aec2982010-11-17 16:06:43 +000048 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000049 TargetMachine *TM) {
Daniel Dunbar6aec2982010-11-17 16:06:43 +000050 // Try to register the program as a source of symbols to resolve against.
51 //
52 // FIXME: Don't do this here.
53 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
54
Filip Pizlo13a3cf12013-05-14 19:29:00 +000055 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
56 GVsWithCode);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000057}
58
Jim Grosbach8005bcd2012-08-21 15:42:49 +000059MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
60 bool AllocateGVsWithCode)
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000061 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(this, MM), Dyld(&MemMgr),
62 ObjCache(0) {
Jim Grosbach31649e62011-03-18 22:48:41 +000063
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +000064 OwnedModules.addModule(m);
Micah Villmow3574eca2012-10-08 16:38:25 +000065 setDataLayout(TM->getDataLayout());
Andrew Kaylorea708d12012-08-07 18:33:00 +000066}
67
68MCJIT::~MCJIT() {
Andrew Kaylor61694532013-10-21 17:42:06 +000069 MutexGuard locked(lock);
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +000070 // FIXME: We are managing our modules, so we do not want the base class
71 // ExecutionEngine to manage them as well. To avoid double destruction
72 // of the first (and only) module added in ExecutionEngine constructor
73 // we remove it from EE and will destruct it ourselves.
74 //
75 // It may make sense to move our module manager (based on SmallStPtr) back
76 // into EE if the JIT and Interpreter can live with it.
77 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
78 // runStaticConstructorsDestructors could be moved back to EE as well.
79 //
80 Modules.clear();
Andrew Kaylor43507d02013-10-16 00:14:21 +000081 Dyld.deregisterEHFrames();
Chandler Carruth81798732013-10-24 09:52:56 +000082
Stephen Hines36b56882014-04-23 16:57:46 -070083 LoadedObjectList::iterator it, end;
84 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
85 ObjectImage *Obj = *it;
Chandler Carruth81798732013-10-24 09:52:56 +000086 if (Obj) {
87 NotifyFreeingObject(*Obj);
88 delete Obj;
89 }
90 }
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000091 LoadedObjects.clear();
Stephen Hines36b56882014-04-23 16:57:46 -070092
93
94 SmallVector<object::Archive *, 2>::iterator ArIt, ArEnd;
95 for (ArIt = Archives.begin(), ArEnd = Archives.end(); ArIt != ArEnd; ++ArIt) {
96 object::Archive *A = *ArIt;
97 delete A;
98 }
99 Archives.clear();
100
Andrew Kaylorea708d12012-08-07 18:33:00 +0000101 delete TM;
102}
103
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000104void MCJIT::addModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000105 MutexGuard locked(lock);
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000106 OwnedModules.addModule(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000107}
108
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000109bool MCJIT::removeModule(Module *M) {
110 MutexGuard locked(lock);
111 return OwnedModules.removeModule(M);
112}
113
114
115
Stephen Hines36b56882014-04-23 16:57:46 -0700116void MCJIT::addObjectFile(object::ObjectFile *Obj) {
117 ObjectImage *LoadedObject = Dyld.loadObject(Obj);
118 if (!LoadedObject || Dyld.hasError())
119 report_fatal_error(Dyld.getErrorString());
120
121 LoadedObjects.push_back(LoadedObject);
122
123 NotifyObjectEmitted(*LoadedObject);
124}
125
126void MCJIT::addArchive(object::Archive *A) {
127 Archives.push_back(A);
128}
129
130
Andrew Kaylor1c489452013-04-25 21:02:36 +0000131void MCJIT::setObjectCache(ObjectCache* NewCache) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000132 MutexGuard locked(lock);
Andrew Kaylor1c489452013-04-25 21:02:36 +0000133 ObjCache = NewCache;
134}
135
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000136ObjectBufferStream* MCJIT::emitObject(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000137 MutexGuard locked(lock);
138
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000139 // This must be a module which has already been added but not loaded to this
140 // MCJIT instance, since these conditions are tested by our caller,
141 // generateCodeForModule.
Andrew Kaylorea708d12012-08-07 18:33:00 +0000142
143 PassManager PM;
144
Stephen Hines36b56882014-04-23 16:57:46 -0700145 M->setDataLayout(TM->getDataLayout());
146 PM.add(new DataLayoutPass(M));
Jim Grosbach31649e62011-03-18 22:48:41 +0000147
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000148 // The RuntimeDyld will take ownership of this shortly
Stephen Hines36b56882014-04-23 16:57:46 -0700149 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000150
Jim Grosbach31649e62011-03-18 22:48:41 +0000151 // Turn the machine code intermediate representation into bytes in memory
152 // that may be executed.
Andrew Kaylor1c489452013-04-25 21:02:36 +0000153 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
Jim Grosbach31649e62011-03-18 22:48:41 +0000154 report_fatal_error("Target does not support MC emission!");
155 }
156
157 // Initialize passes.
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000158 PM.run(*M);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000159 // Flush the output buffer to get the generated code into memory
Andrew Kaylor1c489452013-04-25 21:02:36 +0000160 CompiledObject->flush();
161
162 // If we have an object cache, tell it about the new object.
163 // Note that we're using the compiled image, not the loaded image (as below).
164 if (ObjCache) {
165 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
166 // to create a temporary object here and delete it after the call.
Stephen Hines36b56882014-04-23 16:57:46 -0700167 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000168 ObjCache->notifyObjectCompiled(M, MB.get());
Andrew Kaylor1c489452013-04-25 21:02:36 +0000169 }
170
Stephen Hines36b56882014-04-23 16:57:46 -0700171 return CompiledObject.release();
Andrew Kaylor1c489452013-04-25 21:02:36 +0000172}
173
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000174void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000175 // Get a thread lock to make sure we aren't trying to load multiple times
176 MutexGuard locked(lock);
177
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000178 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000179 assert(OwnedModules.ownsModule(M) &&
180 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylor1c489452013-04-25 21:02:36 +0000181
Andrew Kaylor1c489452013-04-25 21:02:36 +0000182 // Re-compilation is not supported
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000183 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylor1c489452013-04-25 21:02:36 +0000184 return;
185
Stephen Hines36b56882014-04-23 16:57:46 -0700186 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylor1c489452013-04-25 21:02:36 +0000187 // Try to load the pre-compiled object from cache if possible
188 if (0 != ObjCache) {
Stephen Hines36b56882014-04-23 16:57:46 -0700189 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
Andrew Kaylor1c489452013-04-25 21:02:36 +0000190 if (0 != PreCompiledObject.get())
Stephen Hines36b56882014-04-23 16:57:46 -0700191 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
Andrew Kaylor1c489452013-04-25 21:02:36 +0000192 }
193
194 // If the cache did not contain a suitable object, compile the object
195 if (!ObjectToLoad) {
196 ObjectToLoad.reset(emitObject(M));
197 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
198 }
Jim Grosbachf9229102011-03-22 01:06:42 +0000199
200 // Load the object into the dynamic linker.
Stephen Hines36b56882014-04-23 16:57:46 -0700201 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
202 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
203 LoadedObjects.push_back(LoadedObject);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000204 if (!LoadedObject)
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000205 report_fatal_error(Dyld.getErrorString());
Andrew Kaylorea708d12012-08-07 18:33:00 +0000206
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000207 // FIXME: Make this optional, maybe even move it to a JIT event listener
208 LoadedObject->registerWithDebugger();
209
Andrew Kaylor776054d2012-11-06 18:51:59 +0000210 NotifyObjectEmitted(*LoadedObject);
211
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000212 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000213}
214
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000215void MCJIT::finalizeLoadedModules() {
Andrew Kaylor61694532013-10-21 17:42:06 +0000216 MutexGuard locked(lock);
217
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000218 // Resolve any outstanding relocations.
219 Dyld.resolveRelocations();
220
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000221 OwnedModules.markAllLoadedModulesAsFinalized();
222
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000223 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000224 Dyld.registerEHFrames();
225
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000226 // Set page permissions.
227 MemMgr.finalizeMemory();
228}
229
230// FIXME: Rename this.
231void MCJIT::finalizeObject() {
Andrew Kaylor61694532013-10-21 17:42:06 +0000232 MutexGuard locked(lock);
233
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000234 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
235 E = OwnedModules.end_added();
236 I != E; ++I) {
237 Module *M = *I;
238 generateCodeForModule(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000239 }
Andrew Kaylor53608a32012-11-15 23:50:01 +0000240
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000241 finalizeLoadedModules();
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000242}
243
244void MCJIT::finalizeModule(Module *M) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000245 MutexGuard locked(lock);
246
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000247 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000248 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000249
250 // If the module hasn't been compiled, just do that.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000251 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000252 generateCodeForModule(M);
253
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000254 finalizeLoadedModules();
Andrew Kaylor28989882012-11-05 20:57:16 +0000255}
256
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000257void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
258 report_fatal_error("not yet implemented");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000259}
260
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000261uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Stephen Hines36b56882014-04-23 16:57:46 -0700262 Mangler Mang(TM->getDataLayout());
263 SmallString<128> FullName;
264 Mang.getNameWithPrefix(FullName, Name);
265 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000266}
Jim Grosbach35ed8422012-09-05 16:50:40 +0000267
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000268Module *MCJIT::findModuleForSymbol(const std::string &Name,
269 bool CheckFunctionsOnly) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000270 MutexGuard locked(lock);
271
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000272 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000273 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
274 E = OwnedModules.end_added();
275 I != E; ++I) {
276 Module *M = *I;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000277 Function *F = M->getFunction(Name);
Andrew Kaylor59bbf5a2013-11-15 22:10:21 +0000278 if (F && !F->isDeclaration())
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000279 return M;
280 if (!CheckFunctionsOnly) {
281 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor59bbf5a2013-11-15 22:10:21 +0000282 if (G && !G->isDeclaration())
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000283 return M;
284 // FIXME: Do we need to worry about global aliases?
285 }
286 }
287 // We didn't find the symbol in any of our modules.
288 return NULL;
289}
290
291uint64_t MCJIT::getSymbolAddress(const std::string &Name,
292 bool CheckFunctionsOnly)
293{
Andrew Kaylor61694532013-10-21 17:42:06 +0000294 MutexGuard locked(lock);
295
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000296 // First, check to see if we already have this symbol.
297 uint64_t Addr = getExistingSymbolAddress(Name);
298 if (Addr)
299 return Addr;
300
Stephen Hines36b56882014-04-23 16:57:46 -0700301 SmallVector<object::Archive*, 2>::iterator I, E;
302 for (I = Archives.begin(), E = Archives.end(); I != E; ++I) {
303 object::Archive *A = *I;
304 // Look for our symbols in each Archive
305 object::Archive::child_iterator ChildIt = A->findSym(Name);
306 if (ChildIt != A->child_end()) {
307 std::unique_ptr<object::Binary> ChildBin;
308 // FIXME: Support nested archives?
309 if (!ChildIt->getAsBinary(ChildBin) && ChildBin->isObject()) {
310 object::ObjectFile *OF = reinterpret_cast<object::ObjectFile *>(
311 ChildBin.release());
312 // This causes the object file to be loaded.
313 addObjectFile(OF);
314 // The address should be here now.
315 Addr = getExistingSymbolAddress(Name);
316 if (Addr)
317 return Addr;
318 }
319 }
320 }
321
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000322 // If it hasn't already been generated, see if it's in one of our modules.
323 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
324 if (!M)
325 return 0;
326
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000327 generateCodeForModule(M);
328
329 // Check the RuntimeDyld table again, it should be there now.
330 return getExistingSymbolAddress(Name);
331}
332
333uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000334 MutexGuard locked(lock);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000335 uint64_t Result = getSymbolAddress(Name, false);
336 if (Result != 0)
337 finalizeLoadedModules();
338 return Result;
339}
340
341uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000342 MutexGuard locked(lock);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000343 uint64_t Result = getSymbolAddress(Name, true);
344 if (Result != 0)
345 finalizeLoadedModules();
346 return Result;
347}
348
349// Deprecated. Use getFunctionAddress instead.
350void *MCJIT::getPointerToFunction(Function *F) {
Andrew Kaylor61694532013-10-21 17:42:06 +0000351 MutexGuard locked(lock);
Andrew Kaylorea708d12012-08-07 18:33:00 +0000352
Jim Grosbach34714a02011-03-22 18:05:27 +0000353 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
354 bool AbortOnFailure = !F->hasExternalWeakLinkage();
355 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
356 addGlobalMapping(F, Addr);
357 return Addr;
358 }
359
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000360 Module *M = F->getParent();
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000361 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000362
363 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000364 if (HasBeenAddedButNotLoaded)
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000365 generateCodeForModule(M);
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000366 else if (!OwnedModules.hasModuleBeenLoaded(M))
367 // If this function doesn't belong to one of our modules, we're done.
368 return NULL;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000369
Andrew Kaylorea708d12012-08-07 18:33:00 +0000370 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach35ed8422012-09-05 16:50:40 +0000371 //
372 // This is the accessor for the target address, so make sure to check the
373 // load address of the symbol, not the local address.
Stephen Hines36b56882014-04-23 16:57:46 -0700374 Mangler Mang(TM->getDataLayout());
375 SmallString<128> Name;
376 TM->getNameWithPrefix(Name, F, Mang);
377 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000378}
379
380void *MCJIT::recompileAndRelinkFunction(Function *F) {
381 report_fatal_error("not yet implemented");
382}
383
384void MCJIT::freeMachineCodeForFunction(Function *F) {
385 report_fatal_error("not yet implemented");
386}
387
Andrew Kaylor2ad18ef2013-10-24 00:19:14 +0000388void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
389 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
390 for (; I != E; ++I) {
391 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
392 }
393}
394
395void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
396 // Execute global ctors/dtors for each module in the program.
397 runStaticConstructorsDestructorsInModulePtrSet(
398 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
399 runStaticConstructorsDestructorsInModulePtrSet(
400 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
401 runStaticConstructorsDestructorsInModulePtrSet(
402 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
403}
404
405Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
406 ModulePtrSet::iterator I,
407 ModulePtrSet::iterator E) {
408 for (; I != E; ++I) {
409 if (Function *F = (*I)->getFunction(FnName))
410 return F;
411 }
412 return 0;
413}
414
415Function *MCJIT::FindFunctionNamed(const char *FnName) {
416 Function *F = FindFunctionNamedInModulePtrSet(
417 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
418 if (!F)
419 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
420 OwnedModules.end_loaded());
421 if (!F)
422 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
423 OwnedModules.end_finalized());
424 return F;
425}
426
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000427GenericValue MCJIT::runFunction(Function *F,
428 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000429 assert(F && "Function *F was null at entry to run()");
430
Jim Grosbach31649e62011-03-18 22:48:41 +0000431 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000432 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000433 FunctionType *FTy = F->getFunctionType();
434 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-03-22 18:05:27 +0000435
436 assert((FTy->getNumParams() == ArgValues.size() ||
437 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
438 "Wrong number of arguments passed into function!");
439 assert(FTy->getNumParams() == ArgValues.size() &&
440 "This doesn't support passing arguments through varargs (yet)!");
441
442 // Handle some common cases first. These cases correspond to common `main'
443 // prototypes.
444 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
445 switch (ArgValues.size()) {
446 case 3:
447 if (FTy->getParamType(0)->isIntegerTy(32) &&
448 FTy->getParamType(1)->isPointerTy() &&
449 FTy->getParamType(2)->isPointerTy()) {
450 int (*PF)(int, char **, const char **) =
451 (int(*)(int, char **, const char **))(intptr_t)FPtr;
452
453 // Call the function.
454 GenericValue rv;
455 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
456 (char **)GVTOP(ArgValues[1]),
457 (const char **)GVTOP(ArgValues[2])));
458 return rv;
459 }
460 break;
461 case 2:
462 if (FTy->getParamType(0)->isIntegerTy(32) &&
463 FTy->getParamType(1)->isPointerTy()) {
464 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
465
466 // Call the function.
467 GenericValue rv;
468 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
469 (char **)GVTOP(ArgValues[1])));
470 return rv;
471 }
472 break;
473 case 1:
474 if (FTy->getNumParams() == 1 &&
475 FTy->getParamType(0)->isIntegerTy(32)) {
476 GenericValue rv;
477 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
478 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
479 return rv;
480 }
481 break;
482 }
483 }
484
485 // Handle cases where no arguments are passed first.
486 if (ArgValues.empty()) {
487 GenericValue rv;
488 switch (RetTy->getTypeID()) {
489 default: llvm_unreachable("Unknown return type for function call!");
490 case Type::IntegerTyID: {
491 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
492 if (BitWidth == 1)
493 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
494 else if (BitWidth <= 8)
495 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
496 else if (BitWidth <= 16)
497 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
498 else if (BitWidth <= 32)
499 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
500 else if (BitWidth <= 64)
501 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
502 else
503 llvm_unreachable("Integer types > 64 bits not supported");
504 return rv;
505 }
506 case Type::VoidTyID:
507 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
508 return rv;
509 case Type::FloatTyID:
510 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
511 return rv;
512 case Type::DoubleTyID:
513 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
514 return rv;
515 case Type::X86_FP80TyID:
516 case Type::FP128TyID:
517 case Type::PPC_FP128TyID:
518 llvm_unreachable("long double not supported yet");
Jim Grosbach34714a02011-03-22 18:05:27 +0000519 case Type::PointerTyID:
520 return PTOGV(((void*(*)())(intptr_t)FPtr)());
521 }
522 }
523
Craig Topper85814382012-02-07 05:05:23 +0000524 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000525}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000526
527void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000528 bool AbortOnFailure) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000529 if (!isSymbolSearchingDisabled()) {
530 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshev30b9e322012-03-28 21:46:36 +0000531 if (ptr)
532 return ptr;
533 }
534
535 /// If a LazyFunctionCreator is installed, use it to get/create the function.
536 if (LazyFunctionCreator)
537 if (void *RP = LazyFunctionCreator(Name))
538 return RP;
539
540 if (AbortOnFailure) {
541 report_fatal_error("Program used external function '"+Name+
Eli Bendersky5fe01982012-04-29 12:40:47 +0000542 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000543 }
544 return 0;
545}
Andrew Kaylor776054d2012-11-06 18:51:59 +0000546
547void MCJIT::RegisterJITEventListener(JITEventListener *L) {
548 if (L == NULL)
549 return;
550 MutexGuard locked(lock);
551 EventListeners.push_back(L);
552}
553void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
554 if (L == NULL)
555 return;
556 MutexGuard locked(lock);
557 SmallVector<JITEventListener*, 2>::reverse_iterator I=
558 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
559 if (I != EventListeners.rend()) {
560 std::swap(*I, EventListeners.back());
561 EventListeners.pop_back();
562 }
563}
564void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
565 MutexGuard locked(lock);
Andrew Kaylorb868e912013-10-04 00:49:38 +0000566 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylor776054d2012-11-06 18:51:59 +0000567 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
568 EventListeners[I]->NotifyObjectEmitted(Obj);
569 }
570}
571void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
572 MutexGuard locked(lock);
573 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
574 EventListeners[I]->NotifyFreeingObject(Obj);
575 }
576}
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000577
578uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
579 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor52c90162013-10-01 16:42:50 +0000580 // If the symbols wasn't found and it begins with an underscore, try again
581 // without the underscore.
582 if (!Result && Name[0] == '_')
583 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000584 if (Result)
585 return Result;
586 return ClientMM->getSymbolAddress(Name);
587}