blob: 3aa6f2c3fb2c529f076045120e914f833715baad [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
32namespace {
33
34static struct RegisterJIT {
35 RegisterJIT() { MCJIT::Register(); }
36} JITRegistrator;
37
38}
39
40extern "C" void LLVMLinkInMCJIT() {
41}
42
Lang Hames633fe142015-03-30 03:37:06 +000043ExecutionEngine*
44MCJIT::createJIT(std::unique_ptr<Module> M,
45 std::string *ErrorStr,
46 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesad4a9112016-08-01 20:49:11 +000047 std::shared_ptr<JITSymbolResolver> Resolver,
Lang Hames633fe142015-03-30 03:37:06 +000048 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000049 // Try to register the program as a source of symbols to resolve against.
50 //
51 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000052 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000053
Lang Hames633fe142015-03-30 03:37:06 +000054 if (!MemMgr || !Resolver) {
55 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
56 if (!MemMgr)
57 MemMgr = RTDyldMM;
58 if (!Resolver)
59 Resolver = RTDyldMM;
60 }
Lang Hames4a5697e2014-12-03 00:51:19 +000061
Lang Hames633fe142015-03-30 03:37:06 +000062 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
63 std::move(Resolver));
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000064}
65
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000066MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
Lang Hames633fe142015-03-30 03:37:06 +000067 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesad4a9112016-08-01 20:49:11 +000068 std::shared_ptr<JITSymbolResolver> Resolver)
Mehdi Amini26d48132015-07-24 16:04:22 +000069 : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000070 Ctx(nullptr), MemMgr(std::move(MemMgr)),
71 Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
72 ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000073 // FIXME: We are managing our modules, so we do not want the base class
74 // ExecutionEngine to manage them as well. To avoid double destruction
75 // of the first (and only) module added in ExecutionEngine constructor
76 // we remove it from EE and will destruct it ourselves.
77 //
78 // It may make sense to move our module manager (based on SmallStPtr) back
79 // into EE if the JIT and Interpreter can live with it.
80 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
81 // runStaticConstructorsDestructors could be moved back to EE as well.
82 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000083 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000084 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000085
Lang Hames717eacf2016-06-11 05:47:04 +000086 if (First->getDataLayout().isDefault())
87 First->setDataLayout(getDataLayout());
88
Rafael Espindola2a8a2792014-08-19 04:04:25 +000089 OwnedModules.addModule(std::move(First));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000090 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
Rafael Espindola2a8a2792014-08-19 04:04:25 +000091}
92
93MCJIT::~MCJIT() {
94 MutexGuard locked(lock);
95
Andrew Kaylorc442a762013-10-16 00:14:21 +000096 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000097
David Blaikieed9709d2014-09-03 19:48:09 +000098 for (auto &Obj : LoadedObjects)
99 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +0000100 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +0000101
Lang Hames173c69f2014-01-08 04:09:09 +0000102 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000103}
104
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000105void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000106 MutexGuard locked(lock);
Lang Hames717eacf2016-06-11 05:47:04 +0000107
108 if (M->getDataLayout().isDefault())
109 M->setDataLayout(getDataLayout());
110
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000111 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +0000112}
113
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000114bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000115 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000116 return OwnedModules.removeModule(M);
117}
118
David Blaikie7a1e7752014-04-29 21:52:46 +0000119void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000120 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
121 if (Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000122 report_fatal_error(Dyld.getErrorString());
123
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000124 NotifyObjectEmitted(*Obj, *L);
David Blaikie168861a2014-09-04 18:37:31 +0000125
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000126 LoadedObjects.push_back(std::move(Obj));
Lang Hames173c69f2014-01-08 04:09:09 +0000127}
128
Rafael Espindola7271c192014-08-26 21:04:04 +0000129void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000130 std::unique_ptr<object::ObjectFile> ObjFile;
131 std::unique_ptr<MemoryBuffer> MemBuf;
132 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
133 addObjectFile(std::move(ObjFile));
134 Buffers.push_back(std::move(MemBuf));
Rafael Espindola7271c192014-08-26 21:04:04 +0000135}
136
Rafael Espindola48af1c22014-08-19 18:44:46 +0000137void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000138 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000139}
140
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000141void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000142 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000143 ObjCache = NewCache;
144}
145
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000146std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000147 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000148
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000149 // This must be a module which has already been added but not loaded to this
150 // MCJIT instance, since these conditions are tested by our caller,
151 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000152
Chandler Carruth30d69c22015-02-13 10:01:29 +0000153 legacy::PassManager PM;
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000154
Andrew Kayloradc70562012-10-02 21:18:39 +0000155 // The RuntimeDyld will take ownership of this shortly
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000156 SmallVector<char, 4096> ObjBufferSV;
157 raw_svector_ostream ObjStream(ObjBufferSV);
Andrew Kayloradc70562012-10-02 21:18:39 +0000158
Jim Grosbach7b162492011-03-18 22:48:41 +0000159 // Turn the machine code intermediate representation into bytes in memory
160 // that may be executed.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000161 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
Jim Grosbach7b162492011-03-18 22:48:41 +0000162 report_fatal_error("Target does not support MC emission!");
Jim Grosbach7b162492011-03-18 22:48:41 +0000163
164 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000165 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000166 // Flush the output buffer to get the generated code into memory
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000167
168 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
169 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000170
171 // If we have an object cache, tell it about the new object.
172 // Note that we're using the compiled image, not the loaded image (as below).
173 if (ObjCache) {
174 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
175 // to create a temporary object here and delete it after the call.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000176 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
Rafael Espindola48af1c22014-08-19 18:44:46 +0000177 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000178 }
179
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000180 return CompiledObjBuffer;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000181}
182
Andrew Kaylorea395922013-10-01 01:47:35 +0000183void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000184 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000185 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000186
Andrew Kaylorea395922013-10-01 01:47:35 +0000187 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000188 assert(OwnedModules.ownsModule(M) &&
189 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000190
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000191 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000192 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000193 return;
194
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000195 std::unique_ptr<MemoryBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000196 // Try to load the pre-compiled object from cache if possible
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000197 if (ObjCache)
198 ObjectToLoad = ObjCache->getObject(M);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000199
Lang Hames717eacf2016-06-11 05:47:04 +0000200 assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
Rafael Espindola6763f5a2015-06-23 14:42:34 +0000201
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000202 // If the cache did not contain a suitable object, compile the object
203 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000204 ObjectToLoad = emitObject(M);
205 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000206 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000207
208 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000209 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000210 Expected<std::unique_ptr<object::ObjectFile>> LoadedObject =
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000211 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000212 if (!LoadedObject) {
213 std::string Buf;
214 raw_string_ostream OS(Buf);
215 logAllUnhandledErrors(LoadedObject.takeError(), OS, "");
216 OS.flush();
217 report_fatal_error(Buf);
218 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000219 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
220 Dyld.loadObject(*LoadedObject.get());
221
222 if (Dyld.hasError())
Jim Grosbachc114d892011-03-23 19:51:34 +0000223 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000224
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000225 NotifyObjectEmitted(*LoadedObject.get(), *L);
Andrew Kayloradc70562012-10-02 21:18:39 +0000226
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000227 Buffers.push_back(std::move(ObjectToLoad));
228 LoadedObjects.push_back(std::move(*LoadedObject));
David Blaikieed9709d2014-09-03 19:48:09 +0000229
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000230 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000231}
232
Andrew Kaylorea395922013-10-01 01:47:35 +0000233void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000234 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000235
Andrew Kaylorea395922013-10-01 01:47:35 +0000236 // Resolve any outstanding relocations.
237 Dyld.resolveRelocations();
238
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000239 OwnedModules.markAllLoadedModulesAsFinalized();
240
Andrew Kaylorea395922013-10-01 01:47:35 +0000241 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000242 Dyld.registerEHFrames();
243
Andrew Kaylorea395922013-10-01 01:47:35 +0000244 // Set page permissions.
Lang Hames633fe142015-03-30 03:37:06 +0000245 MemMgr->finalizeMemory();
Andrew Kaylorea395922013-10-01 01:47:35 +0000246}
247
248// FIXME: Rename this.
249void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000250 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000251
Lang Hames018452e2014-09-05 23:38:35 +0000252 // Generate code for module is going to move objects out of the 'added' list,
253 // so we need to copy that out before using it:
254 SmallVector<Module*, 16> ModsToAdd;
255 for (auto M : OwnedModules.added())
256 ModsToAdd.push_back(M);
257
258 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000259 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000260
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000261 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000262}
263
264void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000265 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000266
Andrew Kaylorea395922013-10-01 01:47:35 +0000267 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000268 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000269
270 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000271 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000272 generateCodeForModule(M);
273
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000274 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000275}
276
Lang Hamesad4a9112016-08-01 20:49:11 +0000277JITSymbol MCJIT::findExistingSymbol(const std::string &Name) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000278 if (void *Addr = getPointerToGlobalIfAvailable(Name))
Lang Hamesad4a9112016-08-01 20:49:11 +0000279 return JITSymbol(static_cast<uint64_t>(
280 reinterpret_cast<uintptr_t>(Addr)),
281 JITSymbolFlags::Exported);
Lang Hames3393cfd2015-07-29 23:12:33 +0000282
Lang Hames8d4be3a2016-09-12 17:19:24 +0000283 return Dyld.getSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000284}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000285
Andrew Kaylorea395922013-10-01 01:47:35 +0000286Module *MCJIT::findModuleForSymbol(const std::string &Name,
287 bool CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000288 StringRef DemangledName = Name;
289 if (DemangledName[0] == getDataLayout().getGlobalPrefix())
290 DemangledName = DemangledName.substr(1);
291
Zachary Turnerc04b8922014-06-20 21:07:14 +0000292 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000293
Andrew Kaylorea395922013-10-01 01:47:35 +0000294 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000295 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
296 E = OwnedModules.end_added();
297 I != E; ++I) {
298 Module *M = *I;
Lang Hames8d4be3a2016-09-12 17:19:24 +0000299 Function *F = M->getFunction(DemangledName);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000300 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000301 return M;
302 if (!CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000303 GlobalVariable *G = M->getGlobalVariable(DemangledName);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000304 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000305 return M;
306 // FIXME: Do we need to worry about global aliases?
307 }
308 }
309 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000310 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000311}
312
313uint64_t MCJIT::getSymbolAddress(const std::string &Name,
Lang Hames633fe142015-03-30 03:37:06 +0000314 bool CheckFunctionsOnly) {
Lang Hames8d4be3a2016-09-12 17:19:24 +0000315 std::string MangledName;
316 {
317 raw_string_ostream MangledNameStream(MangledName);
318 Mangler::getNameWithPrefix(MangledNameStream, Name, getDataLayout());
319 }
320 return findSymbol(MangledName, CheckFunctionsOnly).getAddress();
Lang Hames633fe142015-03-30 03:37:06 +0000321}
322
Lang Hamesad4a9112016-08-01 20:49:11 +0000323JITSymbol MCJIT::findSymbol(const std::string &Name,
324 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000325 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000326
Andrew Kaylorea395922013-10-01 01:47:35 +0000327 // First, check to see if we already have this symbol.
Lang Hames633fe142015-03-30 03:37:06 +0000328 if (auto Sym = findExistingSymbol(Name))
329 return Sym;
Andrew Kaylorea395922013-10-01 01:47:35 +0000330
Rafael Espindola48af1c22014-08-19 18:44:46 +0000331 for (object::OwningBinary<object::Archive> &OB : Archives) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000332 object::Archive *A = OB.getBinary();
Lang Hames173c69f2014-01-08 04:09:09 +0000333 // Look for our symbols in each Archive
Lang Hames69f49022016-07-14 20:44:27 +0000334 auto OptionalChildOrErr = A->findSym(Name);
335 if (!OptionalChildOrErr)
336 report_fatal_error(OptionalChildOrErr.takeError());
337 auto &OptionalChild = *OptionalChildOrErr;
338 if (OptionalChild) {
Lang Hames173c69f2014-01-08 04:09:09 +0000339 // FIXME: Support nested archives?
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000340 Expected<std::unique_ptr<object::Binary>> ChildBinOrErr =
Lang Hames69f49022016-07-14 20:44:27 +0000341 OptionalChild->getAsBinary();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000342 if (!ChildBinOrErr) {
343 // TODO: Actually report errors helpfully.
344 consumeError(ChildBinOrErr.takeError());
Rafael Espindolaae460022014-06-16 16:08:36 +0000345 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000346 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000347 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000348 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000349 std::unique_ptr<object::ObjectFile> OF(
350 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000351 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000352 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000353 // The address should be here now.
Lang Hames633fe142015-03-30 03:37:06 +0000354 if (auto Sym = findExistingSymbol(Name))
355 return Sym;
Lang Hames173c69f2014-01-08 04:09:09 +0000356 }
357 }
358 }
359
Andrew Kaylorea395922013-10-01 01:47:35 +0000360 // If it hasn't already been generated, see if it's in one of our modules.
361 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000362 if (M) {
363 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000364
Lang Hamesea800ca2014-08-14 02:38:20 +0000365 // Check the RuntimeDyld table again, it should be there now.
Lang Hames633fe142015-03-30 03:37:06 +0000366 return findExistingSymbol(Name);
Lang Hamesea800ca2014-08-14 02:38:20 +0000367 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000368
Lang Hamesea800ca2014-08-14 02:38:20 +0000369 // If a LazyFunctionCreator is installed, use it to get/create the function.
370 // FIXME: Should we instead have a LazySymbolCreator callback?
Lang Hames633fe142015-03-30 03:37:06 +0000371 if (LazyFunctionCreator) {
372 auto Addr = static_cast<uint64_t>(
373 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
Lang Hamesad4a9112016-08-01 20:49:11 +0000374 return JITSymbol(Addr, JITSymbolFlags::Exported);
Lang Hames633fe142015-03-30 03:37:06 +0000375 }
Lang Hamesea800ca2014-08-14 02:38:20 +0000376
Lang Hames633fe142015-03-30 03:37:06 +0000377 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000378}
379
380uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000381 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000382 uint64_t Result = getSymbolAddress(Name, false);
383 if (Result != 0)
384 finalizeLoadedModules();
385 return Result;
386}
387
388uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000389 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000390 uint64_t Result = getSymbolAddress(Name, true);
391 if (Result != 0)
392 finalizeLoadedModules();
393 return Result;
394}
395
396// Deprecated. Use getFunctionAddress instead.
397void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000398 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000399
Rafael Espindolac233f742015-06-23 13:59:29 +0000400 Mangler Mang;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000401 SmallString<128> Name;
402 TM->getNameWithPrefix(Name, F, Mang);
403
Jim Grosbachd5274402011-03-22 18:05:27 +0000404 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
405 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000406 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000407 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000408 return Addr;
409 }
410
Andrew Kaylorea395922013-10-01 01:47:35 +0000411 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000412 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000413
414 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000415 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000416 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000417 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000418 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000419 // FIXME: Asking for the pointer to a function that hasn't been registered,
420 // and isn't a declaration (which is handled above) should probably
421 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000422 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000423 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000424
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000425 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000426 //
427 // This is the accessor for the target address, so make sure to check the
428 // load address of the symbol, not the local address.
Lang Hamesb1186032015-03-11 00:43:26 +0000429 return (void*)Dyld.getSymbol(Name).getAddress();
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000430}
431
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000432void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
433 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
434 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000435 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000436 }
437}
438
439void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
440 // Execute global ctors/dtors for each module in the program.
441 runStaticConstructorsDestructorsInModulePtrSet(
442 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
443 runStaticConstructorsDestructorsInModulePtrSet(
444 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
445 runStaticConstructorsDestructorsInModulePtrSet(
446 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
447}
448
449Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
450 ModulePtrSet::iterator I,
451 ModulePtrSet::iterator E) {
452 for (; I != E; ++I) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000453 Function *F = (*I)->getFunction(FnName);
454 if (F && !F->isDeclaration())
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000455 return F;
456 }
Craig Topper353eda42014-04-24 06:44:33 +0000457 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000458}
459
Keno Fischer73378eb2015-06-20 00:55:58 +0000460GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
461 bool AllowInternal,
462 ModulePtrSet::iterator I,
463 ModulePtrSet::iterator E) {
464 for (; I != E; ++I) {
465 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
466 if (GV && !GV->isDeclaration())
467 return GV;
468 }
469 return nullptr;
470}
471
472
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000473Function *MCJIT::FindFunctionNamed(const char *FnName) {
474 Function *F = FindFunctionNamedInModulePtrSet(
475 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
476 if (!F)
477 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
478 OwnedModules.end_loaded());
479 if (!F)
480 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
481 OwnedModules.end_finalized());
482 return F;
483}
484
Keno Fischer73378eb2015-06-20 00:55:58 +0000485GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
486 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
487 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
488 if (!GV)
489 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
490 OwnedModules.end_loaded());
491 if (!GV)
492 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
493 OwnedModules.end_finalized());
494 return GV;
495}
496
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000497GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000498 assert(F && "Function *F was null at entry to run()");
499
Jim Grosbach7b162492011-03-18 22:48:41 +0000500 void *FPtr = getPointerToFunction(F);
Lang Hames717eacf2016-06-11 05:47:04 +0000501 finalizeModule(F->getParent());
Jim Grosbachd5274402011-03-22 18:05:27 +0000502 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000503 FunctionType *FTy = F->getFunctionType();
504 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000505
506 assert((FTy->getNumParams() == ArgValues.size() ||
507 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
508 "Wrong number of arguments passed into function!");
509 assert(FTy->getNumParams() == ArgValues.size() &&
510 "This doesn't support passing arguments through varargs (yet)!");
511
512 // Handle some common cases first. These cases correspond to common `main'
513 // prototypes.
514 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
515 switch (ArgValues.size()) {
516 case 3:
517 if (FTy->getParamType(0)->isIntegerTy(32) &&
518 FTy->getParamType(1)->isPointerTy() &&
519 FTy->getParamType(2)->isPointerTy()) {
520 int (*PF)(int, char **, const char **) =
521 (int(*)(int, char **, const char **))(intptr_t)FPtr;
522
523 // Call the function.
524 GenericValue rv;
525 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
526 (char **)GVTOP(ArgValues[1]),
527 (const char **)GVTOP(ArgValues[2])));
528 return rv;
529 }
530 break;
531 case 2:
532 if (FTy->getParamType(0)->isIntegerTy(32) &&
533 FTy->getParamType(1)->isPointerTy()) {
534 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
535
536 // Call the function.
537 GenericValue rv;
538 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
539 (char **)GVTOP(ArgValues[1])));
540 return rv;
541 }
542 break;
543 case 1:
544 if (FTy->getNumParams() == 1 &&
545 FTy->getParamType(0)->isIntegerTy(32)) {
546 GenericValue rv;
547 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
548 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
549 return rv;
550 }
551 break;
552 }
553 }
554
555 // Handle cases where no arguments are passed first.
556 if (ArgValues.empty()) {
557 GenericValue rv;
558 switch (RetTy->getTypeID()) {
559 default: llvm_unreachable("Unknown return type for function call!");
560 case Type::IntegerTyID: {
561 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
562 if (BitWidth == 1)
563 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
564 else if (BitWidth <= 8)
565 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
566 else if (BitWidth <= 16)
567 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
568 else if (BitWidth <= 32)
569 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
570 else if (BitWidth <= 64)
571 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
572 else
573 llvm_unreachable("Integer types > 64 bits not supported");
574 return rv;
575 }
576 case Type::VoidTyID:
577 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
578 return rv;
579 case Type::FloatTyID:
580 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
581 return rv;
582 case Type::DoubleTyID:
583 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
584 return rv;
585 case Type::X86_FP80TyID:
586 case Type::FP128TyID:
587 case Type::PPC_FP128TyID:
588 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000589 case Type::PointerTyID:
590 return PTOGV(((void*(*)())(intptr_t)FPtr)());
591 }
592 }
593
Lang Hames30526072016-08-11 15:56:23 +0000594 report_fatal_error("MCJIT::runFunction does not support full-featured "
595 "argument passing. Please use "
596 "ExecutionEngine::getFunctionAddress and cast the result "
597 "to the desired function pointer type.");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000598}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000599
Lang Hames9a783342014-09-15 17:50:22 +0000600void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000601 if (!isSymbolSearchingDisabled()) {
Lang Hames633fe142015-03-30 03:37:06 +0000602 void *ptr =
603 reinterpret_cast<void*>(
604 static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
Danil Malyshevbfee5422012-03-28 21:46:36 +0000605 if (ptr)
606 return ptr;
607 }
608
609 /// If a LazyFunctionCreator is installed, use it to get/create the function.
610 if (LazyFunctionCreator)
611 if (void *RP = LazyFunctionCreator(Name))
612 return RP;
613
614 if (AbortOnFailure) {
615 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000616 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000617 }
Craig Topper353eda42014-04-24 06:44:33 +0000618 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000619}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000620
621void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000622 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000623 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000624 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000625 EventListeners.push_back(L);
626}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000627
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000628void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000629 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000630 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000631 MutexGuard locked(lock);
David Majnemer42531262016-08-12 03:55:06 +0000632 auto I = find(reverse(EventListeners), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000633 if (I != EventListeners.rend()) {
634 std::swap(*I, EventListeners.back());
635 EventListeners.pop_back();
636 }
637}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000638
639void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
640 const RuntimeDyld::LoadedObjectInfo &L) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000641 MutexGuard locked(lock);
Lang Hames633fe142015-03-30 03:37:06 +0000642 MemMgr->notifyObjectLoaded(this, Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000643 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000644 EventListeners[I]->NotifyObjectEmitted(Obj, L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000645 }
646}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000647
648void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000649 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000650 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000651 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000652}
Andrew Kaylorea395922013-10-01 01:47:35 +0000653
Lang Hamesad4a9112016-08-01 20:49:11 +0000654JITSymbol
Lang Hames633fe142015-03-30 03:37:06 +0000655LinkingSymbolResolver::findSymbol(const std::string &Name) {
656 auto Result = ParentEngine.findSymbol(Name, false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000657 if (Result)
658 return Result;
Lang Hames633fe142015-03-30 03:37:06 +0000659 if (ParentEngine.isSymbolSearchingDisabled())
660 return nullptr;
661 return ClientResolver->findSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000662}