blob: 225188b3a89c6f0708602206247f7a361e0f01c4 [file] [log] [blame]
Eric Christopher5c896f72011-04-22 03:07:06 +00001//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "MCJIT.h"
Lang Hames633fe142015-03-30 03:37:06 +000011#include "llvm/ADT/STLExtras.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000012#include "llvm/ExecutionEngine/GenericValue.h"
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +000013#include "llvm/ExecutionEngine/JITEventListener.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000014#include "llvm/ExecutionEngine/MCJIT.h"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000015#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
17#include "llvm/IR/DerivedTypes.h"
18#include "llvm/IR/Function.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000019#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000020#include "llvm/IR/Mangler.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000021#include "llvm/IR/Module.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000022#include "llvm/MC/MCAsmInfo.h"
Lang Hames173c69f2014-01-08 04:09:09 +000023#include "llvm/Object/Archive.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000024#include "llvm/Object/ObjectFile.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000025#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000027#include "llvm/Support/MemoryBuffer.h"
Zachary Turnerc04b8922014-06-20 21:07:14 +000028#include "llvm/Support/MutexGuard.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000029
30using namespace llvm;
31
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000032void ObjectCache::anchor() {}
33
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000034namespace {
35
36static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
38} JITRegistrator;
39
40}
41
42extern "C" void LLVMLinkInMCJIT() {
43}
44
Lang Hames633fe142015-03-30 03:37:06 +000045ExecutionEngine*
46MCJIT::createJIT(std::unique_ptr<Module> M,
47 std::string *ErrorStr,
48 std::shared_ptr<MCJITMemoryManager> MemMgr,
49 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
50 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000051 // Try to register the program as a source of symbols to resolve against.
52 //
53 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000054 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000055
Lang Hames633fe142015-03-30 03:37:06 +000056 if (!MemMgr || !Resolver) {
57 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
58 if (!MemMgr)
59 MemMgr = RTDyldMM;
60 if (!Resolver)
61 Resolver = RTDyldMM;
62 }
Lang Hames4a5697e2014-12-03 00:51:19 +000063
Lang Hames633fe142015-03-30 03:37:06 +000064 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
65 std::move(Resolver));
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000066}
67
David Blaikie196e3232014-09-02 22:41:07 +000068MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
Lang Hames633fe142015-03-30 03:37:06 +000069 std::shared_ptr<MCJITMemoryManager> MemMgr,
70 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver)
David Blaikie196e3232014-09-02 22:41:07 +000071 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
Lang Hames633fe142015-03-30 03:37:06 +000072 MemMgr(std::move(MemMgr)), Resolver(*this, std::move(Resolver)),
73 Dyld(*this->MemMgr, this->Resolver), ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000074 // FIXME: We are managing our modules, so we do not want the base class
75 // ExecutionEngine to manage them as well. To avoid double destruction
76 // of the first (and only) module added in ExecutionEngine constructor
77 // we remove it from EE and will destruct it ourselves.
78 //
79 // It may make sense to move our module manager (based on SmallStPtr) back
80 // into EE if the JIT and Interpreter can live with it.
81 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
82 // runStaticConstructorsDestructors could be moved back to EE as well.
83 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000084 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000085 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000086
87 OwnedModules.addModule(std::move(First));
Eric Christopher8b770652015-01-26 19:03:15 +000088 setDataLayout(TM->getDataLayout());
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000089 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
Rafael Espindola2a8a2792014-08-19 04:04:25 +000090}
91
92MCJIT::~MCJIT() {
93 MutexGuard locked(lock);
94
Andrew Kaylorc442a762013-10-16 00:14:21 +000095 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000096
David Blaikieed9709d2014-09-03 19:48:09 +000097 for (auto &Obj : LoadedObjects)
98 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +000099 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +0000100
Lang Hames173c69f2014-01-08 04:09:09 +0000101 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000102}
103
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000104void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000105 MutexGuard locked(lock);
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000106 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +0000107}
108
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000109bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000110 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000111 return OwnedModules.removeModule(M);
112}
113
David Blaikie7a1e7752014-04-29 21:52:46 +0000114void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000115 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
116 if (Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000117 report_fatal_error(Dyld.getErrorString());
118
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000119 NotifyObjectEmitted(*Obj, *L);
David Blaikie168861a2014-09-04 18:37:31 +0000120
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000121 LoadedObjects.push_back(std::move(Obj));
Lang Hames173c69f2014-01-08 04:09:09 +0000122}
123
Rafael Espindola7271c192014-08-26 21:04:04 +0000124void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000125 std::unique_ptr<object::ObjectFile> ObjFile;
126 std::unique_ptr<MemoryBuffer> MemBuf;
127 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
128 addObjectFile(std::move(ObjFile));
129 Buffers.push_back(std::move(MemBuf));
Rafael Espindola7271c192014-08-26 21:04:04 +0000130}
131
Rafael Espindola48af1c22014-08-19 18:44:46 +0000132void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000133 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000134}
135
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000136void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000137 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000138 ObjCache = NewCache;
139}
140
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000141std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000142 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000143
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000144 // This must be a module which has already been added but not loaded to this
145 // MCJIT instance, since these conditions are tested by our caller,
146 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000147
Chandler Carruth30d69c22015-02-13 10:01:29 +0000148 legacy::PassManager PM;
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000149
Mehdi Amini46a43552015-03-04 18:43:29 +0000150 M->setDataLayout(*TM->getDataLayout());
Jim Grosbach7b162492011-03-18 22:48:41 +0000151
Andrew Kayloradc70562012-10-02 21:18:39 +0000152 // The RuntimeDyld will take ownership of this shortly
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000153 SmallVector<char, 4096> ObjBufferSV;
154 raw_svector_ostream ObjStream(ObjBufferSV);
Andrew Kayloradc70562012-10-02 21:18:39 +0000155
Jim Grosbach7b162492011-03-18 22:48:41 +0000156 // Turn the machine code intermediate representation into bytes in memory
157 // that may be executed.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000158 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
Jim Grosbach7b162492011-03-18 22:48:41 +0000159 report_fatal_error("Target does not support MC emission!");
Jim Grosbach7b162492011-03-18 22:48:41 +0000160
161 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000162 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000163 // Flush the output buffer to get the generated code into memory
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000164 ObjStream.flush();
165
166 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
167 new ObjectMemoryBuffer(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
198 // If the cache did not contain a suitable object, compile the object
199 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000200 ObjectToLoad = emitObject(M);
201 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000202 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000203
204 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000205 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000206 ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
207 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
208 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
209 Dyld.loadObject(*LoadedObject.get());
210
211 if (Dyld.hasError())
Jim Grosbachc114d892011-03-23 19:51:34 +0000212 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000213
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000214 NotifyObjectEmitted(*LoadedObject.get(), *L);
Andrew Kayloradc70562012-10-02 21:18:39 +0000215
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000216 Buffers.push_back(std::move(ObjectToLoad));
217 LoadedObjects.push_back(std::move(*LoadedObject));
David Blaikieed9709d2014-09-03 19:48:09 +0000218
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000219 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000220}
221
Andrew Kaylorea395922013-10-01 01:47:35 +0000222void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000223 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000224
Andrew Kaylorea395922013-10-01 01:47:35 +0000225 // Resolve any outstanding relocations.
226 Dyld.resolveRelocations();
227
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000228 OwnedModules.markAllLoadedModulesAsFinalized();
229
Andrew Kaylorea395922013-10-01 01:47:35 +0000230 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000231 Dyld.registerEHFrames();
232
Andrew Kaylorea395922013-10-01 01:47:35 +0000233 // Set page permissions.
Lang Hames633fe142015-03-30 03:37:06 +0000234 MemMgr->finalizeMemory();
Andrew Kaylorea395922013-10-01 01:47:35 +0000235}
236
237// FIXME: Rename this.
238void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000239 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000240
Lang Hames018452e2014-09-05 23:38:35 +0000241 // Generate code for module is going to move objects out of the 'added' list,
242 // so we need to copy that out before using it:
243 SmallVector<Module*, 16> ModsToAdd;
244 for (auto M : OwnedModules.added())
245 ModsToAdd.push_back(M);
246
247 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000248 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000249
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000250 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000251}
252
253void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000254 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000255
Andrew Kaylorea395922013-10-01 01:47:35 +0000256 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000257 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000258
259 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000260 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000261 generateCodeForModule(M);
262
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000263 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000264}
265
Lang Hames633fe142015-03-30 03:37:06 +0000266RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000267 SmallString<128> FullName;
Rafael Espindolac233f742015-06-23 13:59:29 +0000268 Mangler::getNameWithPrefix(FullName, Name, *TM->getDataLayout());
Lang Hames633fe142015-03-30 03:37:06 +0000269 return Dyld.getSymbol(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000270}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000271
Andrew Kaylorea395922013-10-01 01:47:35 +0000272Module *MCJIT::findModuleForSymbol(const std::string &Name,
273 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000274 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000275
Andrew Kaylorea395922013-10-01 01:47:35 +0000276 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000277 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
278 E = OwnedModules.end_added();
279 I != E; ++I) {
280 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000281 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000282 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000283 return M;
284 if (!CheckFunctionsOnly) {
285 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000286 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000287 return M;
288 // FIXME: Do we need to worry about global aliases?
289 }
290 }
291 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000292 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000293}
294
295uint64_t MCJIT::getSymbolAddress(const std::string &Name,
Lang Hames633fe142015-03-30 03:37:06 +0000296 bool CheckFunctionsOnly) {
297 return findSymbol(Name, CheckFunctionsOnly).getAddress();
298}
299
300RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
301 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000302 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000303
Andrew Kaylorea395922013-10-01 01:47:35 +0000304 // First, check to see if we already have this symbol.
Lang Hames633fe142015-03-30 03:37:06 +0000305 if (auto Sym = findExistingSymbol(Name))
306 return Sym;
Andrew Kaylorea395922013-10-01 01:47:35 +0000307
Rafael Espindola48af1c22014-08-19 18:44:46 +0000308 for (object::OwningBinary<object::Archive> &OB : Archives) {
Lang Hamesf04de6e2014-10-31 21:37:49 +0000309 object::Archive *A = OB.getBinary();
Lang Hames173c69f2014-01-08 04:09:09 +0000310 // Look for our symbols in each Archive
311 object::Archive::child_iterator ChildIt = A->findSym(Name);
Rafael Espindola23a97502014-01-21 16:09:45 +0000312 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000313 // FIXME: Support nested archives?
Rafael Espindolaae460022014-06-16 16:08:36 +0000314 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
315 ChildIt->getAsBinary();
316 if (ChildBinOrErr.getError())
317 continue;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000318 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000319 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000320 std::unique_ptr<object::ObjectFile> OF(
321 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000322 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000323 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000324 // The address should be here now.
Lang Hames633fe142015-03-30 03:37:06 +0000325 if (auto Sym = findExistingSymbol(Name))
326 return Sym;
Lang Hames173c69f2014-01-08 04:09:09 +0000327 }
328 }
329 }
330
Andrew Kaylorea395922013-10-01 01:47:35 +0000331 // If it hasn't already been generated, see if it's in one of our modules.
332 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000333 if (M) {
334 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000335
Lang Hamesea800ca2014-08-14 02:38:20 +0000336 // Check the RuntimeDyld table again, it should be there now.
Lang Hames633fe142015-03-30 03:37:06 +0000337 return findExistingSymbol(Name);
Lang Hamesea800ca2014-08-14 02:38:20 +0000338 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000339
Lang Hamesea800ca2014-08-14 02:38:20 +0000340 // If a LazyFunctionCreator is installed, use it to get/create the function.
341 // FIXME: Should we instead have a LazySymbolCreator callback?
Lang Hames633fe142015-03-30 03:37:06 +0000342 if (LazyFunctionCreator) {
343 auto Addr = static_cast<uint64_t>(
344 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
345 return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
346 }
Lang Hamesea800ca2014-08-14 02:38:20 +0000347
Lang Hames633fe142015-03-30 03:37:06 +0000348 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000349}
350
351uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000352 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000353 uint64_t Result = getSymbolAddress(Name, false);
354 if (Result != 0)
355 finalizeLoadedModules();
356 return Result;
357}
358
359uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000360 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000361 uint64_t Result = getSymbolAddress(Name, true);
362 if (Result != 0)
363 finalizeLoadedModules();
364 return Result;
365}
366
367// Deprecated. Use getFunctionAddress instead.
368void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000369 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000370
Rafael Espindolac233f742015-06-23 13:59:29 +0000371 Mangler Mang;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000372 SmallString<128> Name;
373 TM->getNameWithPrefix(Name, F, Mang);
374
Jim Grosbachd5274402011-03-22 18:05:27 +0000375 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
376 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000377 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Lang Hamesefe7e222014-10-22 23:18:42 +0000378 updateGlobalMapping(F, Addr);
Jim Grosbachd5274402011-03-22 18:05:27 +0000379 return Addr;
380 }
381
Andrew Kaylorea395922013-10-01 01:47:35 +0000382 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000383 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000384
385 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000386 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000387 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000388 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000389 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000390 // FIXME: Asking for the pointer to a function that hasn't been registered,
391 // and isn't a declaration (which is handled above) should probably
392 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000393 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000394 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000395
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000396 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000397 //
398 // This is the accessor for the target address, so make sure to check the
399 // load address of the symbol, not the local address.
Lang Hamesb1186032015-03-11 00:43:26 +0000400 return (void*)Dyld.getSymbol(Name).getAddress();
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000401}
402
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000403void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
404 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
405 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000406 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000407 }
408}
409
410void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
411 // Execute global ctors/dtors for each module in the program.
412 runStaticConstructorsDestructorsInModulePtrSet(
413 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
414 runStaticConstructorsDestructorsInModulePtrSet(
415 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
416 runStaticConstructorsDestructorsInModulePtrSet(
417 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
418}
419
420Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
421 ModulePtrSet::iterator I,
422 ModulePtrSet::iterator E) {
423 for (; I != E; ++I) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000424 Function *F = (*I)->getFunction(FnName);
425 if (F && !F->isDeclaration())
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000426 return F;
427 }
Craig Topper353eda42014-04-24 06:44:33 +0000428 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000429}
430
Keno Fischer73378eb2015-06-20 00:55:58 +0000431GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
432 bool AllowInternal,
433 ModulePtrSet::iterator I,
434 ModulePtrSet::iterator E) {
435 for (; I != E; ++I) {
436 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
437 if (GV && !GV->isDeclaration())
438 return GV;
439 }
440 return nullptr;
441}
442
443
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000444Function *MCJIT::FindFunctionNamed(const char *FnName) {
445 Function *F = FindFunctionNamedInModulePtrSet(
446 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
447 if (!F)
448 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
449 OwnedModules.end_loaded());
450 if (!F)
451 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
452 OwnedModules.end_finalized());
453 return F;
454}
455
Keno Fischer73378eb2015-06-20 00:55:58 +0000456GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
457 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
458 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
459 if (!GV)
460 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
461 OwnedModules.end_loaded());
462 if (!GV)
463 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
464 OwnedModules.end_finalized());
465 return GV;
466}
467
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000468GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000469 assert(F && "Function *F was null at entry to run()");
470
Jim Grosbach7b162492011-03-18 22:48:41 +0000471 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000472 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000473 FunctionType *FTy = F->getFunctionType();
474 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000475
476 assert((FTy->getNumParams() == ArgValues.size() ||
477 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
478 "Wrong number of arguments passed into function!");
479 assert(FTy->getNumParams() == ArgValues.size() &&
480 "This doesn't support passing arguments through varargs (yet)!");
481
482 // Handle some common cases first. These cases correspond to common `main'
483 // prototypes.
484 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
485 switch (ArgValues.size()) {
486 case 3:
487 if (FTy->getParamType(0)->isIntegerTy(32) &&
488 FTy->getParamType(1)->isPointerTy() &&
489 FTy->getParamType(2)->isPointerTy()) {
490 int (*PF)(int, char **, const char **) =
491 (int(*)(int, char **, const char **))(intptr_t)FPtr;
492
493 // Call the function.
494 GenericValue rv;
495 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
496 (char **)GVTOP(ArgValues[1]),
497 (const char **)GVTOP(ArgValues[2])));
498 return rv;
499 }
500 break;
501 case 2:
502 if (FTy->getParamType(0)->isIntegerTy(32) &&
503 FTy->getParamType(1)->isPointerTy()) {
504 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
505
506 // Call the function.
507 GenericValue rv;
508 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
509 (char **)GVTOP(ArgValues[1])));
510 return rv;
511 }
512 break;
513 case 1:
514 if (FTy->getNumParams() == 1 &&
515 FTy->getParamType(0)->isIntegerTy(32)) {
516 GenericValue rv;
517 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
518 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
519 return rv;
520 }
521 break;
522 }
523 }
524
525 // Handle cases where no arguments are passed first.
526 if (ArgValues.empty()) {
527 GenericValue rv;
528 switch (RetTy->getTypeID()) {
529 default: llvm_unreachable("Unknown return type for function call!");
530 case Type::IntegerTyID: {
531 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
532 if (BitWidth == 1)
533 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
534 else if (BitWidth <= 8)
535 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
536 else if (BitWidth <= 16)
537 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
538 else if (BitWidth <= 32)
539 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
540 else if (BitWidth <= 64)
541 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
542 else
543 llvm_unreachable("Integer types > 64 bits not supported");
544 return rv;
545 }
546 case Type::VoidTyID:
547 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
548 return rv;
549 case Type::FloatTyID:
550 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
551 return rv;
552 case Type::DoubleTyID:
553 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
554 return rv;
555 case Type::X86_FP80TyID:
556 case Type::FP128TyID:
557 case Type::PPC_FP128TyID:
558 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000559 case Type::PointerTyID:
560 return PTOGV(((void*(*)())(intptr_t)FPtr)());
561 }
562 }
563
Craig Toppera2886c22012-02-07 05:05:23 +0000564 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000565}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000566
Lang Hames9a783342014-09-15 17:50:22 +0000567void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000568 if (!isSymbolSearchingDisabled()) {
Lang Hames633fe142015-03-30 03:37:06 +0000569 void *ptr =
570 reinterpret_cast<void*>(
571 static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
Danil Malyshevbfee5422012-03-28 21:46:36 +0000572 if (ptr)
573 return ptr;
574 }
575
576 /// If a LazyFunctionCreator is installed, use it to get/create the function.
577 if (LazyFunctionCreator)
578 if (void *RP = LazyFunctionCreator(Name))
579 return RP;
580
581 if (AbortOnFailure) {
582 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000583 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000584 }
Craig Topper353eda42014-04-24 06:44:33 +0000585 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000586}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000587
588void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000589 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000590 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000591 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000592 EventListeners.push_back(L);
593}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000594
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000595void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000596 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000597 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000598 MutexGuard locked(lock);
Eric Christopher79cc1e32014-09-02 22:28:02 +0000599 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000600 if (I != EventListeners.rend()) {
601 std::swap(*I, EventListeners.back());
602 EventListeners.pop_back();
603 }
604}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000605
606void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
607 const RuntimeDyld::LoadedObjectInfo &L) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000608 MutexGuard locked(lock);
Lang Hames633fe142015-03-30 03:37:06 +0000609 MemMgr->notifyObjectLoaded(this, Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000610 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000611 EventListeners[I]->NotifyObjectEmitted(Obj, L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000612 }
613}
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000614
615void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000616 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000617 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000618 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000619}
Andrew Kaylorea395922013-10-01 01:47:35 +0000620
Lang Hames633fe142015-03-30 03:37:06 +0000621RuntimeDyld::SymbolInfo
622LinkingSymbolResolver::findSymbol(const std::string &Name) {
623 auto Result = ParentEngine.findSymbol(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000624 // If the symbols wasn't found and it begins with an underscore, try again
625 // without the underscore.
626 if (!Result && Name[0] == '_')
Lang Hames633fe142015-03-30 03:37:06 +0000627 Result = ParentEngine.findSymbol(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000628 if (Result)
629 return Result;
Lang Hames633fe142015-03-30 03:37:06 +0000630 if (ParentEngine.isSymbolSearchingDisabled())
631 return nullptr;
632 return ClientResolver->findSymbol(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000633}