blob: 08815b7a80aef0d3672912ae256fd21a849e760a [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "MCJIT.h"
Lang Hames633fe142015-03-30 03:37:06 +000010#include "llvm/ADT/STLExtras.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000011#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"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000014#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000015#include "llvm/IR/DataLayout.h"
16#include "llvm/IR/DerivedTypes.h"
17#include "llvm/IR/Function.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000018#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000019#include "llvm/IR/Mangler.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000020#include "llvm/IR/Module.h"
Lang Hames173c69f2014-01-08 04:09:09 +000021#include "llvm/Object/Archive.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000022#include "llvm/Object/ObjectFile.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000023#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000025#include "llvm/Support/MemoryBuffer.h"
Zachary Turnerc04b8922014-06-20 21:07:14 +000026#include "llvm/Support/MutexGuard.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000027
28using namespace llvm;
29
30namespace {
31
32static struct RegisterJIT {
33 RegisterJIT() { MCJIT::Register(); }
34} JITRegistrator;
35
36}
37
38extern "C" void LLVMLinkInMCJIT() {
39}
40
Lang Hamesb72f4842018-01-19 22:24:13 +000041ExecutionEngine *
42MCJIT::createJIT(std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hames633fe142015-03-30 03:37:06 +000043 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesb72f4842018-01-19 22:24:13 +000044 std::shared_ptr<LegacyJITSymbolResolver> Resolver,
Lang Hames633fe142015-03-30 03:37:06 +000045 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000046 // Try to register the program as a source of symbols to resolve against.
47 //
48 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000049 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000050
Lang Hames633fe142015-03-30 03:37:06 +000051 if (!MemMgr || !Resolver) {
52 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
53 if (!MemMgr)
54 MemMgr = RTDyldMM;
55 if (!Resolver)
56 Resolver = RTDyldMM;
57 }
Lang Hames4a5697e2014-12-03 00:51:19 +000058
Lang Hames633fe142015-03-30 03:37:06 +000059 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
60 std::move(Resolver));
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000061}
62
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000063MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
Lang Hames633fe142015-03-30 03:37:06 +000064 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesb72f4842018-01-19 22:24:13 +000065 std::shared_ptr<LegacyJITSymbolResolver> Resolver)
Mehdi Amini26d48132015-07-24 16:04:22 +000066 : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000067 Ctx(nullptr), MemMgr(std::move(MemMgr)),
68 Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
69 ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000070 // FIXME: We are managing our modules, so we do not want the base class
71 // ExecutionEngine to manage them as well. To avoid double destruction
72 // of the first (and only) module added in ExecutionEngine constructor
73 // we remove it from EE and will destruct it ourselves.
74 //
75 // It may make sense to move our module manager (based on SmallStPtr) back
76 // into EE if the JIT and Interpreter can live with it.
77 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
78 // runStaticConstructorsDestructors could be moved back to EE as well.
79 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000080 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000081 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000082
Lang Hames717eacf2016-06-11 05:47:04 +000083 if (First->getDataLayout().isDefault())
84 First->setDataLayout(getDataLayout());
85
Rafael Espindola2a8a2792014-08-19 04:04:25 +000086 OwnedModules.addModule(std::move(First));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000087 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
Rafael Espindola2a8a2792014-08-19 04:04:25 +000088}
89
90MCJIT::~MCJIT() {
91 MutexGuard locked(lock);
92
Andrew Kaylorc442a762013-10-16 00:14:21 +000093 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000094
David Blaikieed9709d2014-09-03 19:48:09 +000095 for (auto &Obj : LoadedObjects)
96 if (Obj)
Lang Hameseca6d4b2018-12-04 00:55:15 +000097 notifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +000098
Lang Hames173c69f2014-01-08 04:09:09 +000099 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000100}
101
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000102void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000103 MutexGuard locked(lock);
Lang Hames717eacf2016-06-11 05:47:04 +0000104
105 if (M->getDataLayout().isDefault())
106 M->setDataLayout(getDataLayout());
107
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000108 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +0000109}
110
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000111bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000112 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000113 return OwnedModules.removeModule(M);
114}
115
David Blaikie7a1e7752014-04-29 21:52:46 +0000116void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000117 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
118 if (Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000119 report_fatal_error(Dyld.getErrorString());
120
Lang Hameseca6d4b2018-12-04 00:55:15 +0000121 notifyObjectLoaded(*Obj, *L);
David Blaikie168861a2014-09-04 18:37:31 +0000122
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000123 LoadedObjects.push_back(std::move(Obj));
Lang Hames173c69f2014-01-08 04:09:09 +0000124}
125
Rafael Espindola7271c192014-08-26 21:04:04 +0000126void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000127 std::unique_ptr<object::ObjectFile> ObjFile;
128 std::unique_ptr<MemoryBuffer> MemBuf;
129 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
130 addObjectFile(std::move(ObjFile));
131 Buffers.push_back(std::move(MemBuf));
Rafael Espindola7271c192014-08-26 21:04:04 +0000132}
133
Rafael Espindola48af1c22014-08-19 18:44:46 +0000134void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000135 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000136}
137
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000138void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000139 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000140 ObjCache = NewCache;
141}
142
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000143std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
Lang Hamese7989ef2018-06-12 20:43:15 +0000144 assert(M && "Can not emit a null module");
145
Zachary Turnerc04b8922014-06-20 21:07:14 +0000146 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000147
Lang Hamese7989ef2018-06-12 20:43:15 +0000148 // Materialize all globals in the module if they have not been
149 // materialized already.
150 cantFail(M->materializeAll());
151
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000152 // This must be a module which has already been added but not loaded to this
153 // MCJIT instance, since these conditions are tested by our caller,
154 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000155
Chandler Carruth30d69c22015-02-13 10:01:29 +0000156 legacy::PassManager PM;
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000157
Andrew Kayloradc70562012-10-02 21:18:39 +0000158 // The RuntimeDyld will take ownership of this shortly
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000159 SmallVector<char, 4096> ObjBufferSV;
160 raw_svector_ostream ObjStream(ObjBufferSV);
Andrew Kayloradc70562012-10-02 21:18:39 +0000161
Jim Grosbach7b162492011-03-18 22:48:41 +0000162 // Turn the machine code intermediate representation into bytes in memory
163 // that may be executed.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000164 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
Jim Grosbach7b162492011-03-18 22:48:41 +0000165 report_fatal_error("Target does not support MC emission!");
Jim Grosbach7b162492011-03-18 22:48:41 +0000166
167 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000168 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000169 // Flush the output buffer to get the generated code into memory
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000170
171 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
Weiming Zhao79f2d092018-04-16 03:44:03 +0000172 new SmallVectorMemoryBuffer(std::move(ObjBufferSV)));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000173
174 // If we have an object cache, tell it about the new object.
175 // Note that we're using the compiled image, not the loaded image (as below).
176 if (ObjCache) {
177 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
178 // to create a temporary object here and delete it after the call.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000179 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
Rafael Espindola48af1c22014-08-19 18:44:46 +0000180 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000181 }
182
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000183 return CompiledObjBuffer;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000184}
185
Andrew Kaylorea395922013-10-01 01:47:35 +0000186void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000187 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000188 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000189
Andrew Kaylorea395922013-10-01 01:47:35 +0000190 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000191 assert(OwnedModules.ownsModule(M) &&
192 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000193
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000194 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000195 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000196 return;
197
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000198 std::unique_ptr<MemoryBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000199 // Try to load the pre-compiled object from cache if possible
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000200 if (ObjCache)
201 ObjectToLoad = ObjCache->getObject(M);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000202
Lang Hames717eacf2016-06-11 05:47:04 +0000203 assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
Rafael Espindola6763f5a2015-06-23 14:42:34 +0000204
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000205 // If the cache did not contain a suitable object, compile the object
206 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000207 ObjectToLoad = emitObject(M);
208 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000209 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000210
211 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000212 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000213 Expected<std::unique_ptr<object::ObjectFile>> LoadedObject =
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000214 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000215 if (!LoadedObject) {
216 std::string Buf;
217 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000218 logAllUnhandledErrors(LoadedObject.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000219 OS.flush();
220 report_fatal_error(Buf);
221 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000222 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
223 Dyld.loadObject(*LoadedObject.get());
224
225 if (Dyld.hasError())
Jim Grosbachc114d892011-03-23 19:51:34 +0000226 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000227
Lang Hameseca6d4b2018-12-04 00:55:15 +0000228 notifyObjectLoaded(*LoadedObject.get(), *L);
Andrew Kayloradc70562012-10-02 21:18:39 +0000229
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000230 Buffers.push_back(std::move(ObjectToLoad));
231 LoadedObjects.push_back(std::move(*LoadedObject));
David Blaikieed9709d2014-09-03 19:48:09 +0000232
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000233 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000234}
235
Andrew Kaylorea395922013-10-01 01:47:35 +0000236void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000237 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000238
Andrew Kaylorea395922013-10-01 01:47:35 +0000239 // Resolve any outstanding relocations.
240 Dyld.resolveRelocations();
241
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000242 OwnedModules.markAllLoadedModulesAsFinalized();
243
Andrew Kaylorea395922013-10-01 01:47:35 +0000244 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000245 Dyld.registerEHFrames();
246
Andrew Kaylorea395922013-10-01 01:47:35 +0000247 // Set page permissions.
Lang Hames633fe142015-03-30 03:37:06 +0000248 MemMgr->finalizeMemory();
Andrew Kaylorea395922013-10-01 01:47:35 +0000249}
250
251// FIXME: Rename this.
252void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000253 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000254
Lang Hames018452e2014-09-05 23:38:35 +0000255 // Generate code for module is going to move objects out of the 'added' list,
256 // so we need to copy that out before using it:
257 SmallVector<Module*, 16> ModsToAdd;
258 for (auto M : OwnedModules.added())
259 ModsToAdd.push_back(M);
260
261 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000262 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000263
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000264 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000265}
266
267void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000268 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000269
Andrew Kaylorea395922013-10-01 01:47:35 +0000270 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000271 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000272
273 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000274 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000275 generateCodeForModule(M);
276
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000277 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000278}
279
Lang Hamesad4a9112016-08-01 20:49:11 +0000280JITSymbol MCJIT::findExistingSymbol(const std::string &Name) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000281 if (void *Addr = getPointerToGlobalIfAvailable(Name))
Lang Hamesad4a9112016-08-01 20:49:11 +0000282 return JITSymbol(static_cast<uint64_t>(
283 reinterpret_cast<uintptr_t>(Addr)),
284 JITSymbolFlags::Exported);
Lang Hames3393cfd2015-07-29 23:12:33 +0000285
Lang Hames8d4be3a2016-09-12 17:19:24 +0000286 return Dyld.getSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000287}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000288
Andrew Kaylorea395922013-10-01 01:47:35 +0000289Module *MCJIT::findModuleForSymbol(const std::string &Name,
290 bool CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000291 StringRef DemangledName = Name;
292 if (DemangledName[0] == getDataLayout().getGlobalPrefix())
293 DemangledName = DemangledName.substr(1);
294
Zachary Turnerc04b8922014-06-20 21:07:14 +0000295 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000296
Andrew Kaylorea395922013-10-01 01:47:35 +0000297 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000298 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
299 E = OwnedModules.end_added();
300 I != E; ++I) {
301 Module *M = *I;
Lang Hames8d4be3a2016-09-12 17:19:24 +0000302 Function *F = M->getFunction(DemangledName);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000303 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000304 return M;
305 if (!CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000306 GlobalVariable *G = M->getGlobalVariable(DemangledName);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000307 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000308 return M;
309 // FIXME: Do we need to worry about global aliases?
310 }
311 }
312 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000313 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000314}
315
316uint64_t MCJIT::getSymbolAddress(const std::string &Name,
Lang Hames633fe142015-03-30 03:37:06 +0000317 bool CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000318 std::string MangledName;
319 {
320 raw_string_ostream MangledNameStream(MangledName);
321 Mangler::getNameWithPrefix(MangledNameStream, Name, getDataLayout());
322 }
Lang Hames4ce98662017-07-07 02:59:13 +0000323 if (auto Sym = findSymbol(MangledName, CheckFunctionsOnly)) {
324 if (auto AddrOrErr = Sym.getAddress())
325 return *AddrOrErr;
326 else
327 report_fatal_error(AddrOrErr.takeError());
Lang Hames942cb7b2018-08-15 20:11:21 +0000328 } else if (auto Err = Sym.takeError())
Lang Hames4ce98662017-07-07 02:59:13 +0000329 report_fatal_error(Sym.takeError());
Lang Hames942cb7b2018-08-15 20:11:21 +0000330 return 0;
Lang Hames633fe142015-03-30 03:37:06 +0000331}
332
Lang Hamesad4a9112016-08-01 20:49:11 +0000333JITSymbol MCJIT::findSymbol(const std::string &Name,
334 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000335 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000336
Andrew Kaylorea395922013-10-01 01:47:35 +0000337 // First, check to see if we already have this symbol.
Lang Hames633fe142015-03-30 03:37:06 +0000338 if (auto Sym = findExistingSymbol(Name))
339 return Sym;
Andrew Kaylorea395922013-10-01 01:47:35 +0000340
Rafael Espindola48af1c22014-08-19 18:44:46 +0000341 for (object::OwningBinary<object::Archive> &OB : Archives) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000342 object::Archive *A = OB.getBinary();
Lang Hames173c69f2014-01-08 04:09:09 +0000343 // Look for our symbols in each Archive
Lang Hames69f49022016-07-14 20:44:27 +0000344 auto OptionalChildOrErr = A->findSym(Name);
345 if (!OptionalChildOrErr)
346 report_fatal_error(OptionalChildOrErr.takeError());
347 auto &OptionalChild = *OptionalChildOrErr;
348 if (OptionalChild) {
Lang Hames173c69f2014-01-08 04:09:09 +0000349 // FIXME: Support nested archives?
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000350 Expected<std::unique_ptr<object::Binary>> ChildBinOrErr =
Lang Hames69f49022016-07-14 20:44:27 +0000351 OptionalChild->getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000352 if (!ChildBinOrErr) {
353 // TODO: Actually report errors helpfully.
354 consumeError(ChildBinOrErr.takeError());
Rafael Espindolaae460022014-06-16 16:08:36 +0000355 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000356 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000357 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000358 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000359 std::unique_ptr<object::ObjectFile> OF(
360 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000361 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000362 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000363 // The address should be here now.
Lang Hames633fe142015-03-30 03:37:06 +0000364 if (auto Sym = findExistingSymbol(Name))
365 return Sym;
Lang Hames173c69f2014-01-08 04:09:09 +0000366 }
367 }
368 }
369
Andrew Kaylorea395922013-10-01 01:47:35 +0000370 // If it hasn't already been generated, see if it's in one of our modules.
371 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000372 if (M) {
373 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000374
Lang Hamesea800ca2014-08-14 02:38:20 +0000375 // Check the RuntimeDyld table again, it should be there now.
Lang Hames633fe142015-03-30 03:37:06 +0000376 return findExistingSymbol(Name);
Lang Hamesea800ca2014-08-14 02:38:20 +0000377 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000378
Lang Hamesea800ca2014-08-14 02:38:20 +0000379 // If a LazyFunctionCreator is installed, use it to get/create the function.
380 // FIXME: Should we instead have a LazySymbolCreator callback?
Lang Hames633fe142015-03-30 03:37:06 +0000381 if (LazyFunctionCreator) {
382 auto Addr = static_cast<uint64_t>(
383 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
Lang Hamesad4a9112016-08-01 20:49:11 +0000384 return JITSymbol(Addr, JITSymbolFlags::Exported);
Lang Hames633fe142015-03-30 03:37:06 +0000385 }
Lang Hamesea800ca2014-08-14 02:38:20 +0000386
Lang Hames633fe142015-03-30 03:37:06 +0000387 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000388}
389
390uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000391 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000392 uint64_t Result = getSymbolAddress(Name, false);
393 if (Result != 0)
394 finalizeLoadedModules();
395 return Result;
396}
397
398uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000399 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000400 uint64_t Result = getSymbolAddress(Name, true);
401 if (Result != 0)
402 finalizeLoadedModules();
403 return Result;
404}
405
406// Deprecated. Use getFunctionAddress instead.
407void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000408 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000409
Rafael Espindolac233f742015-06-23 13:59:29 +0000410 Mangler Mang;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000411 SmallString<128> Name;
412 TM->getNameWithPrefix(Name, F, Mang);
413
Jim Grosbachd5274402011-03-22 18:05:27 +0000414 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
415 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000416 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000417 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000418 return Addr;
419 }
420
Andrew Kaylorea395922013-10-01 01:47:35 +0000421 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000422 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000423
424 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000425 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000426 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000427 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000428 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000429 // FIXME: Asking for the pointer to a function that hasn't been registered,
430 // and isn't a declaration (which is handled above) should probably
431 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000432 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000433 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000434
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000435 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000436 //
437 // This is the accessor for the target address, so make sure to check the
438 // load address of the symbol, not the local address.
Lang Hamesb1186032015-03-11 00:43:26 +0000439 return (void*)Dyld.getSymbol(Name).getAddress();
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000440}
441
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000442void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
443 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
444 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000445 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000446 }
447}
448
449void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
450 // Execute global ctors/dtors for each module in the program.
451 runStaticConstructorsDestructorsInModulePtrSet(
452 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
453 runStaticConstructorsDestructorsInModulePtrSet(
454 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
455 runStaticConstructorsDestructorsInModulePtrSet(
456 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
457}
458
Mehdi Amini7419e942016-10-01 06:22:04 +0000459Function *MCJIT::FindFunctionNamedInModulePtrSet(StringRef FnName,
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000460 ModulePtrSet::iterator I,
461 ModulePtrSet::iterator E) {
462 for (; I != E; ++I) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000463 Function *F = (*I)->getFunction(FnName);
464 if (F && !F->isDeclaration())
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000465 return F;
466 }
Craig Topper353eda42014-04-24 06:44:33 +0000467 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000468}
469
Mehdi Amini7419e942016-10-01 06:22:04 +0000470GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(StringRef Name,
Keno Fischer73378eb2015-06-20 00:55:58 +0000471 bool AllowInternal,
472 ModulePtrSet::iterator I,
473 ModulePtrSet::iterator E) {
474 for (; I != E; ++I) {
475 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
476 if (GV && !GV->isDeclaration())
477 return GV;
478 }
479 return nullptr;
480}
481
482
Mehdi Amini7419e942016-10-01 06:22:04 +0000483Function *MCJIT::FindFunctionNamed(StringRef FnName) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000484 Function *F = FindFunctionNamedInModulePtrSet(
485 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
486 if (!F)
487 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
488 OwnedModules.end_loaded());
489 if (!F)
490 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
491 OwnedModules.end_finalized());
492 return F;
493}
494
Mehdi Amini7419e942016-10-01 06:22:04 +0000495GlobalVariable *MCJIT::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
Keno Fischer73378eb2015-06-20 00:55:58 +0000496 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
497 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
498 if (!GV)
499 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
500 OwnedModules.end_loaded());
501 if (!GV)
502 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
503 OwnedModules.end_finalized());
504 return GV;
505}
506
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000507GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000508 assert(F && "Function *F was null at entry to run()");
509
Jim Grosbach7b162492011-03-18 22:48:41 +0000510 void *FPtr = getPointerToFunction(F);
Lang Hames717eacf2016-06-11 05:47:04 +0000511 finalizeModule(F->getParent());
Jim Grosbachd5274402011-03-22 18:05:27 +0000512 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000513 FunctionType *FTy = F->getFunctionType();
514 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000515
516 assert((FTy->getNumParams() == ArgValues.size() ||
517 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
518 "Wrong number of arguments passed into function!");
519 assert(FTy->getNumParams() == ArgValues.size() &&
520 "This doesn't support passing arguments through varargs (yet)!");
521
522 // Handle some common cases first. These cases correspond to common `main'
523 // prototypes.
524 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
525 switch (ArgValues.size()) {
526 case 3:
527 if (FTy->getParamType(0)->isIntegerTy(32) &&
528 FTy->getParamType(1)->isPointerTy() &&
529 FTy->getParamType(2)->isPointerTy()) {
530 int (*PF)(int, char **, const char **) =
531 (int(*)(int, char **, const char **))(intptr_t)FPtr;
532
533 // Call the function.
534 GenericValue rv;
535 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
536 (char **)GVTOP(ArgValues[1]),
537 (const char **)GVTOP(ArgValues[2])));
538 return rv;
539 }
540 break;
541 case 2:
542 if (FTy->getParamType(0)->isIntegerTy(32) &&
543 FTy->getParamType(1)->isPointerTy()) {
544 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
545
546 // Call the function.
547 GenericValue rv;
548 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
549 (char **)GVTOP(ArgValues[1])));
550 return rv;
551 }
552 break;
553 case 1:
554 if (FTy->getNumParams() == 1 &&
555 FTy->getParamType(0)->isIntegerTy(32)) {
556 GenericValue rv;
557 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
558 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
559 return rv;
560 }
561 break;
562 }
563 }
564
565 // Handle cases where no arguments are passed first.
566 if (ArgValues.empty()) {
567 GenericValue rv;
568 switch (RetTy->getTypeID()) {
569 default: llvm_unreachable("Unknown return type for function call!");
570 case Type::IntegerTyID: {
571 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
572 if (BitWidth == 1)
573 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
574 else if (BitWidth <= 8)
575 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
576 else if (BitWidth <= 16)
577 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
578 else if (BitWidth <= 32)
579 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
580 else if (BitWidth <= 64)
581 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
582 else
583 llvm_unreachable("Integer types > 64 bits not supported");
584 return rv;
585 }
586 case Type::VoidTyID:
587 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
588 return rv;
589 case Type::FloatTyID:
590 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
591 return rv;
592 case Type::DoubleTyID:
593 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
594 return rv;
595 case Type::X86_FP80TyID:
596 case Type::FP128TyID:
597 case Type::PPC_FP128TyID:
598 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000599 case Type::PointerTyID:
600 return PTOGV(((void*(*)())(intptr_t)FPtr)());
601 }
602 }
603
Lang Hames30526072016-08-11 15:56:23 +0000604 report_fatal_error("MCJIT::runFunction does not support full-featured "
605 "argument passing. Please use "
606 "ExecutionEngine::getFunctionAddress and cast the result "
607 "to the desired function pointer type.");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000608}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000609
Lang Hames9a783342014-09-15 17:50:22 +0000610void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000611 if (!isSymbolSearchingDisabled()) {
Lang Hames4ce98662017-07-07 02:59:13 +0000612 if (auto Sym = Resolver.findSymbol(Name)) {
613 if (auto AddrOrErr = Sym.getAddress())
614 return reinterpret_cast<void*>(
615 static_cast<uintptr_t>(*AddrOrErr));
616 } else if (auto Err = Sym.takeError())
617 report_fatal_error(std::move(Err));
Danil Malyshevbfee5422012-03-28 21:46:36 +0000618 }
619
620 /// If a LazyFunctionCreator is installed, use it to get/create the function.
621 if (LazyFunctionCreator)
622 if (void *RP = LazyFunctionCreator(Name))
623 return RP;
624
625 if (AbortOnFailure) {
626 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000627 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000628 }
Craig Topper353eda42014-04-24 06:44:33 +0000629 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000630}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000631
632void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000633 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000634 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000635 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000636 EventListeners.push_back(L);
637}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000638
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000639void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000640 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000641 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000642 MutexGuard locked(lock);
David Majnemer42531262016-08-12 03:55:06 +0000643 auto I = find(reverse(EventListeners), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000644 if (I != EventListeners.rend()) {
645 std::swap(*I, EventListeners.back());
646 EventListeners.pop_back();
647 }
648}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000649
Lang Hameseca6d4b2018-12-04 00:55:15 +0000650void MCJIT::notifyObjectLoaded(const object::ObjectFile &Obj,
651 const RuntimeDyld::LoadedObjectInfo &L) {
652 uint64_t Key =
653 static_cast<uint64_t>(reinterpret_cast<uintptr_t>(Obj.getData().data()));
Zachary Turnerc04b8922014-06-20 21:07:14 +0000654 MutexGuard locked(lock);
Lang Hames633fe142015-03-30 03:37:06 +0000655 MemMgr->notifyObjectLoaded(this, Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000656 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Lang Hameseca6d4b2018-12-04 00:55:15 +0000657 EventListeners[I]->notifyObjectLoaded(Key, Obj, L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000658 }
659}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000660
Lang Hameseca6d4b2018-12-04 00:55:15 +0000661void MCJIT::notifyFreeingObject(const object::ObjectFile &Obj) {
662 uint64_t Key =
663 static_cast<uint64_t>(reinterpret_cast<uintptr_t>(Obj.getData().data()));
Zachary Turnerc04b8922014-06-20 21:07:14 +0000664 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000665 for (JITEventListener *L : EventListeners)
Lang Hameseca6d4b2018-12-04 00:55:15 +0000666 L->notifyFreeingObject(Key);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000667}
Andrew Kaylorea395922013-10-01 01:47:35 +0000668
Lang Hamesad4a9112016-08-01 20:49:11 +0000669JITSymbol
Lang Hames633fe142015-03-30 03:37:06 +0000670LinkingSymbolResolver::findSymbol(const std::string &Name) {
671 auto Result = ParentEngine.findSymbol(Name, false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000672 if (Result)
673 return Result;
Lang Hames633fe142015-03-30 03:37:06 +0000674 if (ParentEngine.isSymbolSearchingDisabled())
675 return nullptr;
676 return ClientResolver->findSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000677}
Weiming Zhao1bd40002018-04-11 23:09:20 +0000678
679void LinkingSymbolResolver::anchor() {}