blob: 8f1662f6ee7c74b36d096d803f62cae0ad925a1c [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"
Andrew Kayloradc70562012-10-02 21:18:39 +000013#include "llvm/ExecutionEngine/MCJIT.h"
14#include "llvm/ExecutionEngine/ObjectBuffer.h"
15#include "llvm/ExecutionEngine/ObjectImage.h"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000016#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/Function.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000020#include "llvm/IR/Mangler.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000021#include "llvm/IR/Module.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000022#include "llvm/MC/MCAsmInfo.h"
Lang Hames173c69f2014-01-08 04:09:09 +000023#include "llvm/Object/Archive.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000024#include "llvm/PassManager.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000025#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000027#include "llvm/Support/MemoryBuffer.h"
Zachary Turnerc04b8922014-06-20 21:07:14 +000028#include "llvm/Support/MutexGuard.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000029#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000030#include "llvm/Target/TargetSubtargetInfo.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
Rafael Espindola2a8a2792014-08-19 04:04:25 +000045ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000046 std::string *ErrorStr,
Filip Pizlo9bc53e82013-05-14 19:29:00 +000047 RTDyldMemoryManager *MemMgr,
David Blaikie196e3232014-09-02 22:41:07 +000048 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000049 // Try to register the program as a source of symbols to resolve against.
50 //
51 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000052 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000053
David Blaikie196e3232014-09-02 22:41:07 +000054 return new MCJIT(std::move(M), std::move(TM),
Rafael Espindola2a8a2792014-08-19 04:04:25 +000055 MemMgr ? MemMgr : new SectionMemoryManager());
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000056}
57
David Blaikie196e3232014-09-02 22:41:07 +000058MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
Rafael Espindola2a8a2792014-08-19 04:04:25 +000059 RTDyldMemoryManager *MM)
David Blaikie196e3232014-09-02 22:41:07 +000060 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
61 MemMgr(this, MM), Dyld(&MemMgr), ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000062 // FIXME: We are managing our modules, so we do not want the base class
63 // ExecutionEngine to manage them as well. To avoid double destruction
64 // of the first (and only) module added in ExecutionEngine constructor
65 // we remove it from EE and will destruct it ourselves.
66 //
67 // It may make sense to move our module manager (based on SmallStPtr) back
68 // into EE if the JIT and Interpreter can live with it.
69 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
70 // runStaticConstructorsDestructors could be moved back to EE as well.
71 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000072 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000073 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000074
75 OwnedModules.addModule(std::move(First));
76 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
77}
78
79MCJIT::~MCJIT() {
80 MutexGuard locked(lock);
81
Andrew Kaylorc442a762013-10-16 00:14:21 +000082 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000083
David Blaikieed9709d2014-09-03 19:48:09 +000084 for (auto &Obj : LoadedObjects)
85 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +000086 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +000087
Lang Hames173c69f2014-01-08 04:09:09 +000088 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +000089}
90
Rafael Espindola2a8a2792014-08-19 04:04:25 +000091void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000092 MutexGuard locked(lock);
Rafael Espindola2a8a2792014-08-19 04:04:25 +000093 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +000094}
95
Andrew Kaylorc89fc822013-10-24 00:19:14 +000096bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000097 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000098 return OwnedModules.removeModule(M);
99}
100
David Blaikie7a1e7752014-04-29 21:52:46 +0000101void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
David Blaikieed9709d2014-09-03 19:48:09 +0000102 std::unique_ptr<ObjectImage> LoadedObject = Dyld.loadObject(std::move(Obj));
Juergen Ributzka6ff29a72014-03-26 18:19:27 +0000103 if (!LoadedObject || Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000104 report_fatal_error(Dyld.getErrorString());
105
Lang Hames173c69f2014-01-08 04:09:09 +0000106 NotifyObjectEmitted(*LoadedObject);
David Blaikie168861a2014-09-04 18:37:31 +0000107
108 LoadedObjects.push_back(std::move(LoadedObject));
Lang Hames173c69f2014-01-08 04:09:09 +0000109}
110
Rafael Espindola7271c192014-08-26 21:04:04 +0000111void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
112 addObjectFile(std::move(Obj.getBinary()));
113 Buffers.push_back(std::move(Obj.getBuffer()));
114}
115
Rafael Espindola48af1c22014-08-19 18:44:46 +0000116void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000117 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000118}
119
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000120void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000121 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000122 ObjCache = NewCache;
123}
124
David Blaikied1101572014-09-03 19:57:35 +0000125std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000126 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000127
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000128 // This must be a module which has already been added but not loaded to this
129 // MCJIT instance, since these conditions are tested by our caller,
130 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000131
132 PassManager PM;
133
Eric Christopherd9134482014-08-04 21:25:23 +0000134 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindolac435adc2014-09-10 21:27:43 +0000135 PM.add(new DataLayoutPass());
Jim Grosbach7b162492011-03-18 22:48:41 +0000136
Andrew Kayloradc70562012-10-02 21:18:39 +0000137 // The RuntimeDyld will take ownership of this shortly
Ahmed Charles56440fd2014-03-06 05:51:42 +0000138 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kayloradc70562012-10-02 21:18:39 +0000139
Jim Grosbach7b162492011-03-18 22:48:41 +0000140 // Turn the machine code intermediate representation into bytes in memory
141 // that may be executed.
Lang Hamesbc876012014-04-18 06:48:23 +0000142 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
143 !getVerifyModules())) {
Jim Grosbach7b162492011-03-18 22:48:41 +0000144 report_fatal_error("Target does not support MC emission!");
145 }
146
147 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000148 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000149 // Flush the output buffer to get the generated code into memory
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000150 CompiledObject->flush();
151
152 // If we have an object cache, tell it about the new object.
153 // Note that we're using the compiled image, not the loaded image (as below).
154 if (ObjCache) {
155 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
156 // to create a temporary object here and delete it after the call.
Rafael Espindola48af1c22014-08-19 18:44:46 +0000157 MemoryBufferRef MB = CompiledObject->getMemBuffer();
158 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000159 }
160
David Blaikied1101572014-09-03 19:57:35 +0000161 return CompiledObject;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000162}
163
Andrew Kaylorea395922013-10-01 01:47:35 +0000164void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000165 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000166 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000167
Andrew Kaylorea395922013-10-01 01:47:35 +0000168 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000169 assert(OwnedModules.ownsModule(M) &&
170 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000171
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000172 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000173 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000174 return;
175
Ahmed Charles56440fd2014-03-06 05:51:42 +0000176 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000177 // Try to load the pre-compiled object from cache if possible
Craig Topper353eda42014-04-24 06:44:33 +0000178 if (ObjCache) {
David Blaikieed9709d2014-09-03 19:48:09 +0000179 if (std::unique_ptr<MemoryBuffer> PreCompiledObject =
180 ObjCache->getObject(M))
181 ObjectToLoad =
182 llvm::make_unique<ObjectBuffer>(std::move(PreCompiledObject));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000183 }
184
185 // If the cache did not contain a suitable object, compile the object
186 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000187 ObjectToLoad = emitObject(M);
188 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000189 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000190
191 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000192 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
David Blaikieed9709d2014-09-03 19:48:09 +0000193 std::unique_ptr<ObjectImage> LoadedObject =
194 Dyld.loadObject(std::move(ObjectToLoad));
Andrew Kayloradc70562012-10-02 21:18:39 +0000195 if (!LoadedObject)
Jim Grosbachc114d892011-03-23 19:51:34 +0000196 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000197
Andrew Kayloradc70562012-10-02 21:18:39 +0000198 // FIXME: Make this optional, maybe even move it to a JIT event listener
199 LoadedObject->registerWithDebugger();
200
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000201 NotifyObjectEmitted(*LoadedObject);
202
David Blaikieed9709d2014-09-03 19:48:09 +0000203 LoadedObjects.push_back(std::move(LoadedObject));
204
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000205 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000206}
207
Andrew Kaylorea395922013-10-01 01:47:35 +0000208void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000209 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000210
Andrew Kaylorea395922013-10-01 01:47:35 +0000211 // Resolve any outstanding relocations.
212 Dyld.resolveRelocations();
213
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000214 OwnedModules.markAllLoadedModulesAsFinalized();
215
Andrew Kaylorea395922013-10-01 01:47:35 +0000216 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000217 Dyld.registerEHFrames();
218
Andrew Kaylorea395922013-10-01 01:47:35 +0000219 // Set page permissions.
220 MemMgr.finalizeMemory();
221}
222
223// FIXME: Rename this.
224void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000225 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000226
Lang Hames018452e2014-09-05 23:38:35 +0000227 // Generate code for module is going to move objects out of the 'added' list,
228 // so we need to copy that out before using it:
229 SmallVector<Module*, 16> ModsToAdd;
230 for (auto M : OwnedModules.added())
231 ModsToAdd.push_back(M);
232
233 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000234 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000235
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000236 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000237}
238
239void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000240 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000241
Andrew Kaylorea395922013-10-01 01:47:35 +0000242 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000243 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000244
245 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000246 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000247 generateCodeForModule(M);
248
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000249 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000250}
251
Andrew Kaylorea395922013-10-01 01:47:35 +0000252uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Eric Christopherd9134482014-08-04 21:25:23 +0000253 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000254 SmallString<128> FullName;
255 Mang.getNameWithPrefix(FullName, Name);
256 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000257}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000258
Andrew Kaylorea395922013-10-01 01:47:35 +0000259Module *MCJIT::findModuleForSymbol(const std::string &Name,
260 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000261 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000262
Andrew Kaylorea395922013-10-01 01:47:35 +0000263 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000264 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
265 E = OwnedModules.end_added();
266 I != E; ++I) {
267 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000268 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000269 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000270 return M;
271 if (!CheckFunctionsOnly) {
272 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000273 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000274 return M;
275 // FIXME: Do we need to worry about global aliases?
276 }
277 }
278 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000279 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000280}
281
282uint64_t MCJIT::getSymbolAddress(const std::string &Name,
283 bool CheckFunctionsOnly)
284{
Zachary Turnerc04b8922014-06-20 21:07:14 +0000285 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000286
Andrew Kaylorea395922013-10-01 01:47:35 +0000287 // First, check to see if we already have this symbol.
288 uint64_t Addr = getExistingSymbolAddress(Name);
289 if (Addr)
290 return Addr;
291
Rafael Espindola48af1c22014-08-19 18:44:46 +0000292 for (object::OwningBinary<object::Archive> &OB : Archives) {
293 object::Archive *A = OB.getBinary().get();
Lang Hames173c69f2014-01-08 04:09:09 +0000294 // Look for our symbols in each Archive
295 object::Archive::child_iterator ChildIt = A->findSym(Name);
Rafael Espindola23a97502014-01-21 16:09:45 +0000296 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000297 // FIXME: Support nested archives?
Rafael Espindolaae460022014-06-16 16:08:36 +0000298 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
299 ChildIt->getAsBinary();
300 if (ChildBinOrErr.getError())
301 continue;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000302 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000303 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000304 std::unique_ptr<object::ObjectFile> OF(
305 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000306 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000307 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000308 // The address should be here now.
309 Addr = getExistingSymbolAddress(Name);
310 if (Addr)
311 return Addr;
312 }
313 }
314 }
315
Andrew Kaylorea395922013-10-01 01:47:35 +0000316 // If it hasn't already been generated, see if it's in one of our modules.
317 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000318 if (M) {
319 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000320
Lang Hamesea800ca2014-08-14 02:38:20 +0000321 // Check the RuntimeDyld table again, it should be there now.
322 return getExistingSymbolAddress(Name);
323 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000324
Lang Hamesea800ca2014-08-14 02:38:20 +0000325 // If a LazyFunctionCreator is installed, use it to get/create the function.
326 // FIXME: Should we instead have a LazySymbolCreator callback?
327 if (LazyFunctionCreator)
328 Addr = (uint64_t)LazyFunctionCreator(Name);
329
330 return Addr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000331}
332
333uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000334 MutexGuard locked(lock);
Andrew Kaylorea395922013-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) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000342 MutexGuard locked(lock);
Andrew Kaylorea395922013-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) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000351 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000352
Lang Hamesb7fbf592014-09-20 17:44:56 +0000353 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
354 SmallString<128> Name;
355 TM->getNameWithPrefix(Name, F, Mang);
356
Jim Grosbachd5274402011-03-22 18:05:27 +0000357 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
358 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000359 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000360 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000361 return Addr;
362 }
363
Andrew Kaylorea395922013-10-01 01:47:35 +0000364 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000365 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000366
367 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000368 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000369 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000370 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000371 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000372 // FIXME: Asking for the pointer to a function that hasn't been registered,
373 // and isn't a declaration (which is handled above) should probably
374 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000375 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000376 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000377
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000378 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000379 //
380 // This is the accessor for the target address, so make sure to check the
381 // load address of the symbol, not the local address.
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000382 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000383}
384
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000385void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
386 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
387 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000388 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000389 }
390}
391
392void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
393 // Execute global ctors/dtors for each module in the program.
394 runStaticConstructorsDestructorsInModulePtrSet(
395 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
396 runStaticConstructorsDestructorsInModulePtrSet(
397 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
398 runStaticConstructorsDestructorsInModulePtrSet(
399 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
400}
401
402Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
403 ModulePtrSet::iterator I,
404 ModulePtrSet::iterator E) {
405 for (; I != E; ++I) {
406 if (Function *F = (*I)->getFunction(FnName))
407 return F;
408 }
Craig Topper353eda42014-04-24 06:44:33 +0000409 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000410}
411
412Function *MCJIT::FindFunctionNamed(const char *FnName) {
413 Function *F = FindFunctionNamedInModulePtrSet(
414 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
415 if (!F)
416 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
417 OwnedModules.end_loaded());
418 if (!F)
419 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
420 OwnedModules.end_finalized());
421 return F;
422}
423
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000424GenericValue MCJIT::runFunction(Function *F,
425 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000426 assert(F && "Function *F was null at entry to run()");
427
Jim Grosbach7b162492011-03-18 22:48:41 +0000428 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000429 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000430 FunctionType *FTy = F->getFunctionType();
431 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000432
433 assert((FTy->getNumParams() == ArgValues.size() ||
434 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
435 "Wrong number of arguments passed into function!");
436 assert(FTy->getNumParams() == ArgValues.size() &&
437 "This doesn't support passing arguments through varargs (yet)!");
438
439 // Handle some common cases first. These cases correspond to common `main'
440 // prototypes.
441 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
442 switch (ArgValues.size()) {
443 case 3:
444 if (FTy->getParamType(0)->isIntegerTy(32) &&
445 FTy->getParamType(1)->isPointerTy() &&
446 FTy->getParamType(2)->isPointerTy()) {
447 int (*PF)(int, char **, const char **) =
448 (int(*)(int, char **, const char **))(intptr_t)FPtr;
449
450 // Call the function.
451 GenericValue rv;
452 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
453 (char **)GVTOP(ArgValues[1]),
454 (const char **)GVTOP(ArgValues[2])));
455 return rv;
456 }
457 break;
458 case 2:
459 if (FTy->getParamType(0)->isIntegerTy(32) &&
460 FTy->getParamType(1)->isPointerTy()) {
461 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
462
463 // Call the function.
464 GenericValue rv;
465 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
466 (char **)GVTOP(ArgValues[1])));
467 return rv;
468 }
469 break;
470 case 1:
471 if (FTy->getNumParams() == 1 &&
472 FTy->getParamType(0)->isIntegerTy(32)) {
473 GenericValue rv;
474 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
475 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
476 return rv;
477 }
478 break;
479 }
480 }
481
482 // Handle cases where no arguments are passed first.
483 if (ArgValues.empty()) {
484 GenericValue rv;
485 switch (RetTy->getTypeID()) {
486 default: llvm_unreachable("Unknown return type for function call!");
487 case Type::IntegerTyID: {
488 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
489 if (BitWidth == 1)
490 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
491 else if (BitWidth <= 8)
492 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
493 else if (BitWidth <= 16)
494 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
495 else if (BitWidth <= 32)
496 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 64)
498 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
499 else
500 llvm_unreachable("Integer types > 64 bits not supported");
501 return rv;
502 }
503 case Type::VoidTyID:
504 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
505 return rv;
506 case Type::FloatTyID:
507 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
508 return rv;
509 case Type::DoubleTyID:
510 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
511 return rv;
512 case Type::X86_FP80TyID:
513 case Type::FP128TyID:
514 case Type::PPC_FP128TyID:
515 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000516 case Type::PointerTyID:
517 return PTOGV(((void*(*)())(intptr_t)FPtr)());
518 }
519 }
520
Craig Toppera2886c22012-02-07 05:05:23 +0000521 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000522}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000523
Lang Hames9a783342014-09-15 17:50:22 +0000524void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000525 if (!isSymbolSearchingDisabled()) {
526 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000527 if (ptr)
528 return ptr;
529 }
530
531 /// If a LazyFunctionCreator is installed, use it to get/create the function.
532 if (LazyFunctionCreator)
533 if (void *RP = LazyFunctionCreator(Name))
534 return RP;
535
536 if (AbortOnFailure) {
537 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000538 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000539 }
Craig Topper353eda42014-04-24 06:44:33 +0000540 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000541}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000542
543void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000544 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000545 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000546 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000547 EventListeners.push_back(L);
548}
549void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000550 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000551 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000552 MutexGuard locked(lock);
Eric Christopher79cc1e32014-09-02 22:28:02 +0000553 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000554 if (I != EventListeners.rend()) {
555 std::swap(*I, EventListeners.back());
556 EventListeners.pop_back();
557 }
558}
559void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000560 MutexGuard locked(lock);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000561 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000562 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
563 EventListeners[I]->NotifyObjectEmitted(Obj);
564 }
565}
566void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000567 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000568 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000569 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000570}
Andrew Kaylorea395922013-10-01 01:47:35 +0000571
572uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
573 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000574 // If the symbols wasn't found and it begins with an underscore, try again
575 // without the underscore.
576 if (!Result && Name[0] == '_')
577 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000578 if (Result)
579 return Result;
Lang Hamesea800ca2014-08-14 02:38:20 +0000580 if (ParentEngine->isSymbolSearchingDisabled())
581 return 0;
Andrew Kaylorea395922013-10-01 01:47:35 +0000582 return ClientMM->getSymbolAddress(Name);
583}