blob: 4d5723a7a1369022c049f9e638d07b37caf326f6 [file] [log] [blame]
Eric Christopher5c896f72011-04-22 03:07:06 +00001//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
Daniel Dunbar7e5d8a72010-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 Kaylord8ffd9c2012-11-06 18:51:59 +000012#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000013#include "llvm/ExecutionEngine/JITMemoryManager.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000014#include "llvm/ExecutionEngine/MCJIT.h"
15#include "llvm/ExecutionEngine/ObjectBuffer.h"
16#include "llvm/ExecutionEngine/ObjectImage.h"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000017#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Function.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000021#include "llvm/IR/Mangler.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000022#include "llvm/IR/Module.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hames173c69f2014-01-08 04:09:09 +000024#include "llvm/Object/Archive.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000025#include "llvm/PassManager.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000026#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000028#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylor1a568c32012-08-07 18:33:00 +000029#include "llvm/Support/MutexGuard.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000030#include "llvm/Target/TargetLowering.h"
Daniel Dunbar7e5d8a72010-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 Pizlo9bc53e82013-05-14 19:29:00 +000047 RTDyldMemoryManager *MemMgr,
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000048 bool GVsWithCode,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000049 TargetMachine *TM) {
Daniel Dunbar7e5d8a72010-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 Pizlo9bc53e82013-05-14 19:29:00 +000055 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
56 GVsWithCode);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000057}
58
Jim Grosbachbea67532012-08-21 15:42:49 +000059MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
60 bool AllocateGVsWithCode)
Andrew Kaylorea395922013-10-01 01:47:35 +000061 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(this, MM), Dyld(&MemMgr),
62 ObjCache(0) {
Jim Grosbach7b162492011-03-18 22:48:41 +000063
Andrew Kaylorc89fc822013-10-24 00:19:14 +000064 OwnedModules.addModule(m);
Micah Villmowcdfe20b2012-10-08 16:38:25 +000065 setDataLayout(TM->getDataLayout());
Andrew Kaylor1a568c32012-08-07 18:33:00 +000066}
67
68MCJIT::~MCJIT() {
Andrew Kaylor4fba0492013-10-21 17:42:06 +000069 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-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 Kaylorc442a762013-10-16 00:14:21 +000081 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000082
Lang Hames173c69f2014-01-08 04:09:09 +000083 LoadedObjectList::iterator it, end;
84 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
85 ObjectImage *Obj = *it;
Chandler Carruthd55d1592013-10-24 09:52:56 +000086 if (Obj) {
87 NotifyFreeingObject(*Obj);
88 delete Obj;
89 }
90 }
Andrew Kaylorea395922013-10-01 01:47:35 +000091 LoadedObjects.clear();
Lang Hames173c69f2014-01-08 04:09:09 +000092
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 Kaylor1a568c32012-08-07 18:33:00 +0000101 delete TM;
102}
103
Andrew Kaylorea395922013-10-01 01:47:35 +0000104void MCJIT::addModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000105 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000106 OwnedModules.addModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000107}
108
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000109bool MCJIT::removeModule(Module *M) {
110 MutexGuard locked(lock);
111 return OwnedModules.removeModule(M);
112}
113
114
115
Lang Hames173c69f2014-01-08 04:09:09 +0000116void MCJIT::addObjectFile(object::ObjectFile *Obj) {
117 ObjectImage *LoadedObject = Dyld.loadObject(Obj);
118 if (!LoadedObject)
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 Kaylorced4e8f2013-04-25 21:02:36 +0000131void MCJIT::setObjectCache(ObjectCache* NewCache) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000132 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000133 ObjCache = NewCache;
134}
135
Andrew Kaylorea395922013-10-01 01:47:35 +0000136ObjectBufferStream* MCJIT::emitObject(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000137 MutexGuard locked(lock);
138
Andrew Kaylorc89fc822013-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 Kaylor1a568c32012-08-07 18:33:00 +0000142
143 PassManager PM;
144
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000145 PM.add(new DataLayout(*TM->getDataLayout()));
Jim Grosbach7b162492011-03-18 22:48:41 +0000146
Andrew Kayloradc70562012-10-02 21:18:39 +0000147 // The RuntimeDyld will take ownership of this shortly
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000148 OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kayloradc70562012-10-02 21:18:39 +0000149
Jim Grosbach7b162492011-03-18 22:48:41 +0000150 // Turn the machine code intermediate representation into bytes in memory
151 // that may be executed.
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000152 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
Jim Grosbach7b162492011-03-18 22:48:41 +0000153 report_fatal_error("Target does not support MC emission!");
154 }
155
156 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000157 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000158 // Flush the output buffer to get the generated code into memory
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000159 CompiledObject->flush();
160
161 // If we have an object cache, tell it about the new object.
162 // Note that we're using the compiled image, not the loaded image (as below).
163 if (ObjCache) {
164 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
165 // to create a temporary object here and delete it after the call.
166 OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
Andrew Kaylorea395922013-10-01 01:47:35 +0000167 ObjCache->notifyObjectCompiled(M, MB.get());
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000168 }
169
170 return CompiledObject.take();
171}
172
Andrew Kaylorea395922013-10-01 01:47:35 +0000173void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000174 // Get a thread lock to make sure we aren't trying to load multiple times
175 MutexGuard locked(lock);
176
Andrew Kaylorea395922013-10-01 01:47:35 +0000177 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000178 assert(OwnedModules.ownsModule(M) &&
179 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000180
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000181 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000182 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000183 return;
184
185 OwningPtr<ObjectBuffer> ObjectToLoad;
186 // Try to load the pre-compiled object from cache if possible
187 if (0 != ObjCache) {
Andrew Kaylorb595f532013-06-28 21:40:16 +0000188 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000189 if (0 != PreCompiledObject.get())
190 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
191 }
192
193 // If the cache did not contain a suitable object, compile the object
194 if (!ObjectToLoad) {
195 ObjectToLoad.reset(emitObject(M));
196 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
197 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000198
199 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000200 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Andrew Kaylorea395922013-10-01 01:47:35 +0000201 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.take());
Lang Hames173c69f2014-01-08 04:09:09 +0000202 LoadedObjects.push_back(LoadedObject);
Andrew Kayloradc70562012-10-02 21:18:39 +0000203 if (!LoadedObject)
Jim Grosbachc114d892011-03-23 19:51:34 +0000204 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000205
Andrew Kayloradc70562012-10-02 21:18:39 +0000206 // FIXME: Make this optional, maybe even move it to a JIT event listener
207 LoadedObject->registerWithDebugger();
208
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000209 NotifyObjectEmitted(*LoadedObject);
210
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000211 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000212}
213
Andrew Kaylorea395922013-10-01 01:47:35 +0000214void MCJIT::finalizeLoadedModules() {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000215 MutexGuard locked(lock);
216
Andrew Kaylorea395922013-10-01 01:47:35 +0000217 // Resolve any outstanding relocations.
218 Dyld.resolveRelocations();
219
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000220 OwnedModules.markAllLoadedModulesAsFinalized();
221
Andrew Kaylorea395922013-10-01 01:47:35 +0000222 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000223 Dyld.registerEHFrames();
224
Andrew Kaylorea395922013-10-01 01:47:35 +0000225 // Set page permissions.
226 MemMgr.finalizeMemory();
227}
228
229// FIXME: Rename this.
230void MCJIT::finalizeObject() {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000231 MutexGuard locked(lock);
232
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000233 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
234 E = OwnedModules.end_added();
235 I != E; ++I) {
236 Module *M = *I;
237 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000238 }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000239
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000240 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000241}
242
243void MCJIT::finalizeModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000244 MutexGuard locked(lock);
245
Andrew Kaylorea395922013-10-01 01:47:35 +0000246 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000247 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000248
249 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000250 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000251 generateCodeForModule(M);
252
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000253 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000254}
255
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000256void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
257 report_fatal_error("not yet implemented");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000258}
259
Andrew Kaylorea395922013-10-01 01:47:35 +0000260uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Rafael Espindola58873562014-01-03 19:21:54 +0000261 Mangler Mang(TM->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000262 SmallString<128> FullName;
263 Mang.getNameWithPrefix(FullName, Name);
264 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000265}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000266
Andrew Kaylorea395922013-10-01 01:47:35 +0000267Module *MCJIT::findModuleForSymbol(const std::string &Name,
268 bool CheckFunctionsOnly) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000269 MutexGuard locked(lock);
270
Andrew Kaylorea395922013-10-01 01:47:35 +0000271 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000272 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
273 E = OwnedModules.end_added();
274 I != E; ++I) {
275 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000276 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000277 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000278 return M;
279 if (!CheckFunctionsOnly) {
280 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000281 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000282 return M;
283 // FIXME: Do we need to worry about global aliases?
284 }
285 }
286 // We didn't find the symbol in any of our modules.
287 return NULL;
288}
289
290uint64_t MCJIT::getSymbolAddress(const std::string &Name,
291 bool CheckFunctionsOnly)
292{
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000293 MutexGuard locked(lock);
294
Andrew Kaylorea395922013-10-01 01:47:35 +0000295 // First, check to see if we already have this symbol.
296 uint64_t Addr = getExistingSymbolAddress(Name);
297 if (Addr)
298 return Addr;
299
Lang Hames173c69f2014-01-08 04:09:09 +0000300 SmallVector<object::Archive*, 2>::iterator I, E;
301 for (I = Archives.begin(), E = Archives.end(); I != E; ++I) {
302 object::Archive *A = *I;
303 // Look for our symbols in each Archive
304 object::Archive::child_iterator ChildIt = A->findSym(Name);
Rafael Espindola23a97502014-01-21 16:09:45 +0000305 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000306 OwningPtr<object::Binary> ChildBin;
307 // FIXME: Support nested archives?
308 if (!ChildIt->getAsBinary(ChildBin) && ChildBin->isObject()) {
309 object::ObjectFile *OF = reinterpret_cast<object::ObjectFile *>(
310 ChildBin.take());
311 // This causes the object file to be loaded.
312 addObjectFile(OF);
313 // The address should be here now.
314 Addr = getExistingSymbolAddress(Name);
315 if (Addr)
316 return Addr;
317 }
318 }
319 }
320
Andrew Kaylorea395922013-10-01 01:47:35 +0000321 // If it hasn't already been generated, see if it's in one of our modules.
322 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
323 if (!M)
324 return 0;
325
Andrew Kaylorea395922013-10-01 01:47:35 +0000326 generateCodeForModule(M);
327
328 // Check the RuntimeDyld table again, it should be there now.
329 return getExistingSymbolAddress(Name);
330}
331
332uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000333 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000334 uint64_t Result = getSymbolAddress(Name, false);
335 if (Result != 0)
336 finalizeLoadedModules();
337 return Result;
338}
339
340uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000341 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000342 uint64_t Result = getSymbolAddress(Name, true);
343 if (Result != 0)
344 finalizeLoadedModules();
345 return Result;
346}
347
348// Deprecated. Use getFunctionAddress instead.
349void *MCJIT::getPointerToFunction(Function *F) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000350 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000351
Jim Grosbachd5274402011-03-22 18:05:27 +0000352 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
353 bool AbortOnFailure = !F->hasExternalWeakLinkage();
354 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
355 addGlobalMapping(F, Addr);
356 return Addr;
357 }
358
Andrew Kaylorea395922013-10-01 01:47:35 +0000359 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000360 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000361
362 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000363 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000364 generateCodeForModule(M);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000365 else if (!OwnedModules.hasModuleBeenLoaded(M))
366 // If this function doesn't belong to one of our modules, we're done.
367 return NULL;
Andrew Kaylorea395922013-10-01 01:47:35 +0000368
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000369 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000370 //
371 // This is the accessor for the target address, so make sure to check the
372 // load address of the symbol, not the local address.
Rafael Espindola58873562014-01-03 19:21:54 +0000373 Mangler Mang(TM->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000374 SmallString<128> Name;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000375 TM->getTargetLowering()->getNameWithPrefix(Name, F, Mang);
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000376 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000377}
378
379void *MCJIT::recompileAndRelinkFunction(Function *F) {
380 report_fatal_error("not yet implemented");
381}
382
383void MCJIT::freeMachineCodeForFunction(Function *F) {
384 report_fatal_error("not yet implemented");
385}
386
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000387void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
388 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
389 for (; I != E; ++I) {
390 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
391 }
392}
393
394void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
395 // Execute global ctors/dtors for each module in the program.
396 runStaticConstructorsDestructorsInModulePtrSet(
397 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
398 runStaticConstructorsDestructorsInModulePtrSet(
399 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
400 runStaticConstructorsDestructorsInModulePtrSet(
401 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
402}
403
404Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
405 ModulePtrSet::iterator I,
406 ModulePtrSet::iterator E) {
407 for (; I != E; ++I) {
408 if (Function *F = (*I)->getFunction(FnName))
409 return F;
410 }
411 return 0;
412}
413
414Function *MCJIT::FindFunctionNamed(const char *FnName) {
415 Function *F = FindFunctionNamedInModulePtrSet(
416 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
417 if (!F)
418 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
419 OwnedModules.end_loaded());
420 if (!F)
421 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
422 OwnedModules.end_finalized());
423 return F;
424}
425
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000426GenericValue MCJIT::runFunction(Function *F,
427 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000428 assert(F && "Function *F was null at entry to run()");
429
Jim Grosbach7b162492011-03-18 22:48:41 +0000430 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000431 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000432 FunctionType *FTy = F->getFunctionType();
433 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000434
435 assert((FTy->getNumParams() == ArgValues.size() ||
436 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
437 "Wrong number of arguments passed into function!");
438 assert(FTy->getNumParams() == ArgValues.size() &&
439 "This doesn't support passing arguments through varargs (yet)!");
440
441 // Handle some common cases first. These cases correspond to common `main'
442 // prototypes.
443 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
444 switch (ArgValues.size()) {
445 case 3:
446 if (FTy->getParamType(0)->isIntegerTy(32) &&
447 FTy->getParamType(1)->isPointerTy() &&
448 FTy->getParamType(2)->isPointerTy()) {
449 int (*PF)(int, char **, const char **) =
450 (int(*)(int, char **, const char **))(intptr_t)FPtr;
451
452 // Call the function.
453 GenericValue rv;
454 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
455 (char **)GVTOP(ArgValues[1]),
456 (const char **)GVTOP(ArgValues[2])));
457 return rv;
458 }
459 break;
460 case 2:
461 if (FTy->getParamType(0)->isIntegerTy(32) &&
462 FTy->getParamType(1)->isPointerTy()) {
463 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
464
465 // Call the function.
466 GenericValue rv;
467 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
468 (char **)GVTOP(ArgValues[1])));
469 return rv;
470 }
471 break;
472 case 1:
473 if (FTy->getNumParams() == 1 &&
474 FTy->getParamType(0)->isIntegerTy(32)) {
475 GenericValue rv;
476 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
477 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
478 return rv;
479 }
480 break;
481 }
482 }
483
484 // Handle cases where no arguments are passed first.
485 if (ArgValues.empty()) {
486 GenericValue rv;
487 switch (RetTy->getTypeID()) {
488 default: llvm_unreachable("Unknown return type for function call!");
489 case Type::IntegerTyID: {
490 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
491 if (BitWidth == 1)
492 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
493 else if (BitWidth <= 8)
494 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
495 else if (BitWidth <= 16)
496 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 32)
498 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
499 else if (BitWidth <= 64)
500 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
501 else
502 llvm_unreachable("Integer types > 64 bits not supported");
503 return rv;
504 }
505 case Type::VoidTyID:
506 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
507 return rv;
508 case Type::FloatTyID:
509 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
510 return rv;
511 case Type::DoubleTyID:
512 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
513 return rv;
514 case Type::X86_FP80TyID:
515 case Type::FP128TyID:
516 case Type::PPC_FP128TyID:
517 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000518 case Type::PointerTyID:
519 return PTOGV(((void*(*)())(intptr_t)FPtr)());
520 }
521 }
522
Craig Toppera2886c22012-02-07 05:05:23 +0000523 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000524}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000525
526void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000527 bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000528 if (!isSymbolSearchingDisabled()) {
529 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000530 if (ptr)
531 return ptr;
532 }
533
534 /// If a LazyFunctionCreator is installed, use it to get/create the function.
535 if (LazyFunctionCreator)
536 if (void *RP = LazyFunctionCreator(Name))
537 return RP;
538
539 if (AbortOnFailure) {
540 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000541 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000542 }
543 return 0;
544}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000545
546void MCJIT::RegisterJITEventListener(JITEventListener *L) {
547 if (L == NULL)
548 return;
549 MutexGuard locked(lock);
550 EventListeners.push_back(L);
551}
552void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
553 if (L == NULL)
554 return;
555 MutexGuard locked(lock);
556 SmallVector<JITEventListener*, 2>::reverse_iterator I=
557 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
558 if (I != EventListeners.rend()) {
559 std::swap(*I, EventListeners.back());
560 EventListeners.pop_back();
561 }
562}
563void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
564 MutexGuard locked(lock);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000565 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000566 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
567 EventListeners[I]->NotifyObjectEmitted(Obj);
568 }
569}
570void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
571 MutexGuard locked(lock);
572 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
573 EventListeners[I]->NotifyFreeingObject(Obj);
574 }
575}
Andrew Kaylorea395922013-10-01 01:47:35 +0000576
577uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
578 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000579 // If the symbols wasn't found and it begins with an underscore, try again
580 // without the underscore.
581 if (!Result && Name[0] == '_')
582 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000583 if (Result)
584 return Result;
585 return ClientMM->getSymbolAddress(Name);
586}