LLJIT.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. //===--------- LLJIT.cpp - An ORC-based JIT for compiling LLVM IR ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ExecutionEngine/Orc/LLJIT.h"
  9. #include "llvm/ExecutionEngine/JITLink/EHFrameSupport.h"
  10. #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
  11. #include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h"
  12. #include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
  13. #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
  14. #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
  15. #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
  16. #include "llvm/ExecutionEngine/Orc/Shared/OrcError.h"
  17. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  18. #include "llvm/IR/GlobalVariable.h"
  19. #include "llvm/IR/IRBuilder.h"
  20. #include "llvm/IR/Mangler.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/Support/DynamicLibrary.h"
  23. #include <map>
  24. #define DEBUG_TYPE "orc"
  25. using namespace llvm;
  26. using namespace llvm::orc;
  27. namespace {
  28. /// Adds helper function decls and wrapper functions that call the helper with
  29. /// some additional prefix arguments.
  30. ///
  31. /// E.g. For wrapper "foo" with type i8(i8, i64), helper "bar", and prefix
  32. /// args i32 4 and i16 12345, this function will add:
  33. ///
  34. /// declare i8 @bar(i32, i16, i8, i64)
  35. ///
  36. /// define i8 @foo(i8, i64) {
  37. /// entry:
  38. /// %2 = call i8 @bar(i32 4, i16 12345, i8 %0, i64 %1)
  39. /// ret i8 %2
  40. /// }
  41. ///
  42. Function *addHelperAndWrapper(Module &M, StringRef WrapperName,
  43. FunctionType *WrapperFnType,
  44. GlobalValue::VisibilityTypes WrapperVisibility,
  45. StringRef HelperName,
  46. ArrayRef<Value *> HelperPrefixArgs) {
  47. std::vector<Type *> HelperArgTypes;
  48. for (auto *Arg : HelperPrefixArgs)
  49. HelperArgTypes.push_back(Arg->getType());
  50. for (auto *T : WrapperFnType->params())
  51. HelperArgTypes.push_back(T);
  52. auto *HelperFnType =
  53. FunctionType::get(WrapperFnType->getReturnType(), HelperArgTypes, false);
  54. auto *HelperFn = Function::Create(HelperFnType, GlobalValue::ExternalLinkage,
  55. HelperName, M);
  56. auto *WrapperFn = Function::Create(
  57. WrapperFnType, GlobalValue::ExternalLinkage, WrapperName, M);
  58. WrapperFn->setVisibility(WrapperVisibility);
  59. auto *EntryBlock = BasicBlock::Create(M.getContext(), "entry", WrapperFn);
  60. IRBuilder<> IB(EntryBlock);
  61. std::vector<Value *> HelperArgs;
  62. for (auto *Arg : HelperPrefixArgs)
  63. HelperArgs.push_back(Arg);
  64. for (auto &Arg : WrapperFn->args())
  65. HelperArgs.push_back(&Arg);
  66. auto *HelperResult = IB.CreateCall(HelperFn, HelperArgs);
  67. if (HelperFn->getReturnType()->isVoidTy())
  68. IB.CreateRetVoid();
  69. else
  70. IB.CreateRet(HelperResult);
  71. return WrapperFn;
  72. }
  73. class GenericLLVMIRPlatformSupport;
  74. /// orc::Platform component of Generic LLVM IR Platform support.
  75. /// Just forwards calls to the GenericLLVMIRPlatformSupport class below.
  76. class GenericLLVMIRPlatform : public Platform {
  77. public:
  78. GenericLLVMIRPlatform(GenericLLVMIRPlatformSupport &S) : S(S) {}
  79. Error setupJITDylib(JITDylib &JD) override;
  80. Error teardownJITDylib(JITDylib &JD) override;
  81. Error notifyAdding(ResourceTracker &RT,
  82. const MaterializationUnit &MU) override;
  83. Error notifyRemoving(ResourceTracker &RT) override {
  84. // Noop -- Nothing to do (yet).
  85. return Error::success();
  86. }
  87. private:
  88. GenericLLVMIRPlatformSupport &S;
  89. };
  90. /// This transform parses llvm.global_ctors to produce a single initialization
  91. /// function for the module, records the function, then deletes
  92. /// llvm.global_ctors.
  93. class GlobalCtorDtorScraper {
  94. public:
  95. GlobalCtorDtorScraper(GenericLLVMIRPlatformSupport &PS,
  96. StringRef InitFunctionPrefix,
  97. StringRef DeInitFunctionPrefix)
  98. : PS(PS), InitFunctionPrefix(InitFunctionPrefix),
  99. DeInitFunctionPrefix(DeInitFunctionPrefix) {}
  100. Expected<ThreadSafeModule> operator()(ThreadSafeModule TSM,
  101. MaterializationResponsibility &R);
  102. private:
  103. GenericLLVMIRPlatformSupport &PS;
  104. StringRef InitFunctionPrefix;
  105. StringRef DeInitFunctionPrefix;
  106. };
  107. /// Generic IR Platform Support
  108. ///
  109. /// Scrapes llvm.global_ctors and llvm.global_dtors and replaces them with
  110. /// specially named 'init' and 'deinit'. Injects definitions / interposes for
  111. /// some runtime API, including __cxa_atexit, dlopen, and dlclose.
  112. class GenericLLVMIRPlatformSupport : public LLJIT::PlatformSupport {
  113. public:
  114. GenericLLVMIRPlatformSupport(LLJIT &J)
  115. : J(J), InitFunctionPrefix(J.mangle("__orc_init_func.")),
  116. DeInitFunctionPrefix(J.mangle("__orc_deinit_func.")) {
  117. getExecutionSession().setPlatform(
  118. std::make_unique<GenericLLVMIRPlatform>(*this));
  119. setInitTransform(J, GlobalCtorDtorScraper(*this, InitFunctionPrefix,
  120. DeInitFunctionPrefix));
  121. SymbolMap StdInterposes;
  122. StdInterposes[J.mangleAndIntern("__lljit.platform_support_instance")] =
  123. JITEvaluatedSymbol(pointerToJITTargetAddress(this),
  124. JITSymbolFlags::Exported);
  125. StdInterposes[J.mangleAndIntern("__lljit.cxa_atexit_helper")] =
  126. JITEvaluatedSymbol(pointerToJITTargetAddress(registerAtExitHelper),
  127. JITSymbolFlags());
  128. cantFail(
  129. J.getMainJITDylib().define(absoluteSymbols(std::move(StdInterposes))));
  130. cantFail(setupJITDylib(J.getMainJITDylib()));
  131. cantFail(J.addIRModule(J.getMainJITDylib(), createPlatformRuntimeModule()));
  132. }
  133. ExecutionSession &getExecutionSession() { return J.getExecutionSession(); }
  134. /// Adds a module that defines the __dso_handle global.
  135. Error setupJITDylib(JITDylib &JD) {
  136. // Add per-jitdylib standard interposes.
  137. SymbolMap PerJDInterposes;
  138. PerJDInterposes[J.mangleAndIntern("__lljit.run_atexits_helper")] =
  139. JITEvaluatedSymbol(pointerToJITTargetAddress(runAtExitsHelper),
  140. JITSymbolFlags());
  141. cantFail(JD.define(absoluteSymbols(std::move(PerJDInterposes))));
  142. auto Ctx = std::make_unique<LLVMContext>();
  143. auto M = std::make_unique<Module>("__standard_lib", *Ctx);
  144. M->setDataLayout(J.getDataLayout());
  145. auto *Int64Ty = Type::getInt64Ty(*Ctx);
  146. auto *DSOHandle = new GlobalVariable(
  147. *M, Int64Ty, true, GlobalValue::ExternalLinkage,
  148. ConstantInt::get(Int64Ty, reinterpret_cast<uintptr_t>(&JD)),
  149. "__dso_handle");
  150. DSOHandle->setVisibility(GlobalValue::DefaultVisibility);
  151. DSOHandle->setInitializer(
  152. ConstantInt::get(Int64Ty, pointerToJITTargetAddress(&JD)));
  153. auto *GenericIRPlatformSupportTy =
  154. StructType::create(*Ctx, "lljit.GenericLLJITIRPlatformSupport");
  155. auto *PlatformInstanceDecl = new GlobalVariable(
  156. *M, GenericIRPlatformSupportTy, true, GlobalValue::ExternalLinkage,
  157. nullptr, "__lljit.platform_support_instance");
  158. auto *VoidTy = Type::getVoidTy(*Ctx);
  159. addHelperAndWrapper(
  160. *M, "__lljit_run_atexits", FunctionType::get(VoidTy, {}, false),
  161. GlobalValue::HiddenVisibility, "__lljit.run_atexits_helper",
  162. {PlatformInstanceDecl, DSOHandle});
  163. return J.addIRModule(JD, ThreadSafeModule(std::move(M), std::move(Ctx)));
  164. }
  165. Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU) {
  166. auto &JD = RT.getJITDylib();
  167. if (auto &InitSym = MU.getInitializerSymbol())
  168. InitSymbols[&JD].add(InitSym, SymbolLookupFlags::WeaklyReferencedSymbol);
  169. else {
  170. // If there's no identified init symbol attached, but there is a symbol
  171. // with the GenericIRPlatform::InitFunctionPrefix, then treat that as
  172. // an init function. Add the symbol to both the InitSymbols map (which
  173. // will trigger a lookup to materialize the module) and the InitFunctions
  174. // map (which holds the names of the symbols to execute).
  175. for (auto &KV : MU.getSymbols())
  176. if ((*KV.first).startswith(InitFunctionPrefix)) {
  177. InitSymbols[&JD].add(KV.first,
  178. SymbolLookupFlags::WeaklyReferencedSymbol);
  179. InitFunctions[&JD].add(KV.first);
  180. } else if ((*KV.first).startswith(DeInitFunctionPrefix)) {
  181. DeInitFunctions[&JD].add(KV.first);
  182. }
  183. }
  184. return Error::success();
  185. }
  186. Error initialize(JITDylib &JD) override {
  187. LLVM_DEBUG({
  188. dbgs() << "GenericLLVMIRPlatformSupport getting initializers to run\n";
  189. });
  190. if (auto Initializers = getInitializers(JD)) {
  191. LLVM_DEBUG(
  192. { dbgs() << "GenericLLVMIRPlatformSupport running initializers\n"; });
  193. for (auto InitFnAddr : *Initializers) {
  194. LLVM_DEBUG({
  195. dbgs() << " Running init " << formatv("{0:x16}", InitFnAddr)
  196. << "...\n";
  197. });
  198. auto *InitFn = jitTargetAddressToFunction<void (*)()>(InitFnAddr);
  199. InitFn();
  200. }
  201. } else
  202. return Initializers.takeError();
  203. return Error::success();
  204. }
  205. Error deinitialize(JITDylib &JD) override {
  206. LLVM_DEBUG({
  207. dbgs() << "GenericLLVMIRPlatformSupport getting deinitializers to run\n";
  208. });
  209. if (auto Deinitializers = getDeinitializers(JD)) {
  210. LLVM_DEBUG({
  211. dbgs() << "GenericLLVMIRPlatformSupport running deinitializers\n";
  212. });
  213. for (auto DeinitFnAddr : *Deinitializers) {
  214. LLVM_DEBUG({
  215. dbgs() << " Running deinit " << formatv("{0:x16}", DeinitFnAddr)
  216. << "...\n";
  217. });
  218. auto *DeinitFn = jitTargetAddressToFunction<void (*)()>(DeinitFnAddr);
  219. DeinitFn();
  220. }
  221. } else
  222. return Deinitializers.takeError();
  223. return Error::success();
  224. }
  225. void registerInitFunc(JITDylib &JD, SymbolStringPtr InitName) {
  226. getExecutionSession().runSessionLocked([&]() {
  227. InitFunctions[&JD].add(InitName);
  228. });
  229. }
  230. void registerDeInitFunc(JITDylib &JD, SymbolStringPtr DeInitName) {
  231. getExecutionSession().runSessionLocked(
  232. [&]() { DeInitFunctions[&JD].add(DeInitName); });
  233. }
  234. private:
  235. Expected<std::vector<JITTargetAddress>> getInitializers(JITDylib &JD) {
  236. if (auto Err = issueInitLookups(JD))
  237. return std::move(Err);
  238. DenseMap<JITDylib *, SymbolLookupSet> LookupSymbols;
  239. std::vector<JITDylibSP> DFSLinkOrder;
  240. if (auto Err = getExecutionSession().runSessionLocked([&]() -> Error {
  241. if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder())
  242. DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
  243. else
  244. return DFSLinkOrderOrErr.takeError();
  245. for (auto &NextJD : DFSLinkOrder) {
  246. auto IFItr = InitFunctions.find(NextJD.get());
  247. if (IFItr != InitFunctions.end()) {
  248. LookupSymbols[NextJD.get()] = std::move(IFItr->second);
  249. InitFunctions.erase(IFItr);
  250. }
  251. }
  252. return Error::success();
  253. }))
  254. return std::move(Err);
  255. LLVM_DEBUG({
  256. dbgs() << "JITDylib init order is [ ";
  257. for (auto &JD : llvm::reverse(DFSLinkOrder))
  258. dbgs() << "\"" << JD->getName() << "\" ";
  259. dbgs() << "]\n";
  260. dbgs() << "Looking up init functions:\n";
  261. for (auto &KV : LookupSymbols)
  262. dbgs() << " \"" << KV.first->getName() << "\": " << KV.second << "\n";
  263. });
  264. auto &ES = getExecutionSession();
  265. auto LookupResult = Platform::lookupInitSymbols(ES, LookupSymbols);
  266. if (!LookupResult)
  267. return LookupResult.takeError();
  268. std::vector<JITTargetAddress> Initializers;
  269. while (!DFSLinkOrder.empty()) {
  270. auto &NextJD = *DFSLinkOrder.back();
  271. DFSLinkOrder.pop_back();
  272. auto InitsItr = LookupResult->find(&NextJD);
  273. if (InitsItr == LookupResult->end())
  274. continue;
  275. for (auto &KV : InitsItr->second)
  276. Initializers.push_back(KV.second.getAddress());
  277. }
  278. return Initializers;
  279. }
  280. Expected<std::vector<JITTargetAddress>> getDeinitializers(JITDylib &JD) {
  281. auto &ES = getExecutionSession();
  282. auto LLJITRunAtExits = J.mangleAndIntern("__lljit_run_atexits");
  283. DenseMap<JITDylib *, SymbolLookupSet> LookupSymbols;
  284. std::vector<JITDylibSP> DFSLinkOrder;
  285. if (auto Err = ES.runSessionLocked([&]() -> Error {
  286. if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder())
  287. DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
  288. else
  289. return DFSLinkOrderOrErr.takeError();
  290. for (auto &NextJD : DFSLinkOrder) {
  291. auto &JDLookupSymbols = LookupSymbols[NextJD.get()];
  292. auto DIFItr = DeInitFunctions.find(NextJD.get());
  293. if (DIFItr != DeInitFunctions.end()) {
  294. LookupSymbols[NextJD.get()] = std::move(DIFItr->second);
  295. DeInitFunctions.erase(DIFItr);
  296. }
  297. JDLookupSymbols.add(LLJITRunAtExits,
  298. SymbolLookupFlags::WeaklyReferencedSymbol);
  299. }
  300. return Error::success();
  301. }))
  302. return std::move(Err);
  303. LLVM_DEBUG({
  304. dbgs() << "JITDylib deinit order is [ ";
  305. for (auto &JD : DFSLinkOrder)
  306. dbgs() << "\"" << JD->getName() << "\" ";
  307. dbgs() << "]\n";
  308. dbgs() << "Looking up deinit functions:\n";
  309. for (auto &KV : LookupSymbols)
  310. dbgs() << " \"" << KV.first->getName() << "\": " << KV.second << "\n";
  311. });
  312. auto LookupResult = Platform::lookupInitSymbols(ES, LookupSymbols);
  313. if (!LookupResult)
  314. return LookupResult.takeError();
  315. std::vector<JITTargetAddress> DeInitializers;
  316. for (auto &NextJD : DFSLinkOrder) {
  317. auto DeInitsItr = LookupResult->find(NextJD.get());
  318. assert(DeInitsItr != LookupResult->end() &&
  319. "Every JD should have at least __lljit_run_atexits");
  320. auto RunAtExitsItr = DeInitsItr->second.find(LLJITRunAtExits);
  321. if (RunAtExitsItr != DeInitsItr->second.end())
  322. DeInitializers.push_back(RunAtExitsItr->second.getAddress());
  323. for (auto &KV : DeInitsItr->second)
  324. if (KV.first != LLJITRunAtExits)
  325. DeInitializers.push_back(KV.second.getAddress());
  326. }
  327. return DeInitializers;
  328. }
  329. /// Issue lookups for all init symbols required to initialize JD (and any
  330. /// JITDylibs that it depends on).
  331. Error issueInitLookups(JITDylib &JD) {
  332. DenseMap<JITDylib *, SymbolLookupSet> RequiredInitSymbols;
  333. std::vector<JITDylibSP> DFSLinkOrder;
  334. if (auto Err = getExecutionSession().runSessionLocked([&]() -> Error {
  335. if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder())
  336. DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
  337. else
  338. return DFSLinkOrderOrErr.takeError();
  339. for (auto &NextJD : DFSLinkOrder) {
  340. auto ISItr = InitSymbols.find(NextJD.get());
  341. if (ISItr != InitSymbols.end()) {
  342. RequiredInitSymbols[NextJD.get()] = std::move(ISItr->second);
  343. InitSymbols.erase(ISItr);
  344. }
  345. }
  346. return Error::success();
  347. }))
  348. return Err;
  349. return Platform::lookupInitSymbols(getExecutionSession(),
  350. RequiredInitSymbols)
  351. .takeError();
  352. }
  353. static void registerAtExitHelper(void *Self, void (*F)(void *), void *Ctx,
  354. void *DSOHandle) {
  355. LLVM_DEBUG({
  356. dbgs() << "Registering atexit function " << (void *)F << " for JD "
  357. << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n";
  358. });
  359. static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.registerAtExit(
  360. F, Ctx, DSOHandle);
  361. }
  362. static void runAtExitsHelper(void *Self, void *DSOHandle) {
  363. LLVM_DEBUG({
  364. dbgs() << "Running atexit functions for JD "
  365. << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n";
  366. });
  367. static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.runAtExits(
  368. DSOHandle);
  369. }
  370. // Constructs an LLVM IR module containing platform runtime globals,
  371. // functions, and interposes.
  372. ThreadSafeModule createPlatformRuntimeModule() {
  373. auto Ctx = std::make_unique<LLVMContext>();
  374. auto M = std::make_unique<Module>("__standard_lib", *Ctx);
  375. M->setDataLayout(J.getDataLayout());
  376. auto *GenericIRPlatformSupportTy =
  377. StructType::create(*Ctx, "lljit.GenericLLJITIRPlatformSupport");
  378. auto *PlatformInstanceDecl = new GlobalVariable(
  379. *M, GenericIRPlatformSupportTy, true, GlobalValue::ExternalLinkage,
  380. nullptr, "__lljit.platform_support_instance");
  381. auto *Int8Ty = Type::getInt8Ty(*Ctx);
  382. auto *IntTy = Type::getIntNTy(*Ctx, sizeof(int) * CHAR_BIT);
  383. auto *VoidTy = Type::getVoidTy(*Ctx);
  384. auto *BytePtrTy = PointerType::getUnqual(Int8Ty);
  385. auto *AtExitCallbackTy = FunctionType::get(VoidTy, {BytePtrTy}, false);
  386. auto *AtExitCallbackPtrTy = PointerType::getUnqual(AtExitCallbackTy);
  387. addHelperAndWrapper(
  388. *M, "__cxa_atexit",
  389. FunctionType::get(IntTy, {AtExitCallbackPtrTy, BytePtrTy, BytePtrTy},
  390. false),
  391. GlobalValue::DefaultVisibility, "__lljit.cxa_atexit_helper",
  392. {PlatformInstanceDecl});
  393. return ThreadSafeModule(std::move(M), std::move(Ctx));
  394. }
  395. LLJIT &J;
  396. std::string InitFunctionPrefix;
  397. std::string DeInitFunctionPrefix;
  398. DenseMap<JITDylib *, SymbolLookupSet> InitSymbols;
  399. DenseMap<JITDylib *, SymbolLookupSet> InitFunctions;
  400. DenseMap<JITDylib *, SymbolLookupSet> DeInitFunctions;
  401. ItaniumCXAAtExitSupport AtExitMgr;
  402. };
  403. Error GenericLLVMIRPlatform::setupJITDylib(JITDylib &JD) {
  404. return S.setupJITDylib(JD);
  405. }
  406. Error GenericLLVMIRPlatform::teardownJITDylib(JITDylib &JD) {
  407. return Error::success();
  408. }
  409. Error GenericLLVMIRPlatform::notifyAdding(ResourceTracker &RT,
  410. const MaterializationUnit &MU) {
  411. return S.notifyAdding(RT, MU);
  412. }
  413. Expected<ThreadSafeModule>
  414. GlobalCtorDtorScraper::operator()(ThreadSafeModule TSM,
  415. MaterializationResponsibility &R) {
  416. auto Err = TSM.withModuleDo([&](Module &M) -> Error {
  417. auto &Ctx = M.getContext();
  418. auto *GlobalCtors = M.getNamedGlobal("llvm.global_ctors");
  419. auto *GlobalDtors = M.getNamedGlobal("llvm.global_dtors");
  420. auto RegisterCOrDtors = [&](GlobalVariable *GlobalCOrDtors,
  421. bool isCtor) -> Error {
  422. // If there's no llvm.global_c/dtor or it's just a decl then skip.
  423. if (!GlobalCOrDtors || GlobalCOrDtors->isDeclaration())
  424. return Error::success();
  425. std::string InitOrDeInitFunctionName;
  426. if (isCtor)
  427. raw_string_ostream(InitOrDeInitFunctionName)
  428. << InitFunctionPrefix << M.getModuleIdentifier();
  429. else
  430. raw_string_ostream(InitOrDeInitFunctionName)
  431. << DeInitFunctionPrefix << M.getModuleIdentifier();
  432. MangleAndInterner Mangle(PS.getExecutionSession(), M.getDataLayout());
  433. auto InternedInitOrDeInitName = Mangle(InitOrDeInitFunctionName);
  434. if (auto Err = R.defineMaterializing(
  435. {{InternedInitOrDeInitName, JITSymbolFlags::Callable}}))
  436. return Err;
  437. auto *InitOrDeInitFunc = Function::Create(
  438. FunctionType::get(Type::getVoidTy(Ctx), {}, false),
  439. GlobalValue::ExternalLinkage, InitOrDeInitFunctionName, &M);
  440. InitOrDeInitFunc->setVisibility(GlobalValue::HiddenVisibility);
  441. std::vector<std::pair<Function *, unsigned>> InitsOrDeInits;
  442. auto COrDtors = isCtor ? getConstructors(M) : getDestructors(M);
  443. for (auto E : COrDtors)
  444. InitsOrDeInits.push_back(std::make_pair(E.Func, E.Priority));
  445. llvm::sort(InitsOrDeInits,
  446. [](const std::pair<Function *, unsigned> &LHS,
  447. const std::pair<Function *, unsigned> &RHS) {
  448. return LHS.first < RHS.first;
  449. });
  450. auto *InitOrDeInitFuncEntryBlock =
  451. BasicBlock::Create(Ctx, "entry", InitOrDeInitFunc);
  452. IRBuilder<> IB(InitOrDeInitFuncEntryBlock);
  453. for (auto &KV : InitsOrDeInits)
  454. IB.CreateCall(KV.first);
  455. IB.CreateRetVoid();
  456. if (isCtor)
  457. PS.registerInitFunc(R.getTargetJITDylib(), InternedInitOrDeInitName);
  458. else
  459. PS.registerDeInitFunc(R.getTargetJITDylib(), InternedInitOrDeInitName);
  460. GlobalCOrDtors->eraseFromParent();
  461. return Error::success();
  462. };
  463. if (auto Err = RegisterCOrDtors(GlobalCtors, true))
  464. return Err;
  465. if (auto Err = RegisterCOrDtors(GlobalDtors, false))
  466. return Err;
  467. return Error::success();
  468. });
  469. if (Err)
  470. return std::move(Err);
  471. return std::move(TSM);
  472. }
  473. /// Inactive Platform Support
  474. ///
  475. /// Explicitly disables platform support. JITDylibs are not scanned for special
  476. /// init/deinit symbols. No runtime API interposes are injected.
  477. class InactivePlatformSupport : public LLJIT::PlatformSupport {
  478. public:
  479. InactivePlatformSupport() = default;
  480. Error initialize(JITDylib &JD) override {
  481. LLVM_DEBUG(dbgs() << "InactivePlatformSupport: no initializers running for "
  482. << JD.getName() << "\n");
  483. return Error::success();
  484. }
  485. Error deinitialize(JITDylib &JD) override {
  486. LLVM_DEBUG(
  487. dbgs() << "InactivePlatformSupport: no deinitializers running for "
  488. << JD.getName() << "\n");
  489. return Error::success();
  490. }
  491. };
  492. } // end anonymous namespace
  493. namespace llvm {
  494. namespace orc {
  495. void LLJIT::PlatformSupport::setInitTransform(
  496. LLJIT &J, IRTransformLayer::TransformFunction T) {
  497. J.InitHelperTransformLayer->setTransform(std::move(T));
  498. }
  499. LLJIT::PlatformSupport::~PlatformSupport() {}
  500. Error LLJITBuilderState::prepareForConstruction() {
  501. LLVM_DEBUG(dbgs() << "Preparing to create LLJIT instance...\n");
  502. if (!JTMB) {
  503. LLVM_DEBUG({
  504. dbgs() << " No explicitly set JITTargetMachineBuilder. "
  505. "Detecting host...\n";
  506. });
  507. if (auto JTMBOrErr = JITTargetMachineBuilder::detectHost())
  508. JTMB = std::move(*JTMBOrErr);
  509. else
  510. return JTMBOrErr.takeError();
  511. }
  512. LLVM_DEBUG({
  513. dbgs() << " JITTargetMachineBuilder is "
  514. << JITTargetMachineBuilderPrinter(*JTMB, " ")
  515. << " Pre-constructed ExecutionSession: " << (ES ? "Yes" : "No")
  516. << "\n"
  517. << " DataLayout: ";
  518. if (DL)
  519. dbgs() << DL->getStringRepresentation() << "\n";
  520. else
  521. dbgs() << "None (will be created by JITTargetMachineBuilder)\n";
  522. dbgs() << " Custom object-linking-layer creator: "
  523. << (CreateObjectLinkingLayer ? "Yes" : "No") << "\n"
  524. << " Custom compile-function creator: "
  525. << (CreateCompileFunction ? "Yes" : "No") << "\n"
  526. << " Custom platform-setup function: "
  527. << (SetUpPlatform ? "Yes" : "No") << "\n"
  528. << " Number of compile threads: " << NumCompileThreads;
  529. if (!NumCompileThreads)
  530. dbgs() << " (code will be compiled on the execution thread)\n";
  531. else
  532. dbgs() << "\n";
  533. });
  534. // If neither ES nor EPC has been set then create an EPC instance.
  535. if (!ES && !EPC) {
  536. LLVM_DEBUG({
  537. dbgs() << "ExecutorProcessControl not specified, "
  538. "Creating SelfExecutorProcessControl instance\n";
  539. });
  540. if (auto EPCOrErr = SelfExecutorProcessControl::Create())
  541. EPC = std::move(*EPCOrErr);
  542. else
  543. return EPCOrErr.takeError();
  544. } else
  545. LLVM_DEBUG({
  546. dbgs() << "Using explicitly specified ExecutorProcessControl instance "
  547. << EPC.get() << "\n";
  548. });
  549. // If the client didn't configure any linker options then auto-configure the
  550. // JIT linker.
  551. if (!CreateObjectLinkingLayer) {
  552. auto &TT = JTMB->getTargetTriple();
  553. if (TT.isOSBinFormatMachO() &&
  554. (TT.getArch() == Triple::aarch64 || TT.getArch() == Triple::x86_64)) {
  555. JTMB->setRelocationModel(Reloc::PIC_);
  556. JTMB->setCodeModel(CodeModel::Small);
  557. CreateObjectLinkingLayer =
  558. [](ExecutionSession &ES,
  559. const Triple &) -> Expected<std::unique_ptr<ObjectLayer>> {
  560. auto ObjLinkingLayer = std::make_unique<ObjectLinkingLayer>(ES);
  561. ObjLinkingLayer->addPlugin(std::make_unique<EHFrameRegistrationPlugin>(
  562. ES, std::make_unique<jitlink::InProcessEHFrameRegistrar>()));
  563. return std::move(ObjLinkingLayer);
  564. };
  565. }
  566. }
  567. return Error::success();
  568. }
  569. LLJIT::~LLJIT() {
  570. if (CompileThreads)
  571. CompileThreads->wait();
  572. if (auto Err = ES->endSession())
  573. ES->reportError(std::move(Err));
  574. }
  575. Error LLJIT::addIRModule(ResourceTrackerSP RT, ThreadSafeModule TSM) {
  576. assert(TSM && "Can not add null module");
  577. if (auto Err =
  578. TSM.withModuleDo([&](Module &M) { return applyDataLayout(M); }))
  579. return Err;
  580. return InitHelperTransformLayer->add(std::move(RT), std::move(TSM));
  581. }
  582. Error LLJIT::addIRModule(JITDylib &JD, ThreadSafeModule TSM) {
  583. return addIRModule(JD.getDefaultResourceTracker(), std::move(TSM));
  584. }
  585. Error LLJIT::addObjectFile(ResourceTrackerSP RT,
  586. std::unique_ptr<MemoryBuffer> Obj) {
  587. assert(Obj && "Can not add null object");
  588. return ObjTransformLayer->add(std::move(RT), std::move(Obj));
  589. }
  590. Error LLJIT::addObjectFile(JITDylib &JD, std::unique_ptr<MemoryBuffer> Obj) {
  591. return addObjectFile(JD.getDefaultResourceTracker(), std::move(Obj));
  592. }
  593. Expected<JITEvaluatedSymbol> LLJIT::lookupLinkerMangled(JITDylib &JD,
  594. SymbolStringPtr Name) {
  595. return ES->lookup(
  596. makeJITDylibSearchOrder(&JD, JITDylibLookupFlags::MatchAllSymbols), Name);
  597. }
  598. Expected<std::unique_ptr<ObjectLayer>>
  599. LLJIT::createObjectLinkingLayer(LLJITBuilderState &S, ExecutionSession &ES) {
  600. // If the config state provided an ObjectLinkingLayer factory then use it.
  601. if (S.CreateObjectLinkingLayer)
  602. return S.CreateObjectLinkingLayer(ES, S.JTMB->getTargetTriple());
  603. // Otherwise default to creating an RTDyldObjectLinkingLayer that constructs
  604. // a new SectionMemoryManager for each object.
  605. auto GetMemMgr = []() { return std::make_unique<SectionMemoryManager>(); };
  606. auto Layer =
  607. std::make_unique<RTDyldObjectLinkingLayer>(ES, std::move(GetMemMgr));
  608. if (S.JTMB->getTargetTriple().isOSBinFormatCOFF()) {
  609. Layer->setOverrideObjectFlagsWithResponsibilityFlags(true);
  610. Layer->setAutoClaimResponsibilityForObjectSymbols(true);
  611. }
  612. // FIXME: Explicit conversion to std::unique_ptr<ObjectLayer> added to silence
  613. // errors from some GCC / libstdc++ bots. Remove this conversion (i.e.
  614. // just return ObjLinkingLayer) once those bots are upgraded.
  615. return std::unique_ptr<ObjectLayer>(std::move(Layer));
  616. }
  617. Expected<std::unique_ptr<IRCompileLayer::IRCompiler>>
  618. LLJIT::createCompileFunction(LLJITBuilderState &S,
  619. JITTargetMachineBuilder JTMB) {
  620. /// If there is a custom compile function creator set then use it.
  621. if (S.CreateCompileFunction)
  622. return S.CreateCompileFunction(std::move(JTMB));
  623. // Otherwise default to creating a SimpleCompiler, or ConcurrentIRCompiler,
  624. // depending on the number of threads requested.
  625. if (S.NumCompileThreads > 0)
  626. return std::make_unique<ConcurrentIRCompiler>(std::move(JTMB));
  627. auto TM = JTMB.createTargetMachine();
  628. if (!TM)
  629. return TM.takeError();
  630. return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM));
  631. }
  632. LLJIT::LLJIT(LLJITBuilderState &S, Error &Err)
  633. : DL(""), TT(S.JTMB->getTargetTriple()) {
  634. ErrorAsOutParameter _(&Err);
  635. assert(!(S.EPC && S.ES) && "EPC and ES should not both be set");
  636. if (S.EPC) {
  637. ES = std::make_unique<ExecutionSession>(std::move(S.EPC));
  638. } else if (S.ES)
  639. ES = std::move(S.ES);
  640. else {
  641. if (auto EPC = SelfExecutorProcessControl::Create()) {
  642. ES = std::make_unique<ExecutionSession>(std::move(*EPC));
  643. } else {
  644. Err = EPC.takeError();
  645. return;
  646. }
  647. }
  648. if (auto MainOrErr = this->ES->createJITDylib("main"))
  649. Main = &*MainOrErr;
  650. else {
  651. Err = MainOrErr.takeError();
  652. return;
  653. }
  654. if (S.DL)
  655. DL = std::move(*S.DL);
  656. else if (auto DLOrErr = S.JTMB->getDefaultDataLayoutForTarget())
  657. DL = std::move(*DLOrErr);
  658. else {
  659. Err = DLOrErr.takeError();
  660. return;
  661. }
  662. auto ObjLayer = createObjectLinkingLayer(S, *ES);
  663. if (!ObjLayer) {
  664. Err = ObjLayer.takeError();
  665. return;
  666. }
  667. ObjLinkingLayer = std::move(*ObjLayer);
  668. ObjTransformLayer =
  669. std::make_unique<ObjectTransformLayer>(*ES, *ObjLinkingLayer);
  670. {
  671. auto CompileFunction = createCompileFunction(S, std::move(*S.JTMB));
  672. if (!CompileFunction) {
  673. Err = CompileFunction.takeError();
  674. return;
  675. }
  676. CompileLayer = std::make_unique<IRCompileLayer>(
  677. *ES, *ObjTransformLayer, std::move(*CompileFunction));
  678. TransformLayer = std::make_unique<IRTransformLayer>(*ES, *CompileLayer);
  679. InitHelperTransformLayer =
  680. std::make_unique<IRTransformLayer>(*ES, *TransformLayer);
  681. }
  682. if (S.NumCompileThreads > 0) {
  683. InitHelperTransformLayer->setCloneToNewContextOnEmit(true);
  684. CompileThreads =
  685. std::make_unique<ThreadPool>(hardware_concurrency(S.NumCompileThreads));
  686. ES->setDispatchTask([this](std::unique_ptr<Task> T) {
  687. // FIXME: We should be able to use move-capture here, but ThreadPool's
  688. // AsyncTaskTys are std::functions rather than unique_functions
  689. // (because MSVC's std::packaged_tasks don't support move-only types).
  690. // Fix this when all the above gets sorted out.
  691. CompileThreads->async([UnownedT = T.release()]() mutable {
  692. std::unique_ptr<Task> T(UnownedT);
  693. T->run();
  694. });
  695. });
  696. }
  697. if (S.SetUpPlatform)
  698. Err = S.SetUpPlatform(*this);
  699. else
  700. setUpGenericLLVMIRPlatform(*this);
  701. }
  702. std::string LLJIT::mangle(StringRef UnmangledName) const {
  703. std::string MangledName;
  704. {
  705. raw_string_ostream MangledNameStream(MangledName);
  706. Mangler::getNameWithPrefix(MangledNameStream, UnmangledName, DL);
  707. }
  708. return MangledName;
  709. }
  710. Error LLJIT::applyDataLayout(Module &M) {
  711. if (M.getDataLayout().isDefault())
  712. M.setDataLayout(DL);
  713. if (M.getDataLayout() != DL)
  714. return make_error<StringError>(
  715. "Added modules have incompatible data layouts: " +
  716. M.getDataLayout().getStringRepresentation() + " (module) vs " +
  717. DL.getStringRepresentation() + " (jit)",
  718. inconvertibleErrorCode());
  719. return Error::success();
  720. }
  721. void setUpGenericLLVMIRPlatform(LLJIT &J) {
  722. LLVM_DEBUG(
  723. { dbgs() << "Setting up GenericLLVMIRPlatform support for LLJIT\n"; });
  724. J.setPlatformSupport(std::make_unique<GenericLLVMIRPlatformSupport>(J));
  725. }
  726. Error setUpInactivePlatform(LLJIT &J) {
  727. LLVM_DEBUG(
  728. { dbgs() << "Explicitly deactivated platform support for LLJIT\n"; });
  729. J.setPlatformSupport(std::make_unique<InactivePlatformSupport>());
  730. return Error::success();
  731. }
  732. Error LLLazyJITBuilderState::prepareForConstruction() {
  733. if (auto Err = LLJITBuilderState::prepareForConstruction())
  734. return Err;
  735. TT = JTMB->getTargetTriple();
  736. return Error::success();
  737. }
  738. Error LLLazyJIT::addLazyIRModule(JITDylib &JD, ThreadSafeModule TSM) {
  739. assert(TSM && "Can not add null module");
  740. if (auto Err = TSM.withModuleDo(
  741. [&](Module &M) -> Error { return applyDataLayout(M); }))
  742. return Err;
  743. return CODLayer->add(JD, std::move(TSM));
  744. }
  745. LLLazyJIT::LLLazyJIT(LLLazyJITBuilderState &S, Error &Err) : LLJIT(S, Err) {
  746. // If LLJIT construction failed then bail out.
  747. if (Err)
  748. return;
  749. ErrorAsOutParameter _(&Err);
  750. /// Take/Create the lazy-compile callthrough manager.
  751. if (S.LCTMgr)
  752. LCTMgr = std::move(S.LCTMgr);
  753. else {
  754. if (auto LCTMgrOrErr = createLocalLazyCallThroughManager(
  755. S.TT, *ES, S.LazyCompileFailureAddr))
  756. LCTMgr = std::move(*LCTMgrOrErr);
  757. else {
  758. Err = LCTMgrOrErr.takeError();
  759. return;
  760. }
  761. }
  762. // Take/Create the indirect stubs manager builder.
  763. auto ISMBuilder = std::move(S.ISMBuilder);
  764. // If none was provided, try to build one.
  765. if (!ISMBuilder)
  766. ISMBuilder = createLocalIndirectStubsManagerBuilder(S.TT);
  767. // No luck. Bail out.
  768. if (!ISMBuilder) {
  769. Err = make_error<StringError>("Could not construct "
  770. "IndirectStubsManagerBuilder for target " +
  771. S.TT.str(),
  772. inconvertibleErrorCode());
  773. return;
  774. }
  775. // Create the COD layer.
  776. CODLayer = std::make_unique<CompileOnDemandLayer>(
  777. *ES, *InitHelperTransformLayer, *LCTMgr, std::move(ISMBuilder));
  778. if (S.NumCompileThreads > 0)
  779. CODLayer->setCloneToNewContextOnEmit(true);
  780. }
  781. } // End namespace orc.
  782. } // End namespace llvm.