blob: 8c6db75487f524d3f028c83c41b63b38d3d0f8a5 [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
46ExecutionEngine *MCJIT::createJIT(Module *M,
47 std::string *ErrorStr,
Filip Pizlo9bc53e82013-05-14 19:29:00 +000048 RTDyldMemoryManager *MemMgr,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000049 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
Rafael Espindolab9a23cd2014-07-31 01:14:09 +000055 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager());
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +000056}
57
Rafael Espindolab9a23cd2014-07-31 01:14:09 +000058MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM)
Craig Topper353eda42014-04-24 06:44:33 +000059 : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
60 ObjCache(nullptr) {
Jim Grosbach7b162492011-03-18 22:48:41 +000061
Andrew Kaylorc89fc822013-10-24 00:19:14 +000062 OwnedModules.addModule(m);
Eric Christopherd9134482014-08-04 21:25:23 +000063 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Andrew Kaylor1a568c32012-08-07 18:33:00 +000064}
65
66MCJIT::~MCJIT() {
Zachary Turnerc04b8922014-06-20 21:07:14 +000067 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000068 // FIXME: We are managing our modules, so we do not want the base class
69 // ExecutionEngine to manage them as well. To avoid double destruction
70 // of the first (and only) module added in ExecutionEngine constructor
71 // we remove it from EE and will destruct it ourselves.
72 //
73 // It may make sense to move our module manager (based on SmallStPtr) back
74 // into EE if the JIT and Interpreter can live with it.
75 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
76 // runStaticConstructorsDestructors could be moved back to EE as well.
77 //
78 Modules.clear();
Andrew Kaylorc442a762013-10-16 00:14:21 +000079 Dyld.deregisterEHFrames();
Chandler Carruthd55d1592013-10-24 09:52:56 +000080
Lang Hames173c69f2014-01-08 04:09:09 +000081 LoadedObjectList::iterator it, end;
82 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
83 ObjectImage *Obj = *it;
Chandler Carruthd55d1592013-10-24 09:52:56 +000084 if (Obj) {
85 NotifyFreeingObject(*Obj);
86 delete Obj;
87 }
88 }
Andrew Kaylorea395922013-10-01 01:47:35 +000089 LoadedObjects.clear();
Lang Hames173c69f2014-01-08 04:09:09 +000090
Lang Hames173c69f2014-01-08 04:09:09 +000091 Archives.clear();
92
Andrew Kaylor1a568c32012-08-07 18:33:00 +000093 delete TM;
94}
95
Andrew Kaylorea395922013-10-01 01:47:35 +000096void MCJIT::addModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +000097 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +000098 OwnedModules.addModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +000099}
100
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000101bool MCJIT::removeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000102 MutexGuard locked(lock);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000103 return OwnedModules.removeModule(M);
104}
105
106
107
David Blaikie7a1e7752014-04-29 21:52:46 +0000108void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
109 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
Juergen Ributzka6ff29a72014-03-26 18:19:27 +0000110 if (!LoadedObject || Dyld.hasError())
Lang Hames173c69f2014-01-08 04:09:09 +0000111 report_fatal_error(Dyld.getErrorString());
112
113 LoadedObjects.push_back(LoadedObject);
114
115 NotifyObjectEmitted(*LoadedObject);
116}
117
Rafael Espindolace47a052014-08-01 18:09:32 +0000118void MCJIT::addArchive(std::unique_ptr<object::Archive> A) {
119 Archives.push_back(std::move(A));
Lang Hames173c69f2014-01-08 04:09:09 +0000120}
121
122
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000123void MCJIT::setObjectCache(ObjectCache* NewCache) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000124 MutexGuard locked(lock);
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000125 ObjCache = NewCache;
126}
127
Andrew Kaylorea395922013-10-01 01:47:35 +0000128ObjectBufferStream* MCJIT::emitObject(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000129 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000130
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000131 // This must be a module which has already been added but not loaded to this
132 // MCJIT instance, since these conditions are tested by our caller,
133 // generateCodeForModule.
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000134
135 PassManager PM;
136
Eric Christopherd9134482014-08-04 21:25:23 +0000137 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola339430f2014-02-25 23:25:17 +0000138 PM.add(new DataLayoutPass(M));
Jim Grosbach7b162492011-03-18 22:48:41 +0000139
Andrew Kayloradc70562012-10-02 21:18:39 +0000140 // The RuntimeDyld will take ownership of this shortly
Ahmed Charles56440fd2014-03-06 05:51:42 +0000141 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
Andrew Kayloradc70562012-10-02 21:18:39 +0000142
Jim Grosbach7b162492011-03-18 22:48:41 +0000143 // Turn the machine code intermediate representation into bytes in memory
144 // that may be executed.
Lang Hamesbc876012014-04-18 06:48:23 +0000145 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
146 !getVerifyModules())) {
Jim Grosbach7b162492011-03-18 22:48:41 +0000147 report_fatal_error("Target does not support MC emission!");
148 }
149
150 // Initialize passes.
Andrew Kaylorea395922013-10-01 01:47:35 +0000151 PM.run(*M);
Andrew Kayloradc70562012-10-02 21:18:39 +0000152 // Flush the output buffer to get the generated code into memory
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000153 CompiledObject->flush();
154
155 // If we have an object cache, tell it about the new object.
156 // Note that we're using the compiled image, not the loaded image (as below).
157 if (ObjCache) {
158 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
159 // to create a temporary object here and delete it after the call.
Rafael Espindola3a1623f2014-08-17 23:38:08 +0000160 std::unique_ptr<MemoryBuffer> MB = CompiledObject->getMemBuffer();
Andrew Kaylorea395922013-10-01 01:47:35 +0000161 ObjCache->notifyObjectCompiled(M, MB.get());
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000162 }
163
Ahmed Charles96c9d952014-03-05 10:19:29 +0000164 return CompiledObject.release();
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000165}
166
Andrew Kaylorea395922013-10-01 01:47:35 +0000167void MCJIT::generateCodeForModule(Module *M) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000168 // Get a thread lock to make sure we aren't trying to load multiple times
Zachary Turnerc04b8922014-06-20 21:07:14 +0000169 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000170
Andrew Kaylorea395922013-10-01 01:47:35 +0000171 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000172 assert(OwnedModules.ownsModule(M) &&
173 "MCJIT::generateCodeForModule: Unknown module.");
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000174
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000175 // Re-compilation is not supported
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000176 if (OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000177 return;
178
Ahmed Charles56440fd2014-03-06 05:51:42 +0000179 std::unique_ptr<ObjectBuffer> ObjectToLoad;
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000180 // Try to load the pre-compiled object from cache if possible
Craig Topper353eda42014-04-24 06:44:33 +0000181 if (ObjCache) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000182 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
Craig Topper353eda42014-04-24 06:44:33 +0000183 if (PreCompiledObject.get())
Ahmed Charles96c9d952014-03-05 10:19:29 +0000184 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
Andrew Kaylorced4e8f2013-04-25 21:02:36 +0000185 }
186
187 // If the cache did not contain a suitable object, compile the object
188 if (!ObjectToLoad) {
189 ObjectToLoad.reset(emitObject(M));
190 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
191 }
Jim Grosbach348a5482011-03-22 01:06:42 +0000192
193 // Load the object into the dynamic linker.
Lang Hames173c69f2014-01-08 04:09:09 +0000194 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
Ahmed Charles96c9d952014-03-05 10:19:29 +0000195 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
Lang Hames173c69f2014-01-08 04:09:09 +0000196 LoadedObjects.push_back(LoadedObject);
Andrew Kayloradc70562012-10-02 21:18:39 +0000197 if (!LoadedObject)
Jim Grosbachc114d892011-03-23 19:51:34 +0000198 report_fatal_error(Dyld.getErrorString());
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000199
Andrew Kayloradc70562012-10-02 21:18:39 +0000200 // FIXME: Make this optional, maybe even move it to a JIT event listener
201 LoadedObject->registerWithDebugger();
202
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000203 NotifyObjectEmitted(*LoadedObject);
204
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000205 OwnedModules.markModuleAsLoaded(M);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000206}
207
Andrew Kaylorea395922013-10-01 01:47:35 +0000208void MCJIT::finalizeLoadedModules() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000209 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000210
Andrew Kaylorea395922013-10-01 01:47:35 +0000211 // Resolve any outstanding relocations.
212 Dyld.resolveRelocations();
213
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000214 OwnedModules.markAllLoadedModulesAsFinalized();
215
Andrew Kaylorea395922013-10-01 01:47:35 +0000216 // Register EH frame data for any module we own which has been loaded
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000217 Dyld.registerEHFrames();
218
Andrew Kaylorea395922013-10-01 01:47:35 +0000219 // Set page permissions.
220 MemMgr.finalizeMemory();
221}
222
223// FIXME: Rename this.
224void MCJIT::finalizeObject() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000225 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000226
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000227 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
228 E = OwnedModules.end_added();
229 I != E; ++I) {
230 Module *M = *I;
231 generateCodeForModule(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000232 }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000233
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000234 finalizeLoadedModules();
Andrew Kaylorea395922013-10-01 01:47:35 +0000235}
236
237void MCJIT::finalizeModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000238 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000239
Andrew Kaylorea395922013-10-01 01:47:35 +0000240 // This must be a module which has already been added to this MCJIT instance.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000241 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
Andrew Kaylorea395922013-10-01 01:47:35 +0000242
243 // If the module hasn't been compiled, just do that.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000244 if (!OwnedModules.hasModuleBeenLoaded(M))
Andrew Kaylorea395922013-10-01 01:47:35 +0000245 generateCodeForModule(M);
246
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000247 finalizeLoadedModules();
Andrew Kaylora714efc2012-11-05 20:57:16 +0000248}
249
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000250void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
251 report_fatal_error("not yet implemented");
252}
253
Andrew Kaylorea395922013-10-01 01:47:35 +0000254uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
Eric Christopherd9134482014-08-04 21:25:23 +0000255 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000256 SmallString<128> FullName;
257 Mang.getNameWithPrefix(FullName, Name);
258 return Dyld.getSymbolLoadAddress(FullName);
Andrew Kaylorea395922013-10-01 01:47:35 +0000259}
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000260
Andrew Kaylorea395922013-10-01 01:47:35 +0000261Module *MCJIT::findModuleForSymbol(const std::string &Name,
262 bool CheckFunctionsOnly) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000263 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000264
Andrew Kaylorea395922013-10-01 01:47:35 +0000265 // If it hasn't already been generated, see if it's in one of our modules.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000266 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
267 E = OwnedModules.end_added();
268 I != E; ++I) {
269 Module *M = *I;
Andrew Kaylorea395922013-10-01 01:47:35 +0000270 Function *F = M->getFunction(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000271 if (F && !F->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000272 return M;
273 if (!CheckFunctionsOnly) {
274 GlobalVariable *G = M->getGlobalVariable(Name);
Andrew Kaylor515b1da2013-11-15 22:10:21 +0000275 if (G && !G->isDeclaration())
Andrew Kaylorea395922013-10-01 01:47:35 +0000276 return M;
277 // FIXME: Do we need to worry about global aliases?
278 }
279 }
280 // We didn't find the symbol in any of our modules.
Craig Topper353eda42014-04-24 06:44:33 +0000281 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000282}
283
284uint64_t MCJIT::getSymbolAddress(const std::string &Name,
285 bool CheckFunctionsOnly)
286{
Zachary Turnerc04b8922014-06-20 21:07:14 +0000287 MutexGuard locked(lock);
Andrew Kaylor4fba0492013-10-21 17:42:06 +0000288
Andrew Kaylorea395922013-10-01 01:47:35 +0000289 // First, check to see if we already have this symbol.
290 uint64_t Addr = getExistingSymbolAddress(Name);
291 if (Addr)
292 return Addr;
293
Rafael Espindolace47a052014-08-01 18:09:32 +0000294 for (std::unique_ptr<object::Archive> &A : Archives) {
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
Jim Grosbachd5274402011-03-22 18:05:27 +0000354 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
355 bool AbortOnFailure = !F->hasExternalWeakLinkage();
356 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
357 addGlobalMapping(F, Addr);
358 return Addr;
359 }
360
Andrew Kaylorea395922013-10-01 01:47:35 +0000361 Module *M = F->getParent();
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000362 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
Andrew Kaylorea395922013-10-01 01:47:35 +0000363
364 // Make sure the relevant module has been compiled and loaded.
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000365 if (HasBeenAddedButNotLoaded)
Andrew Kaylorea395922013-10-01 01:47:35 +0000366 generateCodeForModule(M);
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000367 else if (!OwnedModules.hasModuleBeenLoaded(M))
368 // If this function doesn't belong to one of our modules, we're done.
Craig Topper353eda42014-04-24 06:44:33 +0000369 return nullptr;
Andrew Kaylorea395922013-10-01 01:47:35 +0000370
Andrew Kaylor1a568c32012-08-07 18:33:00 +0000371 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000372 //
373 // This is the accessor for the target address, so make sure to check the
374 // load address of the symbol, not the local address.
Eric Christopherd9134482014-08-04 21:25:23 +0000375 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000376 SmallString<128> Name;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000377 TM->getNameWithPrefix(Name, F, Mang);
Rafael Espindola3e3a3f12013-11-28 08:59:52 +0000378 return (void*)Dyld.getSymbolLoadAddress(Name);
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000379}
380
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000381void *MCJIT::recompileAndRelinkFunction(Function *F) {
382 report_fatal_error("not yet implemented");
383}
384
385void MCJIT::freeMachineCodeForFunction(Function *F) {
386 report_fatal_error("not yet implemented");
387}
388
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000389void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
390 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
391 for (; I != E; ++I) {
392 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
393 }
394}
395
396void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
397 // Execute global ctors/dtors for each module in the program.
398 runStaticConstructorsDestructorsInModulePtrSet(
399 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
400 runStaticConstructorsDestructorsInModulePtrSet(
401 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
402 runStaticConstructorsDestructorsInModulePtrSet(
403 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
404}
405
406Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
407 ModulePtrSet::iterator I,
408 ModulePtrSet::iterator E) {
409 for (; I != E; ++I) {
410 if (Function *F = (*I)->getFunction(FnName))
411 return F;
412 }
Craig Topper353eda42014-04-24 06:44:33 +0000413 return nullptr;
Andrew Kaylorc89fc822013-10-24 00:19:14 +0000414}
415
416Function *MCJIT::FindFunctionNamed(const char *FnName) {
417 Function *F = FindFunctionNamedInModulePtrSet(
418 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
419 if (!F)
420 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
421 OwnedModules.end_loaded());
422 if (!F)
423 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
424 OwnedModules.end_finalized());
425 return F;
426}
427
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000428GenericValue MCJIT::runFunction(Function *F,
429 const std::vector<GenericValue> &ArgValues) {
Jim Grosbachd5274402011-03-22 18:05:27 +0000430 assert(F && "Function *F was null at entry to run()");
431
Jim Grosbach7b162492011-03-18 22:48:41 +0000432 void *FPtr = getPointerToFunction(F);
Jim Grosbachd5274402011-03-22 18:05:27 +0000433 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattner229907c2011-07-18 04:54:35 +0000434 FunctionType *FTy = F->getFunctionType();
435 Type *RetTy = FTy->getReturnType();
Jim Grosbachd5274402011-03-22 18:05:27 +0000436
437 assert((FTy->getNumParams() == ArgValues.size() ||
438 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
439 "Wrong number of arguments passed into function!");
440 assert(FTy->getNumParams() == ArgValues.size() &&
441 "This doesn't support passing arguments through varargs (yet)!");
442
443 // Handle some common cases first. These cases correspond to common `main'
444 // prototypes.
445 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
446 switch (ArgValues.size()) {
447 case 3:
448 if (FTy->getParamType(0)->isIntegerTy(32) &&
449 FTy->getParamType(1)->isPointerTy() &&
450 FTy->getParamType(2)->isPointerTy()) {
451 int (*PF)(int, char **, const char **) =
452 (int(*)(int, char **, const char **))(intptr_t)FPtr;
453
454 // Call the function.
455 GenericValue rv;
456 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
457 (char **)GVTOP(ArgValues[1]),
458 (const char **)GVTOP(ArgValues[2])));
459 return rv;
460 }
461 break;
462 case 2:
463 if (FTy->getParamType(0)->isIntegerTy(32) &&
464 FTy->getParamType(1)->isPointerTy()) {
465 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
466
467 // Call the function.
468 GenericValue rv;
469 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
470 (char **)GVTOP(ArgValues[1])));
471 return rv;
472 }
473 break;
474 case 1:
475 if (FTy->getNumParams() == 1 &&
476 FTy->getParamType(0)->isIntegerTy(32)) {
477 GenericValue rv;
478 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
479 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
480 return rv;
481 }
482 break;
483 }
484 }
485
486 // Handle cases where no arguments are passed first.
487 if (ArgValues.empty()) {
488 GenericValue rv;
489 switch (RetTy->getTypeID()) {
490 default: llvm_unreachable("Unknown return type for function call!");
491 case Type::IntegerTyID: {
492 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
493 if (BitWidth == 1)
494 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
495 else if (BitWidth <= 8)
496 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 16)
498 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
499 else if (BitWidth <= 32)
500 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
501 else if (BitWidth <= 64)
502 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
503 else
504 llvm_unreachable("Integer types > 64 bits not supported");
505 return rv;
506 }
507 case Type::VoidTyID:
508 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
509 return rv;
510 case Type::FloatTyID:
511 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
512 return rv;
513 case Type::DoubleTyID:
514 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
515 return rv;
516 case Type::X86_FP80TyID:
517 case Type::FP128TyID:
518 case Type::PPC_FP128TyID:
519 llvm_unreachable("long double not supported yet");
Jim Grosbachd5274402011-03-22 18:05:27 +0000520 case Type::PointerTyID:
521 return PTOGV(((void*(*)())(intptr_t)FPtr)());
522 }
523 }
524
Craig Toppera2886c22012-02-07 05:05:23 +0000525 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar7e5d8a72010-11-17 16:06:43 +0000526}
Danil Malyshevbfee5422012-03-28 21:46:36 +0000527
528void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000529 bool AbortOnFailure) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000530 if (!isSymbolSearchingDisabled()) {
531 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
Danil Malyshevbfee5422012-03-28 21:46:36 +0000532 if (ptr)
533 return ptr;
534 }
535
536 /// If a LazyFunctionCreator is installed, use it to get/create the function.
537 if (LazyFunctionCreator)
538 if (void *RP = LazyFunctionCreator(Name))
539 return RP;
540
541 if (AbortOnFailure) {
542 report_fatal_error("Program used external function '"+Name+
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000543 "' which could not be resolved!");
Danil Malyshevbfee5422012-03-28 21:46:36 +0000544 }
Craig Topper353eda42014-04-24 06:44:33 +0000545 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000546}
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000547
548void MCJIT::RegisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000549 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000550 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000551 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000552 EventListeners.push_back(L);
553}
554void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
Craig Topper353eda42014-04-24 06:44:33 +0000555 if (!L)
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000556 return;
Zachary Turnerc04b8922014-06-20 21:07:14 +0000557 MutexGuard locked(lock);
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000558 SmallVector<JITEventListener*, 2>::reverse_iterator I=
559 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000560 if (I != EventListeners.rend()) {
561 std::swap(*I, EventListeners.back());
562 EventListeners.pop_back();
563 }
564}
565void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000566 MutexGuard locked(lock);
Andrew Kaylor1b2cfb62013-10-04 00:49:38 +0000567 MemMgr.notifyObjectLoaded(this, &Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000568 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
569 EventListeners[I]->NotifyObjectEmitted(Obj);
570 }
571}
572void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000573 MutexGuard locked(lock);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000574 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
Eric Christopherb9fd9ed2014-08-07 22:02:54 +0000575 EventListeners[I]->NotifyFreeingObject(Obj);
Andrew Kaylord8ffd9c2012-11-06 18:51:59 +0000576 }
577}
Andrew Kaylorea395922013-10-01 01:47:35 +0000578
579uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
580 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
Andrew Kaylor89bdd102013-10-01 16:42:50 +0000581 // If the symbols wasn't found and it begins with an underscore, try again
582 // without the underscore.
583 if (!Result && Name[0] == '_')
584 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
Andrew Kaylorea395922013-10-01 01:47:35 +0000585 if (Result)
586 return Result;
Lang Hamesea800ca2014-08-14 02:38:20 +0000587 if (ParentEngine->isSymbolSearchingDisabled())
588 return 0;
Andrew Kaylorea395922013-10-01 01:47:35 +0000589 return ClientMM->getSymbolAddress(Name);
590}