blob: 82647ea944016b588bb918f1fdd03d3483517889 [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"
Lang Hames173c69f2014-01-08 04:09:09 +000022#include "llvm/Object/Archive.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000023#include "llvm/Object/ObjectFile.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000024#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000026#include "llvm/Support/MemoryBuffer.h"
Zachary Turnerc04b8922014-06-20 21:07:14 +000027#include "llvm/Support/MutexGuard.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000028
29using namespace llvm;
30
31namespace {
32
33static struct RegisterJIT {
34 RegisterJIT() { MCJIT::Register(); }
35} JITRegistrator;
36
37}
38
39extern "C" void LLVMLinkInMCJIT() {
40}
41
Lang Hamesb72f4842018-01-19 22:24:13 +000042ExecutionEngine *
43MCJIT::createJIT(std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hames633fe142015-03-30 03:37:06 +000044 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesb72f4842018-01-19 22:24:13 +000045 std::shared_ptr<LegacyJITSymbolResolver> Resolver,
Lang Hames633fe142015-03-30 03:37:06 +000046 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000047 // Try to register the program as a source of symbols to resolve against.
48 //
49 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000050 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000051
Lang Hames633fe142015-03-30 03:37:06 +000052 if (!MemMgr || !Resolver) {
53 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
54 if (!MemMgr)
55 MemMgr = RTDyldMM;
56 if (!Resolver)
57 Resolver = RTDyldMM;
58 }
Lang Hames4a5697e2014-12-03 00:51:19 +000059
Lang Hames633fe142015-03-30 03:37:06 +000060 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
61 std::move(Resolver));
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000062}
63
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000064MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
Lang Hames633fe142015-03-30 03:37:06 +000065 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesb72f4842018-01-19 22:24:13 +000066 std::shared_ptr<LegacyJITSymbolResolver> Resolver)
Mehdi Amini26d48132015-07-24 16:04:22 +000067 : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000068 Ctx(nullptr), MemMgr(std::move(MemMgr)),
69 Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
70 ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000071 // FIXME: We are managing our modules, so we do not want the base class
72 // ExecutionEngine to manage them as well. To avoid double destruction
73 // of the first (and only) module added in ExecutionEngine constructor
74 // we remove it from EE and will destruct it ourselves.
75 //
76 // It may make sense to move our module manager (based on SmallStPtr) back
77 // into EE if the JIT and Interpreter can live with it.
78 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
79 // runStaticConstructorsDestructors could be moved back to EE as well.
80 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000081 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000082 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000083
Lang Hames717eacf2016-06-11 05:47:04 +000084 if (First->getDataLayout().isDefault())
85 First->setDataLayout(getDataLayout());
86
Rafael Espindola2a8a2792014-08-19 04:04:25 +000087 OwnedModules.addModule(std::move(First));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000088 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
Rafael Espindola2a8a2792014-08-19 04:04:25 +000089}
90
91MCJIT::~MCJIT() {
92 MutexGuard locked(lock);
93
Andrew Kaylorc442a762013-10-16 00:14:21 +000094 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000095
David Blaikieed9709d2014-09-03 19:48:09 +000096 for (auto &Obj : LoadedObjects)
97 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +000098 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +000099
Lang Hames173c69f2014-01-08 04:09:09 +0000100 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000101}
102
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000103void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000104 MutexGuard locked(lock);
Lang Hames717eacf2016-06-11 05:47:04 +0000105
106 if (M->getDataLayout().isDefault())
107 M->setDataLayout(getDataLayout());
108
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000109 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +0000110}
111
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000112bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000113 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000114 return OwnedModules.removeModule(M);
115}
116
David Blaikie7a1e7752014-04-29 21:52:46 +0000117void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000118 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
119 if (Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000120 report_fatal_error(Dyld.getErrorString());
121
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000122 NotifyObjectEmitted(*Obj, *L);
David Blaikie168861a2014-09-04 18:37:31 +0000123
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000124 LoadedObjects.push_back(std::move(Obj));
Lang Hames173c69f2014-01-08 04:09:09 +0000125}
126
Rafael Espindola7271c192014-08-26 21:04:04 +0000127void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000128 std::unique_ptr<object::ObjectFile> ObjFile;
129 std::unique_ptr<MemoryBuffer> MemBuf;
130 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
131 addObjectFile(std::move(ObjFile));
132 Buffers.push_back(std::move(MemBuf));
Rafael Espindola7271c192014-08-26 21:04:04 +0000133}
134
Rafael Espindola48af1c22014-08-19 18:44:46 +0000135void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000136 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000137}
138
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000139void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000140 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000141 ObjCache = NewCache;
142}
143
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000144std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000145 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000146
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000147 // This must be a module which has already been added but not loaded to this
148 // MCJIT instance, since these conditions are tested by our caller,
149 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000150
Chandler Carruth30d69c22015-02-13 10:01:29 +0000151 legacy::PassManager PM;
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000152
Andrew Kayloradc70562012-10-02 21:18:39 +0000153 // The RuntimeDyld will take ownership of this shortly
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000154 SmallVector<char, 4096> ObjBufferSV;
155 raw_svector_ostream ObjStream(ObjBufferSV);
Andrew Kayloradc70562012-10-02 21:18:39 +0000156
Jim Grosbach7b162492011-03-18 22:48:41 +0000157 // Turn the machine code intermediate representation into bytes in memory
158 // that may be executed.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000159 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
Jim Grosbach7b162492011-03-18 22:48:41 +0000160 report_fatal_error("Target does not support MC emission!");
Jim Grosbach7b162492011-03-18 22:48:41 +0000161
162 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000163 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000164 // Flush the output buffer to get the generated code into memory
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000165
166 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
Weiming Zhao79f2d092018-04-16 03:44:03 +0000167 new SmallVectorMemoryBuffer(std::move(ObjBufferSV)));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000168
169 // If we have an object cache, tell it about the new object.
170 // Note that we're using the compiled image, not the loaded image (as below).
171 if (ObjCache) {
172 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
173 // to create a temporary object here and delete it after the call.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000174 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
Rafael Espindola48af1c22014-08-19 18:44:46 +0000175 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000176 }
177
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000178 return CompiledObjBuffer;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000179}
180
Andrew Kaylorea395922013-10-01 01:47:35 +0000181void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000182 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000183 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000184
Andrew Kaylorea395922013-10-01 01:47:35 +0000185 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000186 assert(OwnedModules.ownsModule(M) &&
187 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000188
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000189 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000190 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000191 return;
192
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000193 std::unique_ptr<MemoryBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000194 // Try to load the pre-compiled object from cache if possible
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000195 if (ObjCache)
196 ObjectToLoad = ObjCache->getObject(M);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000197
Lang Hames717eacf2016-06-11 05:47:04 +0000198 assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
Rafael Espindola6763f5a2015-06-23 14:42:34 +0000199
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000200 // If the cache did not contain a suitable object, compile the object
201 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000202 ObjectToLoad = emitObject(M);
203 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000204 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000205
206 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000207 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000208 Expected<std::unique_ptr<object::ObjectFile>> LoadedObject =
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000209 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000210 if (!LoadedObject) {
211 std::string Buf;
212 raw_string_ostream OS(Buf);
213 logAllUnhandledErrors(LoadedObject.takeError(), OS, "");
214 OS.flush();
215 report_fatal_error(Buf);
216 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000217 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
218 Dyld.loadObject(*LoadedObject.get());
219
220 if (Dyld.hasError())
Jim Grosbachc114d892011-03-23 19:51:34 +0000221 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000222
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000223 NotifyObjectEmitted(*LoadedObject.get(), *L);
Andrew Kayloradc70562012-10-02 21:18:39 +0000224
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000225 Buffers.push_back(std::move(ObjectToLoad));
226 LoadedObjects.push_back(std::move(*LoadedObject));
David Blaikieed9709d2014-09-03 19:48:09 +0000227
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000228 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000229}
230
Andrew Kaylorea395922013-10-01 01:47:35 +0000231void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000232 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000233
Andrew Kaylorea395922013-10-01 01:47:35 +0000234 // Resolve any outstanding relocations.
235 Dyld.resolveRelocations();
236
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000237 OwnedModules.markAllLoadedModulesAsFinalized();
238
Andrew Kaylorea395922013-10-01 01:47:35 +0000239 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000240 Dyld.registerEHFrames();
241
Andrew Kaylorea395922013-10-01 01:47:35 +0000242 // Set page permissions.
Lang Hames633fe142015-03-30 03:37:06 +0000243 MemMgr->finalizeMemory();
Andrew Kaylorea395922013-10-01 01:47:35 +0000244}
245
246// FIXME: Rename this.
247void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000248 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000249
Lang Hames018452e2014-09-05 23:38:35 +0000250 // Generate code for module is going to move objects out of the 'added' list,
251 // so we need to copy that out before using it:
252 SmallVector<Module*, 16> ModsToAdd;
253 for (auto M : OwnedModules.added())
254 ModsToAdd.push_back(M);
255
256 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000257 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000258
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000259 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000260}
261
262void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000263 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000264
Andrew Kaylorea395922013-10-01 01:47:35 +0000265 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000266 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000267
268 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000269 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000270 generateCodeForModule(M);
271
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000272 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000273}
274
Lang Hamesad4a9112016-08-01 20:49:11 +0000275JITSymbol MCJIT::findExistingSymbol(const std::string &Name) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000276 if (void *Addr = getPointerToGlobalIfAvailable(Name))
Lang Hamesad4a9112016-08-01 20:49:11 +0000277 return JITSymbol(static_cast<uint64_t>(
278 reinterpret_cast<uintptr_t>(Addr)),
279 JITSymbolFlags::Exported);
Lang Hames3393cfd2015-07-29 23:12:33 +0000280
Lang Hames8d4be3a2016-09-12 17:19:24 +0000281 return Dyld.getSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000282}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000283
Andrew Kaylorea395922013-10-01 01:47:35 +0000284Module *MCJIT::findModuleForSymbol(const std::string &Name,
285 bool CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000286 StringRef DemangledName = Name;
287 if (DemangledName[0] == getDataLayout().getGlobalPrefix())
288 DemangledName = DemangledName.substr(1);
289
Zachary Turnerc04b8922014-06-20 21:07:14 +0000290 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000291
Andrew Kaylorea395922013-10-01 01:47:35 +0000292 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000293 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
294 E = OwnedModules.end_added();
295 I != E; ++I) {
296 Module *M = *I;
Lang Hames8d4be3a2016-09-12 17:19:24 +0000297 Function *F = M->getFunction(DemangledName);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000298 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000299 return M;
300 if (!CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000301 GlobalVariable *G = M->getGlobalVariable(DemangledName);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000302 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000303 return M;
304 // FIXME: Do we need to worry about global aliases?
305 }
306 }
307 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000308 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000309}
310
311uint64_t MCJIT::getSymbolAddress(const std::string &Name,
Lang Hames633fe142015-03-30 03:37:06 +0000312 bool CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000313 std::string MangledName;
314 {
315 raw_string_ostream MangledNameStream(MangledName);
316 Mangler::getNameWithPrefix(MangledNameStream, Name, getDataLayout());
317 }
Lang Hames4ce98662017-07-07 02:59:13 +0000318 if (auto Sym = findSymbol(MangledName, CheckFunctionsOnly)) {
319 if (auto AddrOrErr = Sym.getAddress())
320 return *AddrOrErr;
321 else
322 report_fatal_error(AddrOrErr.takeError());
323 } else
324 report_fatal_error(Sym.takeError());
Lang Hames633fe142015-03-30 03:37:06 +0000325}
326
Lang Hamesad4a9112016-08-01 20:49:11 +0000327JITSymbol MCJIT::findSymbol(const std::string &Name,
328 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000329 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000330
Andrew Kaylorea395922013-10-01 01:47:35 +0000331 // First, check to see if we already have this symbol.
Lang Hames633fe142015-03-30 03:37:06 +0000332 if (auto Sym = findExistingSymbol(Name))
333 return Sym;
Andrew Kaylorea395922013-10-01 01:47:35 +0000334
Rafael Espindola48af1c22014-08-19 18:44:46 +0000335 for (object::OwningBinary<object::Archive> &OB : Archives) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000336 object::Archive *A = OB.getBinary();
Lang Hames173c69f2014-01-08 04:09:09 +0000337 // Look for our symbols in each Archive
Lang Hames69f49022016-07-14 20:44:27 +0000338 auto OptionalChildOrErr = A->findSym(Name);
339 if (!OptionalChildOrErr)
340 report_fatal_error(OptionalChildOrErr.takeError());
341 auto &OptionalChild = *OptionalChildOrErr;
342 if (OptionalChild) {
Lang Hames173c69f2014-01-08 04:09:09 +0000343 // FIXME: Support nested archives?
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000344 Expected<std::unique_ptr<object::Binary>> ChildBinOrErr =
Lang Hames69f49022016-07-14 20:44:27 +0000345 OptionalChild->getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000346 if (!ChildBinOrErr) {
347 // TODO: Actually report errors helpfully.
348 consumeError(ChildBinOrErr.takeError());
Rafael Espindolaae460022014-06-16 16:08:36 +0000349 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000350 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000351 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000352 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000353 std::unique_ptr<object::ObjectFile> OF(
354 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000355 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000356 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000357 // The address should be here now.
Lang Hames633fe142015-03-30 03:37:06 +0000358 if (auto Sym = findExistingSymbol(Name))
359 return Sym;
Lang Hames173c69f2014-01-08 04:09:09 +0000360 }
361 }
362 }
363
Andrew Kaylorea395922013-10-01 01:47:35 +0000364 // If it hasn't already been generated, see if it's in one of our modules.
365 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000366 if (M) {
367 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000368
Lang Hamesea800ca2014-08-14 02:38:20 +0000369 // Check the RuntimeDyld table again, it should be there now.
Lang Hames633fe142015-03-30 03:37:06 +0000370 return findExistingSymbol(Name);
Lang Hamesea800ca2014-08-14 02:38:20 +0000371 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000372
Lang Hamesea800ca2014-08-14 02:38:20 +0000373 // If a LazyFunctionCreator is installed, use it to get/create the function.
374 // FIXME: Should we instead have a LazySymbolCreator callback?
Lang Hames633fe142015-03-30 03:37:06 +0000375 if (LazyFunctionCreator) {
376 auto Addr = static_cast<uint64_t>(
377 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
Lang Hamesad4a9112016-08-01 20:49:11 +0000378 return JITSymbol(Addr, JITSymbolFlags::Exported);
Lang Hames633fe142015-03-30 03:37:06 +0000379 }
Lang Hamesea800ca2014-08-14 02:38:20 +0000380
Lang Hames633fe142015-03-30 03:37:06 +0000381 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000382}
383
384uint64_t MCJIT::getGlobalValueAddress(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, false);
387 if (Result != 0)
388 finalizeLoadedModules();
389 return Result;
390}
391
392uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000393 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000394 uint64_t Result = getSymbolAddress(Name, true);
395 if (Result != 0)
396 finalizeLoadedModules();
397 return Result;
398}
399
400// Deprecated. Use getFunctionAddress instead.
401void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000402 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000403
Rafael Espindolac233f742015-06-23 13:59:29 +0000404 Mangler Mang;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000405 SmallString<128> Name;
406 TM->getNameWithPrefix(Name, F, Mang);
407
Jim Grosbachd5274402011-03-22 18:05:27 +0000408 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
409 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000410 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000411 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000412 return Addr;
413 }
414
Andrew Kaylorea395922013-10-01 01:47:35 +0000415 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000416 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000417
418 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000419 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000420 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000421 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000422 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000423 // FIXME: Asking for the pointer to a function that hasn't been registered,
424 // and isn't a declaration (which is handled above) should probably
425 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000426 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000427 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000428
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000429 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000430 //
431 // This is the accessor for the target address, so make sure to check the
432 // load address of the symbol, not the local address.
Lang Hamesb1186032015-03-11 00:43:26 +0000433 return (void*)Dyld.getSymbol(Name).getAddress();
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000434}
435
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000436void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
437 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
438 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000439 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000440 }
441}
442
443void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
444 // Execute global ctors/dtors for each module in the program.
445 runStaticConstructorsDestructorsInModulePtrSet(
446 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
447 runStaticConstructorsDestructorsInModulePtrSet(
448 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
449 runStaticConstructorsDestructorsInModulePtrSet(
450 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
451}
452
Mehdi Amini7419e942016-10-01 06:22:04 +0000453Function *MCJIT::FindFunctionNamedInModulePtrSet(StringRef FnName,
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000454 ModulePtrSet::iterator I,
455 ModulePtrSet::iterator E) {
456 for (; I != E; ++I) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000457 Function *F = (*I)->getFunction(FnName);
458 if (F && !F->isDeclaration())
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000459 return F;
460 }
Craig Topper353eda42014-04-24 06:44:33 +0000461 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000462}
463
Mehdi Amini7419e942016-10-01 06:22:04 +0000464GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(StringRef Name,
Keno Fischer73378eb2015-06-20 00:55:58 +0000465 bool AllowInternal,
466 ModulePtrSet::iterator I,
467 ModulePtrSet::iterator E) {
468 for (; I != E; ++I) {
469 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
470 if (GV && !GV->isDeclaration())
471 return GV;
472 }
473 return nullptr;
474}
475
476
Mehdi Amini7419e942016-10-01 06:22:04 +0000477Function *MCJIT::FindFunctionNamed(StringRef FnName) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000478 Function *F = FindFunctionNamedInModulePtrSet(
479 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
480 if (!F)
481 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
482 OwnedModules.end_loaded());
483 if (!F)
484 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
485 OwnedModules.end_finalized());
486 return F;
487}
488
Mehdi Amini7419e942016-10-01 06:22:04 +0000489GlobalVariable *MCJIT::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
Keno Fischer73378eb2015-06-20 00:55:58 +0000490 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
491 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
492 if (!GV)
493 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
494 OwnedModules.end_loaded());
495 if (!GV)
496 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
497 OwnedModules.end_finalized());
498 return GV;
499}
500
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000501GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000502 assert(F && "Function *F was null at entry to run()");
503
Jim Grosbach7b162492011-03-18 22:48:41 +0000504 void *FPtr = getPointerToFunction(F);
Lang Hames717eacf2016-06-11 05:47:04 +0000505 finalizeModule(F->getParent());
Jim Grosbachd5274402011-03-22 18:05:27 +0000506 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000507 FunctionType *FTy = F->getFunctionType();
508 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000509
510 assert((FTy->getNumParams() == ArgValues.size() ||
511 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
512 "Wrong number of arguments passed into function!");
513 assert(FTy->getNumParams() == ArgValues.size() &&
514 "This doesn't support passing arguments through varargs (yet)!");
515
516 // Handle some common cases first. These cases correspond to common `main'
517 // prototypes.
518 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
519 switch (ArgValues.size()) {
520 case 3:
521 if (FTy->getParamType(0)->isIntegerTy(32) &&
522 FTy->getParamType(1)->isPointerTy() &&
523 FTy->getParamType(2)->isPointerTy()) {
524 int (*PF)(int, char **, const char **) =
525 (int(*)(int, char **, const char **))(intptr_t)FPtr;
526
527 // Call the function.
528 GenericValue rv;
529 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
530 (char **)GVTOP(ArgValues[1]),
531 (const char **)GVTOP(ArgValues[2])));
532 return rv;
533 }
534 break;
535 case 2:
536 if (FTy->getParamType(0)->isIntegerTy(32) &&
537 FTy->getParamType(1)->isPointerTy()) {
538 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
539
540 // Call the function.
541 GenericValue rv;
542 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
543 (char **)GVTOP(ArgValues[1])));
544 return rv;
545 }
546 break;
547 case 1:
548 if (FTy->getNumParams() == 1 &&
549 FTy->getParamType(0)->isIntegerTy(32)) {
550 GenericValue rv;
551 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
552 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
553 return rv;
554 }
555 break;
556 }
557 }
558
559 // Handle cases where no arguments are passed first.
560 if (ArgValues.empty()) {
561 GenericValue rv;
562 switch (RetTy->getTypeID()) {
563 default: llvm_unreachable("Unknown return type for function call!");
564 case Type::IntegerTyID: {
565 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
566 if (BitWidth == 1)
567 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
568 else if (BitWidth <= 8)
569 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
570 else if (BitWidth <= 16)
571 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
572 else if (BitWidth <= 32)
573 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
574 else if (BitWidth <= 64)
575 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
576 else
577 llvm_unreachable("Integer types > 64 bits not supported");
578 return rv;
579 }
580 case Type::VoidTyID:
581 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
582 return rv;
583 case Type::FloatTyID:
584 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
585 return rv;
586 case Type::DoubleTyID:
587 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
588 return rv;
589 case Type::X86_FP80TyID:
590 case Type::FP128TyID:
591 case Type::PPC_FP128TyID:
592 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000593 case Type::PointerTyID:
594 return PTOGV(((void*(*)())(intptr_t)FPtr)());
595 }
596 }
597
Lang Hames30526072016-08-11 15:56:23 +0000598 report_fatal_error("MCJIT::runFunction does not support full-featured "
599 "argument passing. Please use "
600 "ExecutionEngine::getFunctionAddress and cast the result "
601 "to the desired function pointer type.");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000602}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000603
Lang Hames9a783342014-09-15 17:50:22 +0000604void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000605 if (!isSymbolSearchingDisabled()) {
Lang Hames4ce98662017-07-07 02:59:13 +0000606 if (auto Sym = Resolver.findSymbol(Name)) {
607 if (auto AddrOrErr = Sym.getAddress())
608 return reinterpret_cast<void*>(
609 static_cast<uintptr_t>(*AddrOrErr));
610 } else if (auto Err = Sym.takeError())
611 report_fatal_error(std::move(Err));
Danil Malyshevbfee5422012-03-28 21:46:36 +0000612 }
613
614 /// If a LazyFunctionCreator is installed, use it to get/create the function.
615 if (LazyFunctionCreator)
616 if (void *RP = LazyFunctionCreator(Name))
617 return RP;
618
619 if (AbortOnFailure) {
620 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000621 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000622 }
Craig Topper353eda42014-04-24 06:44:33 +0000623 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000624}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000625
626void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000627 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000628 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000629 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000630 EventListeners.push_back(L);
631}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000632
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000633void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000634 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000635 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000636 MutexGuard locked(lock);
David Majnemer42531262016-08-12 03:55:06 +0000637 auto I = find(reverse(EventListeners), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000638 if (I != EventListeners.rend()) {
639 std::swap(*I, EventListeners.back());
640 EventListeners.pop_back();
641 }
642}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000643
644void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
645 const RuntimeDyld::LoadedObjectInfo &L) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000646 MutexGuard locked(lock);
Lang Hames633fe142015-03-30 03:37:06 +0000647 MemMgr->notifyObjectLoaded(this, Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000648 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000649 EventListeners[I]->NotifyObjectEmitted(Obj, L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000650 }
651}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000652
653void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000654 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000655 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000656 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000657}
Andrew Kaylorea395922013-10-01 01:47:35 +0000658
Lang Hamesad4a9112016-08-01 20:49:11 +0000659JITSymbol
Lang Hames633fe142015-03-30 03:37:06 +0000660LinkingSymbolResolver::findSymbol(const std::string &Name) {
661 auto Result = ParentEngine.findSymbol(Name, false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000662 if (Result)
663 return Result;
Lang Hames633fe142015-03-30 03:37:06 +0000664 if (ParentEngine.isSymbolSearchingDisabled())
665 return nullptr;
666 return ClientResolver->findSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000667}
Weiming Zhao1bd40002018-04-11 23:09:20 +0000668
669void LinkingSymbolResolver::anchor() {}