blob: bb93271f596e094192c7acea17dcd470f1819b2a [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"
Lang Hames633fe142015-03-30 03:37:06 +000011#include "llvm/ADT/STLExtras.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000012#include "llvm/ExecutionEngine/GenericValue.h"
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +000013#include "llvm/ExecutionEngine/JITEventListener.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000014#include "llvm/ExecutionEngine/MCJIT.h"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000015#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
17#include "llvm/IR/DerivedTypes.h"
18#include "llvm/IR/Function.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000019#include "llvm/IR/LegacyPassManager.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"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000024#include "llvm/Object/ObjectFile.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"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000029
30using namespace llvm;
31
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000032void ObjectCache::anchor() {}
33
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000034namespace {
35
36static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
38} JITRegistrator;
39
40}
41
42extern "C" void LLVMLinkInMCJIT() {
43}
44
Lang Hames633fe142015-03-30 03:37:06 +000045ExecutionEngine*
46MCJIT::createJIT(std::unique_ptr<Module> M,
47 std::string *ErrorStr,
48 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesad4a9112016-08-01 20:49:11 +000049 std::shared_ptr<JITSymbolResolver> Resolver,
Lang Hames633fe142015-03-30 03:37:06 +000050 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000051 // Try to register the program as a source of symbols to resolve against.
52 //
53 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000054 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000055
Lang Hames633fe142015-03-30 03:37:06 +000056 if (!MemMgr || !Resolver) {
57 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
58 if (!MemMgr)
59 MemMgr = RTDyldMM;
60 if (!Resolver)
61 Resolver = RTDyldMM;
62 }
Lang Hames4a5697e2014-12-03 00:51:19 +000063
Lang Hames633fe142015-03-30 03:37:06 +000064 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
65 std::move(Resolver));
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000066}
67
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000068MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
Lang Hames633fe142015-03-30 03:37:06 +000069 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesad4a9112016-08-01 20:49:11 +000070 std::shared_ptr<JITSymbolResolver> Resolver)
Mehdi Amini26d48132015-07-24 16:04:22 +000071 : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000072 Ctx(nullptr), MemMgr(std::move(MemMgr)),
73 Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
74 ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000075 // FIXME: We are managing our modules, so we do not want the base class
76 // ExecutionEngine to manage them as well. To avoid double destruction
77 // of the first (and only) module added in ExecutionEngine constructor
78 // we remove it from EE and will destruct it ourselves.
79 //
80 // It may make sense to move our module manager (based on SmallStPtr) back
81 // into EE if the JIT and Interpreter can live with it.
82 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
83 // runStaticConstructorsDestructors could be moved back to EE as well.
84 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000085 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000086 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000087
Lang Hames717eacf2016-06-11 05:47:04 +000088 if (First->getDataLayout().isDefault())
89 First->setDataLayout(getDataLayout());
90
Rafael Espindola2a8a2792014-08-19 04:04:25 +000091 OwnedModules.addModule(std::move(First));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000092 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
Rafael Espindola2a8a2792014-08-19 04:04:25 +000093}
94
95MCJIT::~MCJIT() {
96 MutexGuard locked(lock);
97
Andrew Kaylorc442a762013-10-16 00:14:21 +000098 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000099
David Blaikieed9709d2014-09-03 19:48:09 +0000100 for (auto &Obj : LoadedObjects)
101 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +0000102 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +0000103
Lang Hames173c69f2014-01-08 04:09:09 +0000104 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000105}
106
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000107void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000108 MutexGuard locked(lock);
Lang Hames717eacf2016-06-11 05:47:04 +0000109
110 if (M->getDataLayout().isDefault())
111 M->setDataLayout(getDataLayout());
112
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000113 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +0000114}
115
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000116bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000117 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000118 return OwnedModules.removeModule(M);
119}
120
David Blaikie7a1e7752014-04-29 21:52:46 +0000121void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000122 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
123 if (Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000124 report_fatal_error(Dyld.getErrorString());
125
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000126 NotifyObjectEmitted(*Obj, *L);
David Blaikie168861a2014-09-04 18:37:31 +0000127
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000128 LoadedObjects.push_back(std::move(Obj));
Lang Hames173c69f2014-01-08 04:09:09 +0000129}
130
Rafael Espindola7271c192014-08-26 21:04:04 +0000131void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000132 std::unique_ptr<object::ObjectFile> ObjFile;
133 std::unique_ptr<MemoryBuffer> MemBuf;
134 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
135 addObjectFile(std::move(ObjFile));
136 Buffers.push_back(std::move(MemBuf));
Rafael Espindola7271c192014-08-26 21:04:04 +0000137}
138
Rafael Espindola48af1c22014-08-19 18:44:46 +0000139void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000140 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000141}
142
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000143void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000144 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000145 ObjCache = NewCache;
146}
147
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000148std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000149 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000150
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000151 // This must be a module which has already been added but not loaded to this
152 // MCJIT instance, since these conditions are tested by our caller,
153 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000154
Chandler Carruth30d69c22015-02-13 10:01:29 +0000155 legacy::PassManager PM;
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000156
Andrew Kayloradc70562012-10-02 21:18:39 +0000157 // The RuntimeDyld will take ownership of this shortly
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000158 SmallVector<char, 4096> ObjBufferSV;
159 raw_svector_ostream ObjStream(ObjBufferSV);
Andrew Kayloradc70562012-10-02 21:18:39 +0000160
Jim Grosbach7b162492011-03-18 22:48:41 +0000161 // Turn the machine code intermediate representation into bytes in memory
162 // that may be executed.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000163 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
Jim Grosbach7b162492011-03-18 22:48:41 +0000164 report_fatal_error("Target does not support MC emission!");
Jim Grosbach7b162492011-03-18 22:48:41 +0000165
166 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000167 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000168 // Flush the output buffer to get the generated code into memory
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000169
170 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
171 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000172
173 // If we have an object cache, tell it about the new object.
174 // Note that we're using the compiled image, not the loaded image (as below).
175 if (ObjCache) {
176 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
177 // to create a temporary object here and delete it after the call.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000178 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
Rafael Espindola48af1c22014-08-19 18:44:46 +0000179 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000180 }
181
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000182 return CompiledObjBuffer;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000183}
184
Andrew Kaylorea395922013-10-01 01:47:35 +0000185void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000186 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000187 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000188
Andrew Kaylorea395922013-10-01 01:47:35 +0000189 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000190 assert(OwnedModules.ownsModule(M) &&
191 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000192
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000193 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000194 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000195 return;
196
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000197 std::unique_ptr<MemoryBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000198 // Try to load the pre-compiled object from cache if possible
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000199 if (ObjCache)
200 ObjectToLoad = ObjCache->getObject(M);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000201
Lang Hames717eacf2016-06-11 05:47:04 +0000202 assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
Rafael Espindola6763f5a2015-06-23 14:42:34 +0000203
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000204 // If the cache did not contain a suitable object, compile the object
205 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000206 ObjectToLoad = emitObject(M);
207 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000208 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000209
210 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000211 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000212 Expected<std::unique_ptr<object::ObjectFile>> LoadedObject =
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000213 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000214 if (!LoadedObject) {
215 std::string Buf;
216 raw_string_ostream OS(Buf);
217 logAllUnhandledErrors(LoadedObject.takeError(), OS, "");
218 OS.flush();
219 report_fatal_error(Buf);
220 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000221 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
222 Dyld.loadObject(*LoadedObject.get());
223
224 if (Dyld.hasError())
Jim Grosbachc114d892011-03-23 19:51:34 +0000225 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000226
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000227 NotifyObjectEmitted(*LoadedObject.get(), *L);
Andrew Kayloradc70562012-10-02 21:18:39 +0000228
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000229 Buffers.push_back(std::move(ObjectToLoad));
230 LoadedObjects.push_back(std::move(*LoadedObject));
David Blaikieed9709d2014-09-03 19:48:09 +0000231
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000232 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000233}
234
Andrew Kaylorea395922013-10-01 01:47:35 +0000235void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000236 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000237
Andrew Kaylorea395922013-10-01 01:47:35 +0000238 // Resolve any outstanding relocations.
239 Dyld.resolveRelocations();
240
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000241 OwnedModules.markAllLoadedModulesAsFinalized();
242
Andrew Kaylorea395922013-10-01 01:47:35 +0000243 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000244 Dyld.registerEHFrames();
245
Andrew Kaylorea395922013-10-01 01:47:35 +0000246 // Set page permissions.
Lang Hames633fe142015-03-30 03:37:06 +0000247 MemMgr->finalizeMemory();
Andrew Kaylorea395922013-10-01 01:47:35 +0000248}
249
250// FIXME: Rename this.
251void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000252 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000253
Lang Hames018452e2014-09-05 23:38:35 +0000254 // Generate code for module is going to move objects out of the 'added' list,
255 // so we need to copy that out before using it:
256 SmallVector<Module*, 16> ModsToAdd;
257 for (auto M : OwnedModules.added())
258 ModsToAdd.push_back(M);
259
260 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000261 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000262
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000263 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000264}
265
266void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000267 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000268
Andrew Kaylorea395922013-10-01 01:47:35 +0000269 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000270 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000271
272 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000273 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000274 generateCodeForModule(M);
275
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000276 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000277}
278
Lang Hamesad4a9112016-08-01 20:49:11 +0000279JITSymbol MCJIT::findExistingSymbol(const std::string &Name) {
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000280 SmallString<128> FullName;
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000281 Mangler::getNameWithPrefix(FullName, Name, getDataLayout());
Lang Hames3393cfd2015-07-29 23:12:33 +0000282
283 if (void *Addr = getPointerToGlobalIfAvailable(FullName))
Lang Hamesad4a9112016-08-01 20:49:11 +0000284 return JITSymbol(static_cast<uint64_t>(
285 reinterpret_cast<uintptr_t>(Addr)),
286 JITSymbolFlags::Exported);
Lang Hames3393cfd2015-07-29 23:12:33 +0000287
Lang Hames633fe142015-03-30 03:37:06 +0000288 return Dyld.getSymbol(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000289}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000290
Andrew Kaylorea395922013-10-01 01:47:35 +0000291Module *MCJIT::findModuleForSymbol(const std::string &Name,
292 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000293 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000294
Andrew Kaylorea395922013-10-01 01:47:35 +0000295 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000296 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
297 E = OwnedModules.end_added();
298 I != E; ++I) {
299 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000300 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000301 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000302 return M;
303 if (!CheckFunctionsOnly) {
304 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000305 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000306 return M;
307 // FIXME: Do we need to worry about global aliases?
308 }
309 }
310 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000311 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000312}
313
314uint64_t MCJIT::getSymbolAddress(const std::string &Name,
Lang Hames633fe142015-03-30 03:37:06 +0000315 bool CheckFunctionsOnly) {
316 return findSymbol(Name, CheckFunctionsOnly).getAddress();
317}
318
Lang Hamesad4a9112016-08-01 20:49:11 +0000319JITSymbol MCJIT::findSymbol(const std::string &Name,
320 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000321 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000322
Andrew Kaylorea395922013-10-01 01:47:35 +0000323 // First, check to see if we already have this symbol.
Lang Hames633fe142015-03-30 03:37:06 +0000324 if (auto Sym = findExistingSymbol(Name))
325 return Sym;
Andrew Kaylorea395922013-10-01 01:47:35 +0000326
Rafael Espindola48af1c22014-08-19 18:44:46 +0000327 for (object::OwningBinary<object::Archive> &OB : Archives) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000328 object::Archive *A = OB.getBinary();
Lang Hames173c69f2014-01-08 04:09:09 +0000329 // Look for our symbols in each Archive
Lang Hames69f49022016-07-14 20:44:27 +0000330 auto OptionalChildOrErr = A->findSym(Name);
331 if (!OptionalChildOrErr)
332 report_fatal_error(OptionalChildOrErr.takeError());
333 auto &OptionalChild = *OptionalChildOrErr;
334 if (OptionalChild) {
Lang Hames173c69f2014-01-08 04:09:09 +0000335 // FIXME: Support nested archives?
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000336 Expected<std::unique_ptr<object::Binary>> ChildBinOrErr =
Lang Hames69f49022016-07-14 20:44:27 +0000337 OptionalChild->getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000338 if (!ChildBinOrErr) {
339 // TODO: Actually report errors helpfully.
340 consumeError(ChildBinOrErr.takeError());
Rafael Espindolaae460022014-06-16 16:08:36 +0000341 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000342 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000343 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000344 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000345 std::unique_ptr<object::ObjectFile> OF(
346 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000347 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000348 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000349 // The address should be here now.
Lang Hames633fe142015-03-30 03:37:06 +0000350 if (auto Sym = findExistingSymbol(Name))
351 return Sym;
Lang Hames173c69f2014-01-08 04:09:09 +0000352 }
353 }
354 }
355
Andrew Kaylorea395922013-10-01 01:47:35 +0000356 // If it hasn't already been generated, see if it's in one of our modules.
357 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000358 if (M) {
359 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000360
Lang Hamesea800ca2014-08-14 02:38:20 +0000361 // Check the RuntimeDyld table again, it should be there now.
Lang Hames633fe142015-03-30 03:37:06 +0000362 return findExistingSymbol(Name);
Lang Hamesea800ca2014-08-14 02:38:20 +0000363 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000364
Lang Hamesea800ca2014-08-14 02:38:20 +0000365 // If a LazyFunctionCreator is installed, use it to get/create the function.
366 // FIXME: Should we instead have a LazySymbolCreator callback?
Lang Hames633fe142015-03-30 03:37:06 +0000367 if (LazyFunctionCreator) {
368 auto Addr = static_cast<uint64_t>(
369 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
Lang Hamesad4a9112016-08-01 20:49:11 +0000370 return JITSymbol(Addr, JITSymbolFlags::Exported);
Lang Hames633fe142015-03-30 03:37:06 +0000371 }
Lang Hamesea800ca2014-08-14 02:38:20 +0000372
Lang Hames633fe142015-03-30 03:37:06 +0000373 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000374}
375
376uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000377 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000378 uint64_t Result = getSymbolAddress(Name, false);
379 if (Result != 0)
380 finalizeLoadedModules();
381 return Result;
382}
383
384uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000385 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000386 uint64_t Result = getSymbolAddress(Name, true);
387 if (Result != 0)
388 finalizeLoadedModules();
389 return Result;
390}
391
392// Deprecated. Use getFunctionAddress instead.
393void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000394 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000395
Rafael Espindolac233f742015-06-23 13:59:29 +0000396 Mangler Mang;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000397 SmallString<128> Name;
398 TM->getNameWithPrefix(Name, F, Mang);
399
Jim Grosbachd5274402011-03-22 18:05:27 +0000400 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
401 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000402 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000403 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000404 return Addr;
405 }
406
Andrew Kaylorea395922013-10-01 01:47:35 +0000407 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000408 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000409
410 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000411 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000412 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000413 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000414 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000415 // FIXME: Asking for the pointer to a function that hasn't been registered,
416 // and isn't a declaration (which is handled above) should probably
417 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000418 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000419 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000420
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000421 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000422 //
423 // This is the accessor for the target address, so make sure to check the
424 // load address of the symbol, not the local address.
Lang Hamesb1186032015-03-11 00:43:26 +0000425 return (void*)Dyld.getSymbol(Name).getAddress();
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000426}
427
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000428void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
429 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
430 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000431 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000432 }
433}
434
435void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
436 // Execute global ctors/dtors for each module in the program.
437 runStaticConstructorsDestructorsInModulePtrSet(
438 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
439 runStaticConstructorsDestructorsInModulePtrSet(
440 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
441 runStaticConstructorsDestructorsInModulePtrSet(
442 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
443}
444
445Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
446 ModulePtrSet::iterator I,
447 ModulePtrSet::iterator E) {
448 for (; I != E; ++I) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000449 Function *F = (*I)->getFunction(FnName);
450 if (F && !F->isDeclaration())
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000451 return F;
452 }
Craig Topper353eda42014-04-24 06:44:33 +0000453 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000454}
455
Keno Fischer73378eb2015-06-20 00:55:58 +0000456GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
457 bool AllowInternal,
458 ModulePtrSet::iterator I,
459 ModulePtrSet::iterator E) {
460 for (; I != E; ++I) {
461 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
462 if (GV && !GV->isDeclaration())
463 return GV;
464 }
465 return nullptr;
466}
467
468
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000469Function *MCJIT::FindFunctionNamed(const char *FnName) {
470 Function *F = FindFunctionNamedInModulePtrSet(
471 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
472 if (!F)
473 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
474 OwnedModules.end_loaded());
475 if (!F)
476 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
477 OwnedModules.end_finalized());
478 return F;
479}
480
Keno Fischer73378eb2015-06-20 00:55:58 +0000481GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
482 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
483 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
484 if (!GV)
485 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
486 OwnedModules.end_loaded());
487 if (!GV)
488 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
489 OwnedModules.end_finalized());
490 return GV;
491}
492
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000493GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000494 assert(F && "Function *F was null at entry to run()");
495
Jim Grosbach7b162492011-03-18 22:48:41 +0000496 void *FPtr = getPointerToFunction(F);
Lang Hames717eacf2016-06-11 05:47:04 +0000497 finalizeModule(F->getParent());
Jim Grosbachd5274402011-03-22 18:05:27 +0000498 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000499 FunctionType *FTy = F->getFunctionType();
500 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000501
502 assert((FTy->getNumParams() == ArgValues.size() ||
503 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
504 "Wrong number of arguments passed into function!");
505 assert(FTy->getNumParams() == ArgValues.size() &&
506 "This doesn't support passing arguments through varargs (yet)!");
507
508 // Handle some common cases first. These cases correspond to common `main'
509 // prototypes.
510 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
511 switch (ArgValues.size()) {
512 case 3:
513 if (FTy->getParamType(0)->isIntegerTy(32) &&
514 FTy->getParamType(1)->isPointerTy() &&
515 FTy->getParamType(2)->isPointerTy()) {
516 int (*PF)(int, char **, const char **) =
517 (int(*)(int, char **, const char **))(intptr_t)FPtr;
518
519 // Call the function.
520 GenericValue rv;
521 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
522 (char **)GVTOP(ArgValues[1]),
523 (const char **)GVTOP(ArgValues[2])));
524 return rv;
525 }
526 break;
527 case 2:
528 if (FTy->getParamType(0)->isIntegerTy(32) &&
529 FTy->getParamType(1)->isPointerTy()) {
530 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
531
532 // Call the function.
533 GenericValue rv;
534 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
535 (char **)GVTOP(ArgValues[1])));
536 return rv;
537 }
538 break;
539 case 1:
540 if (FTy->getNumParams() == 1 &&
541 FTy->getParamType(0)->isIntegerTy(32)) {
542 GenericValue rv;
543 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
544 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
545 return rv;
546 }
547 break;
548 }
549 }
550
551 // Handle cases where no arguments are passed first.
552 if (ArgValues.empty()) {
553 GenericValue rv;
554 switch (RetTy->getTypeID()) {
555 default: llvm_unreachable("Unknown return type for function call!");
556 case Type::IntegerTyID: {
557 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
558 if (BitWidth == 1)
559 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
560 else if (BitWidth <= 8)
561 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
562 else if (BitWidth <= 16)
563 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
564 else if (BitWidth <= 32)
565 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
566 else if (BitWidth <= 64)
567 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
568 else
569 llvm_unreachable("Integer types > 64 bits not supported");
570 return rv;
571 }
572 case Type::VoidTyID:
573 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
574 return rv;
575 case Type::FloatTyID:
576 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
577 return rv;
578 case Type::DoubleTyID:
579 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
580 return rv;
581 case Type::X86_FP80TyID:
582 case Type::FP128TyID:
583 case Type::PPC_FP128TyID:
584 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000585 case Type::PointerTyID:
586 return PTOGV(((void*(*)())(intptr_t)FPtr)());
587 }
588 }
589
Craig Toppera2886c22012-02-07 05:05:23 +0000590 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000591}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000592
Lang Hames9a783342014-09-15 17:50:22 +0000593void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000594 if (!isSymbolSearchingDisabled()) {
Lang Hames633fe142015-03-30 03:37:06 +0000595 void *ptr =
596 reinterpret_cast<void*>(
597 static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
Danil Malyshevbfee5422012-03-28 21:46:36 +0000598 if (ptr)
599 return ptr;
600 }
601
602 /// If a LazyFunctionCreator is installed, use it to get/create the function.
603 if (LazyFunctionCreator)
604 if (void *RP = LazyFunctionCreator(Name))
605 return RP;
606
607 if (AbortOnFailure) {
608 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000609 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000610 }
Craig Topper353eda42014-04-24 06:44:33 +0000611 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000612}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000613
614void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000615 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000616 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000617 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000618 EventListeners.push_back(L);
619}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000620
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000621void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000622 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000623 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000624 MutexGuard locked(lock);
Eric Christopher79cc1e32014-09-02 22:28:02 +0000625 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000626 if (I != EventListeners.rend()) {
627 std::swap(*I, EventListeners.back());
628 EventListeners.pop_back();
629 }
630}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000631
632void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
633 const RuntimeDyld::LoadedObjectInfo &L) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000634 MutexGuard locked(lock);
Lang Hames633fe142015-03-30 03:37:06 +0000635 MemMgr->notifyObjectLoaded(this, Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000636 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000637 EventListeners[I]->NotifyObjectEmitted(Obj, L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000638 }
639}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000640
641void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000642 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000643 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000644 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000645}
Andrew Kaylorea395922013-10-01 01:47:35 +0000646
Lang Hamesad4a9112016-08-01 20:49:11 +0000647JITSymbol
Lang Hames633fe142015-03-30 03:37:06 +0000648LinkingSymbolResolver::findSymbol(const std::string &Name) {
649 auto Result = ParentEngine.findSymbol(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000650 // If the symbols wasn't found and it begins with an underscore, try again
651 // without the underscore.
652 if (!Result && Name[0] == '_')
Lang Hames633fe142015-03-30 03:37:06 +0000653 Result = ParentEngine.findSymbol(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000654 if (Result)
655 return Result;
Lang Hames633fe142015-03-30 03:37:06 +0000656 if (ParentEngine.isSymbolSearchingDisabled())
657 return nullptr;
658 return ClientResolver->findSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000659}