blob: efd30ba7580a2ba15ae5f0fe9303ce3de416f85b [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"
11#include "llvm/ExecutionEngine/GenericValue.h"
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +000012#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000013#include "llvm/ExecutionEngine/JITMemoryManager.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000014#include "llvm/ExecutionEngine/MCJIT.h"
15#include "llvm/ExecutionEngine/ObjectBuffer.h"
16#include "llvm/ExecutionEngine/ObjectImage.h"
Andrew Kaylor31be5ef2013-04-29 17:49:40 +000017#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Function.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000021#include "llvm/IR/Mangler.h"
Andrew Kaylorea395922013-10-01 01:47:35 +000022#include "llvm/IR/Module.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hames173c69f2014-01-08 04:09:09 +000024#include "llvm/Object/Archive.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000025#include "llvm/PassManager.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000026#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Support/ErrorHandling.h"
Jim Grosbach348a5482011-03-22 01:06:42 +000028#include "llvm/Support/MemoryBuffer.h"
Zachary Turnerc04b8922014-06-20 21:07:14 +000029#include "llvm/Support/MutexGuard.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000030#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000031#include "llvm/Target/TargetSubtargetInfo.h"
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000032
33using namespace llvm;
34
35namespace {
36
37static struct RegisterJIT {
38 RegisterJIT() { MCJIT::Register(); }
39} JITRegistrator;
40
41}
42
43extern "C" void LLVMLinkInMCJIT() {
44}
45
Rafael Espindola2a8a2792014-08-19 04:04:25 +000046ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000047 std::string *ErrorStr,
Filip Pizlo9bc53e82013-05-14 19:29:00 +000048 RTDyldMemoryManager *MemMgr,
David Blaikie196e3232014-09-02 22:41:07 +000049 std::unique_ptr<TargetMachine> TM) {
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000050 // Try to register the program as a source of symbols to resolve against.
51 //
52 // FIXME: Don't do this here.
Craig Topper353eda42014-04-24 06:44:33 +000053 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000054
David Blaikie196e3232014-09-02 22:41:07 +000055 return new MCJIT(std::move(M), std::move(TM),
Rafael Espindola2a8a2792014-08-19 04:04:25 +000056 MemMgr ? MemMgr : new SectionMemoryManager());
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000057}
58
David Blaikie196e3232014-09-02 22:41:07 +000059MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
Rafael Espindola2a8a2792014-08-19 04:04:25 +000060 RTDyldMemoryManager *MM)
David Blaikie196e3232014-09-02 22:41:07 +000061 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
62 MemMgr(this, MM), Dyld(&MemMgr), ObjCache(nullptr) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +000063 // FIXME: We are managing our modules, so we do not want the base class
64 // ExecutionEngine to manage them as well. To avoid double destruction
65 // of the first (and only) module added in ExecutionEngine constructor
66 // we remove it from EE and will destruct it ourselves.
67 //
68 // It may make sense to move our module manager (based on SmallStPtr) back
69 // into EE if the JIT and Interpreter can live with it.
70 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
71 // runStaticConstructorsDestructors could be moved back to EE as well.
72 //
Rafael Espindola2a8a2792014-08-19 04:04:25 +000073 std::unique_ptr<Module> First = std::move(Modules[0]);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000074 Modules.clear();
Rafael Espindola2a8a2792014-08-19 04:04:25 +000075
76 OwnedModules.addModule(std::move(First));
77 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
78}
79
80MCJIT::~MCJIT() {
81 MutexGuard locked(lock);
82
Andrew Kaylorc442a762013-10-16 00:14:21 +000083 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000084
David Blaikieed9709d2014-09-03 19:48:09 +000085 for (auto &Obj : LoadedObjects)
86 if (Obj)
Chandler Carruthd55d1592013-10-24 09:52:56 +000087 NotifyFreeingObject(*Obj);
Lang Hames173c69f2014-01-08 04:09:09 +000088
Lang Hames173c69f2014-01-08 04:09:09 +000089 Archives.clear();
Andrew Kaylor1a568c32012-08-07 18:33:00 +000090}
91
Rafael Espindola2a8a2792014-08-19 04:04:25 +000092void MCJIT::addModule(std::unique_ptr<Module> M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000093 MutexGuard locked(lock);
Rafael Espindola2a8a2792014-08-19 04:04:25 +000094 OwnedModules.addModule(std::move(M));
Andrew Kaylorea395922013-10-01 01:47:35 +000095}
96
Andrew Kaylorc89fc822013-10-24 00:19:14 +000097bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000098 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000099 return OwnedModules.removeModule(M);
100}
101
David Blaikie7a1e7752014-04-29 21:52:46 +0000102void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
David Blaikieed9709d2014-09-03 19:48:09 +0000103 std::unique_ptr<ObjectImage> LoadedObject = Dyld.loadObject(std::move(Obj));
Juergen Ributzka6ff29a72014-03-26 18:19:27 +0000104 if (!LoadedObject || Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000105 report_fatal_error(Dyld.getErrorString());
106
Lang Hames173c69f2014-01-08 04:09:09 +0000107 NotifyObjectEmitted(*LoadedObject);
David Blaikie168861a2014-09-04 18:37:31 +0000108
109 LoadedObjects.push_back(std::move(LoadedObject));
Lang Hames173c69f2014-01-08 04:09:09 +0000110}
111
Rafael Espindola7271c192014-08-26 21:04:04 +0000112void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
113 addObjectFile(std::move(Obj.getBinary()));
114 Buffers.push_back(std::move(Obj.getBuffer()));
115}
116
Rafael Espindola48af1c22014-08-19 18:44:46 +0000117void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolace47a052014-08-01 18:09:32 +0000118 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000119}
120
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000121void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000122 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000123 ObjCache = NewCache;
124}
125
David Blaikied1101572014-09-03 19:57:35 +0000126std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000127 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000128
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000129 // This must be a module which has already been added but not loaded to this
130 // MCJIT instance, since these conditions are tested by our caller,
131 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000132
133 PassManager PM;
134
Eric Christopherd9134482014-08-04 21:25:23 +0000135 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindolac435adc2014-09-10 21:27:43 +0000136 PM.add(new DataLayoutPass());
Jim Grosbach7b162492011-03-18 22:48:41 +0000137
Andrew Kayloradc70562012-10-02 21:18:39 +0000138 // The RuntimeDyld will take ownership of this shortly
Ahmed Charles56440fd2014-03-06 05:51:42 +0000139 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kayloradc70562012-10-02 21:18:39 +0000140
Jim Grosbach7b162492011-03-18 22:48:41 +0000141 // Turn the machine code intermediate representation into bytes in memory
142 // that may be executed.
Lang Hamesbc876012014-04-18 06:48:23 +0000143 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
144 !getVerifyModules())) {
Jim Grosbach7b162492011-03-18 22:48:41 +0000145 report_fatal_error("Target does not support MC emission!");
146 }
147
148 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000149 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000150 // Flush the output buffer to get the generated code into memory
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000151 CompiledObject->flush();
152
153 // If we have an object cache, tell it about the new object.
154 // Note that we're using the compiled image, not the loaded image (as below).
155 if (ObjCache) {
156 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
157 // to create a temporary object here and delete it after the call.
Rafael Espindola48af1c22014-08-19 18:44:46 +0000158 MemoryBufferRef MB = CompiledObject->getMemBuffer();
159 ObjCache->notifyObjectCompiled(M, MB);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000160 }
161
David Blaikied1101572014-09-03 19:57:35 +0000162 return CompiledObject;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000163}
164
Andrew Kaylorea395922013-10-01 01:47:35 +0000165void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000166 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000167 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000168
Andrew Kaylorea395922013-10-01 01:47:35 +0000169 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000170 assert(OwnedModules.ownsModule(M) &&
171 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000172
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000173 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000174 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000175 return;
176
Ahmed Charles56440fd2014-03-06 05:51:42 +0000177 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000178 // Try to load the pre-compiled object from cache if possible
Craig Topper353eda42014-04-24 06:44:33 +0000179 if (ObjCache) {
David Blaikieed9709d2014-09-03 19:48:09 +0000180 if (std::unique_ptr<MemoryBuffer> PreCompiledObject =
181 ObjCache->getObject(M))
182 ObjectToLoad =
183 llvm::make_unique<ObjectBuffer>(std::move(PreCompiledObject));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000184 }
185
186 // If the cache did not contain a suitable object, compile the object
187 if (!ObjectToLoad) {
David Blaikied1101572014-09-03 19:57:35 +0000188 ObjectToLoad = emitObject(M);
189 assert(ObjectToLoad && "Compilation did not produce an object.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000190 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000191
192 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000193 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
David Blaikieed9709d2014-09-03 19:48:09 +0000194 std::unique_ptr<ObjectImage> LoadedObject =
195 Dyld.loadObject(std::move(ObjectToLoad));
Andrew Kayloradc70562012-10-02 21:18:39 +0000196 if (!LoadedObject)
Jim Grosbachc114d892011-03-23 19:51:34 +0000197 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000198
Andrew Kayloradc70562012-10-02 21:18:39 +0000199 // FIXME: Make this optional, maybe even move it to a JIT event listener
200 LoadedObject->registerWithDebugger();
201
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000202 NotifyObjectEmitted(*LoadedObject);
203
David Blaikieed9709d2014-09-03 19:48:09 +0000204 LoadedObjects.push_back(std::move(LoadedObject));
205
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000206 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000207}
208
Andrew Kaylorea395922013-10-01 01:47:35 +0000209void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000210 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000211
Andrew Kaylorea395922013-10-01 01:47:35 +0000212 // Resolve any outstanding relocations.
213 Dyld.resolveRelocations();
214
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000215 OwnedModules.markAllLoadedModulesAsFinalized();
216
Andrew Kaylorea395922013-10-01 01:47:35 +0000217 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000218 Dyld.registerEHFrames();
219
Andrew Kaylorea395922013-10-01 01:47:35 +0000220 // Set page permissions.
221 MemMgr.finalizeMemory();
222}
223
224// FIXME: Rename this.
225void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000226 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000227
Lang Hames018452e2014-09-05 23:38:35 +0000228 // Generate code for module is going to move objects out of the 'added' list,
229 // so we need to copy that out before using it:
230 SmallVector<Module*, 16> ModsToAdd;
231 for (auto M : OwnedModules.added())
232 ModsToAdd.push_back(M);
233
234 for (auto M : ModsToAdd)
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000235 generateCodeForModule(M);
Andrew Kaylora342cb92012-11-15 23:50:01 +0000236
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000237 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000238}
239
240void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000241 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000242
Andrew Kaylorea395922013-10-01 01:47:35 +0000243 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000244 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000245
246 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000247 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000248 generateCodeForModule(M);
249
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000250 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000251}
252
Andrew Kaylorea395922013-10-01 01:47:35 +0000253uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Eric Christopherd9134482014-08-04 21:25:23 +0000254 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000255 SmallString<128> FullName;
256 Mang.getNameWithPrefix(FullName, Name);
257 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000258}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000259
Andrew Kaylorea395922013-10-01 01:47:35 +0000260Module *MCJIT::findModuleForSymbol(const std::string &Name,
261 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000262 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000263
Andrew Kaylorea395922013-10-01 01:47:35 +0000264 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000265 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
266 E = OwnedModules.end_added();
267 I != E; ++I) {
268 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000269 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000270 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000271 return M;
272 if (!CheckFunctionsOnly) {
273 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000274 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000275 return M;
276 // FIXME: Do we need to worry about global aliases?
277 }
278 }
279 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000280 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000281}
282
283uint64_t MCJIT::getSymbolAddress(const std::string &Name,
284 bool CheckFunctionsOnly)
285{
Zachary Turnerc04b8922014-06-20 21:07:14 +0000286 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000287
Andrew Kaylorea395922013-10-01 01:47:35 +0000288 // First, check to see if we already have this symbol.
289 uint64_t Addr = getExistingSymbolAddress(Name);
290 if (Addr)
291 return Addr;
292
Rafael Espindola48af1c22014-08-19 18:44:46 +0000293 for (object::OwningBinary<object::Archive> &OB : Archives) {
294 object::Archive *A = OB.getBinary().get();
Lang Hames173c69f2014-01-08 04:09:09 +0000295 // Look for our symbols in each Archive
296 object::Archive::child_iterator ChildIt = A->findSym(Name);
Rafael Espindola23a97502014-01-21 16:09:45 +0000297 if (ChildIt != A->child_end()) {
Lang Hames173c69f2014-01-08 04:09:09 +0000298 // FIXME: Support nested archives?
Rafael Espindolaae460022014-06-16 16:08:36 +0000299 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
300 ChildIt->getAsBinary();
301 if (ChildBinOrErr.getError())
302 continue;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000303 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
Rafael Espindolaae460022014-06-16 16:08:36 +0000304 if (ChildBin->isObject()) {
David Blaikie7a1e7752014-04-29 21:52:46 +0000305 std::unique_ptr<object::ObjectFile> OF(
306 static_cast<object::ObjectFile *>(ChildBin.release()));
Lang Hames173c69f2014-01-08 04:09:09 +0000307 // This causes the object file to be loaded.
David Blaikie7a1e7752014-04-29 21:52:46 +0000308 addObjectFile(std::move(OF));
Lang Hames173c69f2014-01-08 04:09:09 +0000309 // The address should be here now.
310 Addr = getExistingSymbolAddress(Name);
311 if (Addr)
312 return Addr;
313 }
314 }
315 }
316
Andrew Kaylorea395922013-10-01 01:47:35 +0000317 // If it hasn't already been generated, see if it's in one of our modules.
318 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
Lang Hamesea800ca2014-08-14 02:38:20 +0000319 if (M) {
320 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000321
Lang Hamesea800ca2014-08-14 02:38:20 +0000322 // Check the RuntimeDyld table again, it should be there now.
323 return getExistingSymbolAddress(Name);
324 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000325
Lang Hamesea800ca2014-08-14 02:38:20 +0000326 // If a LazyFunctionCreator is installed, use it to get/create the function.
327 // FIXME: Should we instead have a LazySymbolCreator callback?
328 if (LazyFunctionCreator)
329 Addr = (uint64_t)LazyFunctionCreator(Name);
330
331 return Addr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000332}
333
334uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000335 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000336 uint64_t Result = getSymbolAddress(Name, false);
337 if (Result != 0)
338 finalizeLoadedModules();
339 return Result;
340}
341
342uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000343 MutexGuard locked(lock);
Andrew Kaylorea395922013-10-01 01:47:35 +0000344 uint64_t Result = getSymbolAddress(Name, true);
345 if (Result != 0)
346 finalizeLoadedModules();
347 return Result;
348}
349
350// Deprecated. Use getFunctionAddress instead.
351void *MCJIT::getPointerToFunction(Function *F) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000352 MutexGuard locked(lock);
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000353
Lang Hamesb7fbf592014-09-20 17:44:56 +0000354 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
355 SmallString<128> Name;
356 TM->getNameWithPrefix(Name, F, Mang);
357
Jim Grosbachd5274402011-03-22 18:05:27 +0000358 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
359 bool AbortOnFailure = !F->hasExternalWeakLinkage();
Lang Hamesb7fbf592014-09-20 17:44:56 +0000360 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
Jim Grosbachd5274402011-03-22 18:05:27 +0000361 addGlobalMapping(F, Addr);
362 return Addr;
363 }
364
Andrew Kaylorea395922013-10-01 01:47:35 +0000365 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000366 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000367
368 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000369 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000370 generateCodeForModule(M);
Lang Hamesb7fbf592014-09-20 17:44:56 +0000371 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000372 // If this function doesn't belong to one of our modules, we're done.
Lang Hamesb7fbf592014-09-20 17:44:56 +0000373 // FIXME: Asking for the pointer to a function that hasn't been registered,
374 // and isn't a declaration (which is handled above) should probably
375 // be an assertion.
Craig Topper353eda42014-04-24 06:44:33 +0000376 return nullptr;
Lang Hamesb7fbf592014-09-20 17:44:56 +0000377 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000378
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000379 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000380 //
381 // This is the accessor for the target address, so make sure to check the
382 // load address of the symbol, not the local address.
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000383 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000384}
385
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000386void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
387 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
388 for (; I != E; ++I) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000389 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000390 }
391}
392
393void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
394 // Execute global ctors/dtors for each module in the program.
395 runStaticConstructorsDestructorsInModulePtrSet(
396 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
397 runStaticConstructorsDestructorsInModulePtrSet(
398 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
399 runStaticConstructorsDestructorsInModulePtrSet(
400 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
401}
402
403Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
404 ModulePtrSet::iterator I,
405 ModulePtrSet::iterator E) {
406 for (; I != E; ++I) {
407 if (Function *F = (*I)->getFunction(FnName))
408 return F;
409 }
Craig Topper353eda42014-04-24 06:44:33 +0000410 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000411}
412
413Function *MCJIT::FindFunctionNamed(const char *FnName) {
414 Function *F = FindFunctionNamedInModulePtrSet(
415 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
416 if (!F)
417 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
418 OwnedModules.end_loaded());
419 if (!F)
420 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
421 OwnedModules.end_finalized());
422 return F;
423}
424
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000425GenericValue MCJIT::runFunction(Function *F,
426 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000427 assert(F && "Function *F was null at entry to run()");
428
Jim Grosbach7b162492011-03-18 22:48:41 +0000429 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000430 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000431 FunctionType *FTy = F->getFunctionType();
432 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000433
434 assert((FTy->getNumParams() == ArgValues.size() ||
435 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
436 "Wrong number of arguments passed into function!");
437 assert(FTy->getNumParams() == ArgValues.size() &&
438 "This doesn't support passing arguments through varargs (yet)!");
439
440 // Handle some common cases first. These cases correspond to common `main'
441 // prototypes.
442 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
443 switch (ArgValues.size()) {
444 case 3:
445 if (FTy->getParamType(0)->isIntegerTy(32) &&
446 FTy->getParamType(1)->isPointerTy() &&
447 FTy->getParamType(2)->isPointerTy()) {
448 int (*PF)(int, char **, const char **) =
449 (int(*)(int, char **, const char **))(intptr_t)FPtr;
450
451 // Call the function.
452 GenericValue rv;
453 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
454 (char **)GVTOP(ArgValues[1]),
455 (const char **)GVTOP(ArgValues[2])));
456 return rv;
457 }
458 break;
459 case 2:
460 if (FTy->getParamType(0)->isIntegerTy(32) &&
461 FTy->getParamType(1)->isPointerTy()) {
462 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
463
464 // Call the function.
465 GenericValue rv;
466 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
467 (char **)GVTOP(ArgValues[1])));
468 return rv;
469 }
470 break;
471 case 1:
472 if (FTy->getNumParams() == 1 &&
473 FTy->getParamType(0)->isIntegerTy(32)) {
474 GenericValue rv;
475 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
476 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
477 return rv;
478 }
479 break;
480 }
481 }
482
483 // Handle cases where no arguments are passed first.
484 if (ArgValues.empty()) {
485 GenericValue rv;
486 switch (RetTy->getTypeID()) {
487 default: llvm_unreachable("Unknown return type for function call!");
488 case Type::IntegerTyID: {
489 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
490 if (BitWidth == 1)
491 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
492 else if (BitWidth <= 8)
493 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
494 else if (BitWidth <= 16)
495 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
496 else if (BitWidth <= 32)
497 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
498 else if (BitWidth <= 64)
499 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
500 else
501 llvm_unreachable("Integer types > 64 bits not supported");
502 return rv;
503 }
504 case Type::VoidTyID:
505 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
506 return rv;
507 case Type::FloatTyID:
508 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
509 return rv;
510 case Type::DoubleTyID:
511 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
512 return rv;
513 case Type::X86_FP80TyID:
514 case Type::FP128TyID:
515 case Type::PPC_FP128TyID:
516 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000517 case Type::PointerTyID:
518 return PTOGV(((void*(*)())(intptr_t)FPtr)());
519 }
520 }
521
Craig Toppera2886c22012-02-07 05:05:23 +0000522 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000523}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000524
Lang Hames9a783342014-09-15 17:50:22 +0000525void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000526 if (!isSymbolSearchingDisabled()) {
527 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000528 if (ptr)
529 return ptr;
530 }
531
532 /// If a LazyFunctionCreator is installed, use it to get/create the function.
533 if (LazyFunctionCreator)
534 if (void *RP = LazyFunctionCreator(Name))
535 return RP;
536
537 if (AbortOnFailure) {
538 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000539 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000540 }
Craig Topper353eda42014-04-24 06:44:33 +0000541 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000542}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000543
544void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000545 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000546 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000547 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000548 EventListeners.push_back(L);
549}
550void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000551 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000552 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000553 MutexGuard locked(lock);
Eric Christopher79cc1e32014-09-02 22:28:02 +0000554 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000555 if (I != EventListeners.rend()) {
556 std::swap(*I, EventListeners.back());
557 EventListeners.pop_back();
558 }
559}
560void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000561 MutexGuard locked(lock);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000562 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000563 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
564 EventListeners[I]->NotifyObjectEmitted(Obj);
565 }
566}
567void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000568 MutexGuard locked(lock);
David Blaikieed9709d2014-09-03 19:48:09 +0000569 for (JITEventListener *L : EventListeners)
Eric Christopher79cc1e32014-09-02 22:28:02 +0000570 L->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000571}
Andrew Kaylorea395922013-10-01 01:47:35 +0000572
573uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
574 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000575 // If the symbols wasn't found and it begins with an underscore, try again
576 // without the underscore.
577 if (!Result && Name[0] == '_')
578 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000579 if (Result)
580 return Result;
Lang Hamesea800ca2014-08-14 02:38:20 +0000581 if (ParentEngine->isSymbolSearchingDisabled())
582 return 0;
Andrew Kaylorea395922013-10-01 01:47:35 +0000583 return ClientMM->getSymbolAddress(Name);
584}