blob: 6cbebe98e7c92fc801ce50b0b10a5ad08122fd96 [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,
49 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
50 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,
70 std::shared_ptr<RuntimeDyld::SymbolResolver> 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
88 OwnedModules.addModule(std::move(First));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000089 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
Rafael Espindola2a8a2792014-08-19 04:04:25 +000090}
91
92MCJIT::~MCJIT() {
93 MutexGuard locked(lock);
94
Andrew Kaylorc442a762013-10-16 00:14:21 +000095 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000096
David Blaikieed9709d2014-09-03 19:48:09 +000097 for (auto &Obj : LoadedObjects)
98 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +000099 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +0000100
Lang Hames173c69f2014-01-08 04:09:09 +0000101 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000102}
103
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000104void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000105 MutexGuard locked(lock);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000106 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +0000107}
108
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000109bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000110 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000111 return OwnedModules.removeModule(M);
112}
113
David Blaikie7a1e7752014-04-29 21:52:46 +0000114void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000115 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
116 if (Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000117 report_fatal_error(Dyld.getErrorString());
118
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000119 NotifyObjectEmitted(*Obj, *L);
David Blaikie168861a2014-09-04 18:37:31 +0000120
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000121 LoadedObjects.push_back(std::move(Obj));
Lang Hames173c69f2014-01-08 04:09:09 +0000122}
123
Rafael Espindola7271c192014-08-26 21:04:04 +0000124void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000125 std::unique_ptr<object::ObjectFile> ObjFile;
126 std::unique_ptr<MemoryBuffer> MemBuf;
127 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
128 addObjectFile(std::move(ObjFile));
129 Buffers.push_back(std::move(MemBuf));
Rafael Espindola7271c192014-08-26 21:04:04 +0000130}
131
Rafael Espindola48af1c22014-08-19 18:44:46 +0000132void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000133 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000134}
135
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000136void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000137 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000138 ObjCache = NewCache;
139}
140
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000141std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000142 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000143
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000144 // This must be a module which has already been added but not loaded to this
145 // MCJIT instance, since these conditions are tested by our caller,
146 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000147
Chandler Carruth30d69c22015-02-13 10:01:29 +0000148 legacy::PassManager PM;
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000149
Andrew Kayloradc70562012-10-02 21:18:39 +0000150 // The RuntimeDyld will take ownership of this shortly
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000151 SmallVector<char, 4096> ObjBufferSV;
152 raw_svector_ostream ObjStream(ObjBufferSV);
Andrew Kayloradc70562012-10-02 21:18:39 +0000153
Jim Grosbach7b162492011-03-18 22:48:41 +0000154 // Turn the machine code intermediate representation into bytes in memory
155 // that may be executed.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000156 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
Jim Grosbach7b162492011-03-18 22:48:41 +0000157 report_fatal_error("Target does not support MC emission!");
Jim Grosbach7b162492011-03-18 22:48:41 +0000158
159 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000160 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000161 // Flush the output buffer to get the generated code into memory
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000162
163 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
164 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000165
166 // If we have an object cache, tell it about the new object.
167 // Note that we're using the compiled image, not the loaded image (as below).
168 if (ObjCache) {
169 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
170 // to create a temporary object here and delete it after the call.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000171 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
Rafael Espindola48af1c22014-08-19 18:44:46 +0000172 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000173 }
174
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000175 return CompiledObjBuffer;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000176}
177
Andrew Kaylorea395922013-10-01 01:47:35 +0000178void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000179 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000180 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000181
Andrew Kaylorea395922013-10-01 01:47:35 +0000182 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000183 assert(OwnedModules.ownsModule(M) &&
184 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000185
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000186 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000187 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000188 return;
189
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000190 std::unique_ptr<MemoryBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000191 // Try to load the pre-compiled object from cache if possible
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000192 if (ObjCache)
193 ObjectToLoad = ObjCache->getObject(M);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000194
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000195 if (M->getDataLayout().isDefault()) {
196 M->setDataLayout(getDataLayout());
197 } else {
198 assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
199 }
Rafael Espindola6763f5a2015-06-23 14:42:34 +0000200
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000201 // If the cache did not contain a suitable object, compile the object
202 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000203 ObjectToLoad = emitObject(M);
204 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000205 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000206
207 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000208 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000209 ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
210 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
211 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
212 Dyld.loadObject(*LoadedObject.get());
213
214 if (Dyld.hasError())
Jim Grosbachc114d892011-03-23 19:51:34 +0000215 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000216
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000217 NotifyObjectEmitted(*LoadedObject.get(), *L);
Andrew Kayloradc70562012-10-02 21:18:39 +0000218
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000219 Buffers.push_back(std::move(ObjectToLoad));
220 LoadedObjects.push_back(std::move(*LoadedObject));
David Blaikieed9709d2014-09-03 19:48:09 +0000221
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000222 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000223}
224
Andrew Kaylorea395922013-10-01 01:47:35 +0000225void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000226 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000227
Andrew Kaylorea395922013-10-01 01:47:35 +0000228 // Resolve any outstanding relocations.
229 Dyld.resolveRelocations();
230
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000231 OwnedModules.markAllLoadedModulesAsFinalized();
232
Andrew Kaylorea395922013-10-01 01:47:35 +0000233 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000234 Dyld.registerEHFrames();
235
Andrew Kaylorea395922013-10-01 01:47:35 +0000236 // Set page permissions.
Lang Hames633fe142015-03-30 03:37:06 +0000237 MemMgr->finalizeMemory();
Andrew Kaylorea395922013-10-01 01:47:35 +0000238}
239
240// FIXME: Rename this.
241void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000242 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000243
Lang Hames018452e2014-09-05 23:38:35 +0000244 // Generate code for module is going to move objects out of the 'added' list,
245 // so we need to copy that out before using it:
246 SmallVector<Module*, 16> ModsToAdd;
247 for (auto M : OwnedModules.added())
248 ModsToAdd.push_back(M);
249
250 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000251 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000252
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000253 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000254}
255
256void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000257 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000258
Andrew Kaylorea395922013-10-01 01:47:35 +0000259 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000260 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000261
262 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000263 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000264 generateCodeForModule(M);
265
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000266 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000267}
268
Lang Hames633fe142015-03-30 03:37:06 +0000269RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000270 SmallString<128> FullName;
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000271 Mangler::getNameWithPrefix(FullName, Name, getDataLayout());
Lang Hames3393cfd2015-07-29 23:12:33 +0000272
273 if (void *Addr = getPointerToGlobalIfAvailable(FullName))
274 return RuntimeDyld::SymbolInfo(static_cast<uint64_t>(
275 reinterpret_cast<uintptr_t>(Addr)),
276 JITSymbolFlags::Exported);
277
Lang Hames633fe142015-03-30 03:37:06 +0000278 return Dyld.getSymbol(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000279}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000280
Andrew Kaylorea395922013-10-01 01:47:35 +0000281Module *MCJIT::findModuleForSymbol(const std::string &Name,
282 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000283 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000284
Andrew Kaylorea395922013-10-01 01:47:35 +0000285 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000286 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
287 E = OwnedModules.end_added();
288 I != E; ++I) {
289 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000290 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000291 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000292 return M;
293 if (!CheckFunctionsOnly) {
294 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000295 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000296 return M;
297 // FIXME: Do we need to worry about global aliases?
298 }
299 }
300 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000301 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000302}
303
304uint64_t MCJIT::getSymbolAddress(const std::string &Name,
Lang Hames633fe142015-03-30 03:37:06 +0000305 bool CheckFunctionsOnly) {
306 return findSymbol(Name, CheckFunctionsOnly).getAddress();
307}
308
309RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
310 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000311 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000312
Andrew Kaylorea395922013-10-01 01:47:35 +0000313 // First, check to see if we already have this symbol.
Lang Hames633fe142015-03-30 03:37:06 +0000314 if (auto Sym = findExistingSymbol(Name))
315 return Sym;
Andrew Kaylorea395922013-10-01 01:47:35 +0000316
Rafael Espindola48af1c22014-08-19 18:44:46 +0000317 for (object::OwningBinary<object::Archive> &OB : Archives) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000318 object::Archive *A = OB.getBinary();
Lang Hames173c69f2014-01-08 04:09:09 +0000319 // Look for our symbols in each Archive
320 object::Archive::child_iterator ChildIt = A->findSym(Name);
Kevin Enderby7a969422015-11-05 19:24:56 +0000321 if (std::error_code EC = ChildIt->getError())
322 report_fatal_error(EC.message());
Kevin Enderbyda9dd052015-10-21 17:13:20 +0000323 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000324 // FIXME: Support nested archives?
Rafael Espindolaae460022014-06-16 16:08:36 +0000325 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
Kevin Enderby7a969422015-11-05 19:24:56 +0000326 (*ChildIt)->getAsBinary();
Rafael Espindolaae460022014-06-16 16:08:36 +0000327 if (ChildBinOrErr.getError())
328 continue;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000329 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000330 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000331 std::unique_ptr<object::ObjectFile> OF(
332 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000333 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000334 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000335 // The address should be here now.
Lang Hames633fe142015-03-30 03:37:06 +0000336 if (auto Sym = findExistingSymbol(Name))
337 return Sym;
Lang Hames173c69f2014-01-08 04:09:09 +0000338 }
339 }
340 }
341
Andrew Kaylorea395922013-10-01 01:47:35 +0000342 // If it hasn't already been generated, see if it's in one of our modules.
343 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000344 if (M) {
345 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000346
Lang Hamesea800ca2014-08-14 02:38:20 +0000347 // Check the RuntimeDyld table again, it should be there now.
Lang Hames633fe142015-03-30 03:37:06 +0000348 return findExistingSymbol(Name);
Lang Hamesea800ca2014-08-14 02:38:20 +0000349 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000350
Lang Hamesea800ca2014-08-14 02:38:20 +0000351 // If a LazyFunctionCreator is installed, use it to get/create the function.
352 // FIXME: Should we instead have a LazySymbolCreator callback?
Lang Hames633fe142015-03-30 03:37:06 +0000353 if (LazyFunctionCreator) {
354 auto Addr = static_cast<uint64_t>(
355 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
356 return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
357 }
Lang Hamesea800ca2014-08-14 02:38:20 +0000358
Lang Hames633fe142015-03-30 03:37:06 +0000359 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000360}
361
362uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000363 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000364 uint64_t Result = getSymbolAddress(Name, false);
365 if (Result != 0)
366 finalizeLoadedModules();
367 return Result;
368}
369
370uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000371 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000372 uint64_t Result = getSymbolAddress(Name, true);
373 if (Result != 0)
374 finalizeLoadedModules();
375 return Result;
376}
377
378// Deprecated. Use getFunctionAddress instead.
379void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000380 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000381
Rafael Espindolac233f742015-06-23 13:59:29 +0000382 Mangler Mang;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000383 SmallString<128> Name;
384 TM->getNameWithPrefix(Name, F, Mang);
385
Jim Grosbachd5274402011-03-22 18:05:27 +0000386 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
387 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000388 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000389 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000390 return Addr;
391 }
392
Andrew Kaylorea395922013-10-01 01:47:35 +0000393 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000394 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000395
396 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000397 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000398 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000399 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000400 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000401 // FIXME: Asking for the pointer to a function that hasn't been registered,
402 // and isn't a declaration (which is handled above) should probably
403 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000404 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000405 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000406
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000407 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000408 //
409 // This is the accessor for the target address, so make sure to check the
410 // load address of the symbol, not the local address.
Lang Hamesb1186032015-03-11 00:43:26 +0000411 return (void*)Dyld.getSymbol(Name).getAddress();
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000412}
413
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000414void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
415 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
416 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000417 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000418 }
419}
420
421void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
422 // Execute global ctors/dtors for each module in the program.
423 runStaticConstructorsDestructorsInModulePtrSet(
424 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
425 runStaticConstructorsDestructorsInModulePtrSet(
426 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
427 runStaticConstructorsDestructorsInModulePtrSet(
428 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
429}
430
431Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
432 ModulePtrSet::iterator I,
433 ModulePtrSet::iterator E) {
434 for (; I != E; ++I) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000435 Function *F = (*I)->getFunction(FnName);
436 if (F && !F->isDeclaration())
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000437 return F;
438 }
Craig Topper353eda42014-04-24 06:44:33 +0000439 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000440}
441
Keno Fischer73378eb2015-06-20 00:55:58 +0000442GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
443 bool AllowInternal,
444 ModulePtrSet::iterator I,
445 ModulePtrSet::iterator E) {
446 for (; I != E; ++I) {
447 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
448 if (GV && !GV->isDeclaration())
449 return GV;
450 }
451 return nullptr;
452}
453
454
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000455Function *MCJIT::FindFunctionNamed(const char *FnName) {
456 Function *F = FindFunctionNamedInModulePtrSet(
457 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
458 if (!F)
459 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
460 OwnedModules.end_loaded());
461 if (!F)
462 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
463 OwnedModules.end_finalized());
464 return F;
465}
466
Keno Fischer73378eb2015-06-20 00:55:58 +0000467GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
468 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
469 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
470 if (!GV)
471 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
472 OwnedModules.end_loaded());
473 if (!GV)
474 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
475 OwnedModules.end_finalized());
476 return GV;
477}
478
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000479GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000480 assert(F && "Function *F was null at entry to run()");
481
Jim Grosbach7b162492011-03-18 22:48:41 +0000482 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000483 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000484 FunctionType *FTy = F->getFunctionType();
485 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000486
487 assert((FTy->getNumParams() == ArgValues.size() ||
488 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
489 "Wrong number of arguments passed into function!");
490 assert(FTy->getNumParams() == ArgValues.size() &&
491 "This doesn't support passing arguments through varargs (yet)!");
492
493 // Handle some common cases first. These cases correspond to common `main'
494 // prototypes.
495 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
496 switch (ArgValues.size()) {
497 case 3:
498 if (FTy->getParamType(0)->isIntegerTy(32) &&
499 FTy->getParamType(1)->isPointerTy() &&
500 FTy->getParamType(2)->isPointerTy()) {
501 int (*PF)(int, char **, const char **) =
502 (int(*)(int, char **, const char **))(intptr_t)FPtr;
503
504 // Call the function.
505 GenericValue rv;
506 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
507 (char **)GVTOP(ArgValues[1]),
508 (const char **)GVTOP(ArgValues[2])));
509 return rv;
510 }
511 break;
512 case 2:
513 if (FTy->getParamType(0)->isIntegerTy(32) &&
514 FTy->getParamType(1)->isPointerTy()) {
515 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
516
517 // Call the function.
518 GenericValue rv;
519 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
520 (char **)GVTOP(ArgValues[1])));
521 return rv;
522 }
523 break;
524 case 1:
525 if (FTy->getNumParams() == 1 &&
526 FTy->getParamType(0)->isIntegerTy(32)) {
527 GenericValue rv;
528 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
529 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
530 return rv;
531 }
532 break;
533 }
534 }
535
536 // Handle cases where no arguments are passed first.
537 if (ArgValues.empty()) {
538 GenericValue rv;
539 switch (RetTy->getTypeID()) {
540 default: llvm_unreachable("Unknown return type for function call!");
541 case Type::IntegerTyID: {
542 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
543 if (BitWidth == 1)
544 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
545 else if (BitWidth <= 8)
546 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
547 else if (BitWidth <= 16)
548 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
549 else if (BitWidth <= 32)
550 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
551 else if (BitWidth <= 64)
552 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
553 else
554 llvm_unreachable("Integer types > 64 bits not supported");
555 return rv;
556 }
557 case Type::VoidTyID:
558 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
559 return rv;
560 case Type::FloatTyID:
561 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
562 return rv;
563 case Type::DoubleTyID:
564 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
565 return rv;
566 case Type::X86_FP80TyID:
567 case Type::FP128TyID:
568 case Type::PPC_FP128TyID:
569 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000570 case Type::PointerTyID:
571 return PTOGV(((void*(*)())(intptr_t)FPtr)());
572 }
573 }
574
Craig Toppera2886c22012-02-07 05:05:23 +0000575 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000576}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000577
Lang Hames9a783342014-09-15 17:50:22 +0000578void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000579 if (!isSymbolSearchingDisabled()) {
Lang Hames633fe142015-03-30 03:37:06 +0000580 void *ptr =
581 reinterpret_cast<void*>(
582 static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
Danil Malyshevbfee5422012-03-28 21:46:36 +0000583 if (ptr)
584 return ptr;
585 }
586
587 /// If a LazyFunctionCreator is installed, use it to get/create the function.
588 if (LazyFunctionCreator)
589 if (void *RP = LazyFunctionCreator(Name))
590 return RP;
591
592 if (AbortOnFailure) {
593 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000594 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000595 }
Craig Topper353eda42014-04-24 06:44:33 +0000596 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000597}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000598
599void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000600 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000601 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000602 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000603 EventListeners.push_back(L);
604}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000605
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000606void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000607 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000608 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000609 MutexGuard locked(lock);
Eric Christopher79cc1e32014-09-02 22:28:02 +0000610 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000611 if (I != EventListeners.rend()) {
612 std::swap(*I, EventListeners.back());
613 EventListeners.pop_back();
614 }
615}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000616
617void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
618 const RuntimeDyld::LoadedObjectInfo &L) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000619 MutexGuard locked(lock);
Lang Hames633fe142015-03-30 03:37:06 +0000620 MemMgr->notifyObjectLoaded(this, Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000621 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000622 EventListeners[I]->NotifyObjectEmitted(Obj, L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000623 }
624}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000625
626void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000627 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000628 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000629 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000630}
Andrew Kaylorea395922013-10-01 01:47:35 +0000631
Lang Hames633fe142015-03-30 03:37:06 +0000632RuntimeDyld::SymbolInfo
633LinkingSymbolResolver::findSymbol(const std::string &Name) {
634 auto Result = ParentEngine.findSymbol(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000635 // If the symbols wasn't found and it begins with an underscore, try again
636 // without the underscore.
637 if (!Result && Name[0] == '_')
Lang Hames633fe142015-03-30 03:37:06 +0000638 Result = ParentEngine.findSymbol(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000639 if (Result)
640 return Result;
Lang Hames633fe142015-03-30 03:37:06 +0000641 if (ParentEngine.isSymbolSearchingDisabled())
642 return nullptr;
643 return ClientResolver->findSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000644}