MCJIT.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
  2. //
  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. #include "MCJIT.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ExecutionEngine/GenericValue.h"
  12. #include "llvm/ExecutionEngine/JITEventListener.h"
  13. #include "llvm/ExecutionEngine/MCJIT.h"
  14. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  15. #include "llvm/IR/DataLayout.h"
  16. #include "llvm/IR/DerivedTypes.h"
  17. #include "llvm/IR/Function.h"
  18. #include "llvm/IR/LegacyPassManager.h"
  19. #include "llvm/IR/Mangler.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/MC/MCAsmInfo.h"
  22. #include "llvm/Object/Archive.h"
  23. #include "llvm/Object/ObjectFile.h"
  24. #include "llvm/Support/DynamicLibrary.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/MemoryBuffer.h"
  27. #include "llvm/Support/MutexGuard.h"
  28. using namespace llvm;
  29. void ObjectCache::anchor() {}
  30. namespace {
  31. static struct RegisterJIT {
  32. RegisterJIT() { MCJIT::Register(); }
  33. } JITRegistrator;
  34. }
  35. extern "C" void LLVMLinkInMCJIT() {
  36. }
  37. ExecutionEngine*
  38. MCJIT::createJIT(std::unique_ptr<Module> M,
  39. std::string *ErrorStr,
  40. std::shared_ptr<MCJITMemoryManager> MemMgr,
  41. std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
  42. std::unique_ptr<TargetMachine> TM) {
  43. // Try to register the program as a source of symbols to resolve against.
  44. //
  45. // FIXME: Don't do this here.
  46. sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
  47. if (!MemMgr || !Resolver) {
  48. auto RTDyldMM = std::make_shared<SectionMemoryManager>();
  49. if (!MemMgr)
  50. MemMgr = RTDyldMM;
  51. if (!Resolver)
  52. Resolver = RTDyldMM;
  53. }
  54. return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
  55. std::move(Resolver));
  56. }
  57. MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
  58. std::shared_ptr<MCJITMemoryManager> MemMgr,
  59. std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver)
  60. : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
  61. MemMgr(std::move(MemMgr)), Resolver(*this, std::move(Resolver)),
  62. Dyld(*this->MemMgr, this->Resolver), ObjCache(nullptr) {
  63. // 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. //
  73. std::unique_ptr<Module> First = std::move(Modules[0]);
  74. Modules.clear();
  75. OwnedModules.addModule(std::move(First));
  76. setDataLayout(TM->getDataLayout());
  77. RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
  78. }
  79. MCJIT::~MCJIT() {
  80. MutexGuard locked(lock);
  81. Dyld.deregisterEHFrames();
  82. for (auto &Obj : LoadedObjects)
  83. if (Obj)
  84. NotifyFreeingObject(*Obj);
  85. Archives.clear();
  86. }
  87. void MCJIT::addModule(std::unique_ptr<Module> M) {
  88. MutexGuard locked(lock);
  89. OwnedModules.addModule(std::move(M));
  90. }
  91. bool MCJIT::removeModule(Module *M) {
  92. MutexGuard locked(lock);
  93. return OwnedModules.removeModule(M);
  94. }
  95. void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
  96. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
  97. if (Dyld.hasError())
  98. report_fatal_error(Dyld.getErrorString());
  99. NotifyObjectEmitted(*Obj, *L);
  100. LoadedObjects.push_back(std::move(Obj));
  101. }
  102. void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
  103. std::unique_ptr<object::ObjectFile> ObjFile;
  104. std::unique_ptr<MemoryBuffer> MemBuf;
  105. std::tie(ObjFile, MemBuf) = Obj.takeBinary();
  106. addObjectFile(std::move(ObjFile));
  107. Buffers.push_back(std::move(MemBuf));
  108. }
  109. void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
  110. Archives.push_back(std::move(A));
  111. }
  112. void MCJIT::setObjectCache(ObjectCache* NewCache) {
  113. MutexGuard locked(lock);
  114. ObjCache = NewCache;
  115. }
  116. std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
  117. MutexGuard locked(lock);
  118. // This must be a module which has already been added but not loaded to this
  119. // MCJIT instance, since these conditions are tested by our caller,
  120. // generateCodeForModule.
  121. legacy::PassManager PM;
  122. // The RuntimeDyld will take ownership of this shortly
  123. SmallVector<char, 4096> ObjBufferSV;
  124. raw_svector_ostream ObjStream(ObjBufferSV);
  125. // Turn the machine code intermediate representation into bytes in memory
  126. // that may be executed.
  127. if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
  128. report_fatal_error("Target does not support MC emission!");
  129. // Initialize passes.
  130. PM.run(*M);
  131. // Flush the output buffer to get the generated code into memory
  132. ObjStream.flush();
  133. std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
  134. new ObjectMemoryBuffer(std::move(ObjBufferSV)));
  135. // If we have an object cache, tell it about the new object.
  136. // Note that we're using the compiled image, not the loaded image (as below).
  137. if (ObjCache) {
  138. // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
  139. // to create a temporary object here and delete it after the call.
  140. MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
  141. ObjCache->notifyObjectCompiled(M, MB);
  142. }
  143. return CompiledObjBuffer;
  144. }
  145. void MCJIT::generateCodeForModule(Module *M) {
  146. // Get a thread lock to make sure we aren't trying to load multiple times
  147. MutexGuard locked(lock);
  148. // This must be a module which has already been added to this MCJIT instance.
  149. assert(OwnedModules.ownsModule(M) &&
  150. "MCJIT::generateCodeForModule: Unknown module.");
  151. // Re-compilation is not supported
  152. if (OwnedModules.hasModuleBeenLoaded(M))
  153. return;
  154. std::unique_ptr<MemoryBuffer> ObjectToLoad;
  155. // Try to load the pre-compiled object from cache if possible
  156. if (ObjCache)
  157. ObjectToLoad = ObjCache->getObject(M);
  158. M->setDataLayout(*TM->getDataLayout());
  159. // If the cache did not contain a suitable object, compile the object
  160. if (!ObjectToLoad) {
  161. ObjectToLoad = emitObject(M);
  162. assert(ObjectToLoad && "Compilation did not produce an object.");
  163. }
  164. // Load the object into the dynamic linker.
  165. // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
  166. ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
  167. object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
  168. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
  169. Dyld.loadObject(*LoadedObject.get());
  170. if (Dyld.hasError())
  171. report_fatal_error(Dyld.getErrorString());
  172. NotifyObjectEmitted(*LoadedObject.get(), *L);
  173. Buffers.push_back(std::move(ObjectToLoad));
  174. LoadedObjects.push_back(std::move(*LoadedObject));
  175. OwnedModules.markModuleAsLoaded(M);
  176. }
  177. void MCJIT::finalizeLoadedModules() {
  178. MutexGuard locked(lock);
  179. // Resolve any outstanding relocations.
  180. Dyld.resolveRelocations();
  181. OwnedModules.markAllLoadedModulesAsFinalized();
  182. // Register EH frame data for any module we own which has been loaded
  183. Dyld.registerEHFrames();
  184. // Set page permissions.
  185. MemMgr->finalizeMemory();
  186. }
  187. // FIXME: Rename this.
  188. void MCJIT::finalizeObject() {
  189. MutexGuard locked(lock);
  190. // Generate code for module is going to move objects out of the 'added' list,
  191. // so we need to copy that out before using it:
  192. SmallVector<Module*, 16> ModsToAdd;
  193. for (auto M : OwnedModules.added())
  194. ModsToAdd.push_back(M);
  195. for (auto M : ModsToAdd)
  196. generateCodeForModule(M);
  197. finalizeLoadedModules();
  198. }
  199. void MCJIT::finalizeModule(Module *M) {
  200. MutexGuard locked(lock);
  201. // This must be a module which has already been added to this MCJIT instance.
  202. assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
  203. // If the module hasn't been compiled, just do that.
  204. if (!OwnedModules.hasModuleBeenLoaded(M))
  205. generateCodeForModule(M);
  206. finalizeLoadedModules();
  207. }
  208. RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
  209. SmallString<128> FullName;
  210. Mangler::getNameWithPrefix(FullName, Name, *TM->getDataLayout());
  211. if (void *Addr = getPointerToGlobalIfAvailable(FullName))
  212. return RuntimeDyld::SymbolInfo(static_cast<uint64_t>(
  213. reinterpret_cast<uintptr_t>(Addr)),
  214. JITSymbolFlags::Exported);
  215. return Dyld.getSymbol(FullName);
  216. }
  217. Module *MCJIT::findModuleForSymbol(const std::string &Name,
  218. bool CheckFunctionsOnly) {
  219. MutexGuard locked(lock);
  220. // If it hasn't already been generated, see if it's in one of our modules.
  221. for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
  222. E = OwnedModules.end_added();
  223. I != E; ++I) {
  224. Module *M = *I;
  225. Function *F = M->getFunction(Name);
  226. if (F && !F->isDeclaration())
  227. return M;
  228. if (!CheckFunctionsOnly) {
  229. GlobalVariable *G = M->getGlobalVariable(Name);
  230. if (G && !G->isDeclaration())
  231. return M;
  232. // FIXME: Do we need to worry about global aliases?
  233. }
  234. }
  235. // We didn't find the symbol in any of our modules.
  236. return nullptr;
  237. }
  238. uint64_t MCJIT::getSymbolAddress(const std::string &Name,
  239. bool CheckFunctionsOnly) {
  240. return findSymbol(Name, CheckFunctionsOnly).getAddress();
  241. }
  242. RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
  243. bool CheckFunctionsOnly) {
  244. MutexGuard locked(lock);
  245. // First, check to see if we already have this symbol.
  246. if (auto Sym = findExistingSymbol(Name))
  247. return Sym;
  248. for (object::OwningBinary<object::Archive> &OB : Archives) {
  249. object::Archive *A = OB.getBinary();
  250. // Look for our symbols in each Archive
  251. object::Archive::child_iterator ChildIt = A->findSym(Name);
  252. if (ChildIt != A->child_end()) {
  253. // FIXME: Support nested archives?
  254. ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
  255. ChildIt->getAsBinary();
  256. if (ChildBinOrErr.getError())
  257. continue;
  258. std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
  259. if (ChildBin->isObject()) {
  260. std::unique_ptr<object::ObjectFile> OF(
  261. static_cast<object::ObjectFile *>(ChildBin.release()));
  262. // This causes the object file to be loaded.
  263. addObjectFile(std::move(OF));
  264. // The address should be here now.
  265. if (auto Sym = findExistingSymbol(Name))
  266. return Sym;
  267. }
  268. }
  269. }
  270. // If it hasn't already been generated, see if it's in one of our modules.
  271. Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
  272. if (M) {
  273. generateCodeForModule(M);
  274. // Check the RuntimeDyld table again, it should be there now.
  275. return findExistingSymbol(Name);
  276. }
  277. // If a LazyFunctionCreator is installed, use it to get/create the function.
  278. // FIXME: Should we instead have a LazySymbolCreator callback?
  279. if (LazyFunctionCreator) {
  280. auto Addr = static_cast<uint64_t>(
  281. reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
  282. return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
  283. }
  284. return nullptr;
  285. }
  286. uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
  287. MutexGuard locked(lock);
  288. uint64_t Result = getSymbolAddress(Name, false);
  289. if (Result != 0)
  290. finalizeLoadedModules();
  291. return Result;
  292. }
  293. uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
  294. MutexGuard locked(lock);
  295. uint64_t Result = getSymbolAddress(Name, true);
  296. if (Result != 0)
  297. finalizeLoadedModules();
  298. return Result;
  299. }
  300. // Deprecated. Use getFunctionAddress instead.
  301. void *MCJIT::getPointerToFunction(Function *F) {
  302. MutexGuard locked(lock);
  303. Mangler Mang;
  304. SmallString<128> Name;
  305. TM->getNameWithPrefix(Name, F, Mang);
  306. if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
  307. bool AbortOnFailure = !F->hasExternalWeakLinkage();
  308. void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
  309. updateGlobalMapping(F, Addr);
  310. return Addr;
  311. }
  312. Module *M = F->getParent();
  313. bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
  314. // Make sure the relevant module has been compiled and loaded.
  315. if (HasBeenAddedButNotLoaded)
  316. generateCodeForModule(M);
  317. else if (!OwnedModules.hasModuleBeenLoaded(M)) {
  318. // If this function doesn't belong to one of our modules, we're done.
  319. // FIXME: Asking for the pointer to a function that hasn't been registered,
  320. // and isn't a declaration (which is handled above) should probably
  321. // be an assertion.
  322. return nullptr;
  323. }
  324. // FIXME: Should the Dyld be retaining module information? Probably not.
  325. //
  326. // This is the accessor for the target address, so make sure to check the
  327. // load address of the symbol, not the local address.
  328. return (void*)Dyld.getSymbol(Name).getAddress();
  329. }
  330. void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
  331. bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
  332. for (; I != E; ++I) {
  333. ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
  334. }
  335. }
  336. void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
  337. // Execute global ctors/dtors for each module in the program.
  338. runStaticConstructorsDestructorsInModulePtrSet(
  339. isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
  340. runStaticConstructorsDestructorsInModulePtrSet(
  341. isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
  342. runStaticConstructorsDestructorsInModulePtrSet(
  343. isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
  344. }
  345. Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
  346. ModulePtrSet::iterator I,
  347. ModulePtrSet::iterator E) {
  348. for (; I != E; ++I) {
  349. Function *F = (*I)->getFunction(FnName);
  350. if (F && !F->isDeclaration())
  351. return F;
  352. }
  353. return nullptr;
  354. }
  355. GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
  356. bool AllowInternal,
  357. ModulePtrSet::iterator I,
  358. ModulePtrSet::iterator E) {
  359. for (; I != E; ++I) {
  360. GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
  361. if (GV && !GV->isDeclaration())
  362. return GV;
  363. }
  364. return nullptr;
  365. }
  366. Function *MCJIT::FindFunctionNamed(const char *FnName) {
  367. Function *F = FindFunctionNamedInModulePtrSet(
  368. FnName, OwnedModules.begin_added(), OwnedModules.end_added());
  369. if (!F)
  370. F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
  371. OwnedModules.end_loaded());
  372. if (!F)
  373. F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
  374. OwnedModules.end_finalized());
  375. return F;
  376. }
  377. GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
  378. GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
  379. Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
  380. if (!GV)
  381. GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
  382. OwnedModules.end_loaded());
  383. if (!GV)
  384. GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
  385. OwnedModules.end_finalized());
  386. return GV;
  387. }
  388. GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
  389. assert(F && "Function *F was null at entry to run()");
  390. void *FPtr = getPointerToFunction(F);
  391. assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
  392. FunctionType *FTy = F->getFunctionType();
  393. Type *RetTy = FTy->getReturnType();
  394. assert((FTy->getNumParams() == ArgValues.size() ||
  395. (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
  396. "Wrong number of arguments passed into function!");
  397. assert(FTy->getNumParams() == ArgValues.size() &&
  398. "This doesn't support passing arguments through varargs (yet)!");
  399. // Handle some common cases first. These cases correspond to common `main'
  400. // prototypes.
  401. if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
  402. switch (ArgValues.size()) {
  403. case 3:
  404. if (FTy->getParamType(0)->isIntegerTy(32) &&
  405. FTy->getParamType(1)->isPointerTy() &&
  406. FTy->getParamType(2)->isPointerTy()) {
  407. int (*PF)(int, char **, const char **) =
  408. (int(*)(int, char **, const char **))(intptr_t)FPtr;
  409. // Call the function.
  410. GenericValue rv;
  411. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  412. (char **)GVTOP(ArgValues[1]),
  413. (const char **)GVTOP(ArgValues[2])));
  414. return rv;
  415. }
  416. break;
  417. case 2:
  418. if (FTy->getParamType(0)->isIntegerTy(32) &&
  419. FTy->getParamType(1)->isPointerTy()) {
  420. int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
  421. // Call the function.
  422. GenericValue rv;
  423. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  424. (char **)GVTOP(ArgValues[1])));
  425. return rv;
  426. }
  427. break;
  428. case 1:
  429. if (FTy->getNumParams() == 1 &&
  430. FTy->getParamType(0)->isIntegerTy(32)) {
  431. GenericValue rv;
  432. int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
  433. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
  434. return rv;
  435. }
  436. break;
  437. }
  438. }
  439. // Handle cases where no arguments are passed first.
  440. if (ArgValues.empty()) {
  441. GenericValue rv;
  442. switch (RetTy->getTypeID()) {
  443. default: llvm_unreachable("Unknown return type for function call!");
  444. case Type::IntegerTyID: {
  445. unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
  446. if (BitWidth == 1)
  447. rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
  448. else if (BitWidth <= 8)
  449. rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
  450. else if (BitWidth <= 16)
  451. rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
  452. else if (BitWidth <= 32)
  453. rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
  454. else if (BitWidth <= 64)
  455. rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
  456. else
  457. llvm_unreachable("Integer types > 64 bits not supported");
  458. return rv;
  459. }
  460. case Type::VoidTyID:
  461. rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
  462. return rv;
  463. case Type::FloatTyID:
  464. rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
  465. return rv;
  466. case Type::DoubleTyID:
  467. rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
  468. return rv;
  469. case Type::X86_FP80TyID:
  470. case Type::FP128TyID:
  471. case Type::PPC_FP128TyID:
  472. llvm_unreachable("long double not supported yet");
  473. case Type::PointerTyID:
  474. return PTOGV(((void*(*)())(intptr_t)FPtr)());
  475. }
  476. }
  477. llvm_unreachable("Full-featured argument passing not supported yet!");
  478. }
  479. void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
  480. if (!isSymbolSearchingDisabled()) {
  481. void *ptr =
  482. reinterpret_cast<void*>(
  483. static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
  484. if (ptr)
  485. return ptr;
  486. }
  487. /// If a LazyFunctionCreator is installed, use it to get/create the function.
  488. if (LazyFunctionCreator)
  489. if (void *RP = LazyFunctionCreator(Name))
  490. return RP;
  491. if (AbortOnFailure) {
  492. report_fatal_error("Program used external function '"+Name+
  493. "' which could not be resolved!");
  494. }
  495. return nullptr;
  496. }
  497. void MCJIT::RegisterJITEventListener(JITEventListener *L) {
  498. if (!L)
  499. return;
  500. MutexGuard locked(lock);
  501. EventListeners.push_back(L);
  502. }
  503. void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
  504. if (!L)
  505. return;
  506. MutexGuard locked(lock);
  507. auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
  508. if (I != EventListeners.rend()) {
  509. std::swap(*I, EventListeners.back());
  510. EventListeners.pop_back();
  511. }
  512. }
  513. void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
  514. const RuntimeDyld::LoadedObjectInfo &L) {
  515. MutexGuard locked(lock);
  516. MemMgr->notifyObjectLoaded(this, Obj);
  517. for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
  518. EventListeners[I]->NotifyObjectEmitted(Obj, L);
  519. }
  520. }
  521. void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
  522. MutexGuard locked(lock);
  523. for (JITEventListener *L : EventListeners)
  524. L->NotifyFreeingObject(Obj);
  525. }
  526. RuntimeDyld::SymbolInfo
  527. LinkingSymbolResolver::findSymbol(const std::string &Name) {
  528. auto Result = ParentEngine.findSymbol(Name, false);
  529. // If the symbols wasn't found and it begins with an underscore, try again
  530. // without the underscore.
  531. if (!Result && Name[0] == '_')
  532. Result = ParentEngine.findSymbol(Name.substr(1), false);
  533. if (Result)
  534. return Result;
  535. if (ParentEngine.isSymbolSearchingDisabled())
  536. return nullptr;
  537. return ClientResolver->findSymbol(Name);
  538. }