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 9 #include "llvm/ExecutionEngine/Orc/LLJIT.h" 10 #include "llvm/ExecutionEngine/JITLink/EHFrameSupport.h" 11 #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h" 12 #include "llvm/ExecutionEngine/Orc/COFFPlatform.h" 13 #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h" 14 #include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h" 15 #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h" 16 #include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h" 17 #include "llvm/ExecutionEngine/Orc/MachOPlatform.h" 18 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h" 19 #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h" 20 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 21 #include "llvm/ExecutionEngine/Orc/Shared/OrcError.h" 22 #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h" 23 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 24 #include "llvm/IR/GlobalVariable.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/Mangler.h" 27 #include "llvm/IR/Module.h" 28 #include "llvm/Support/DynamicLibrary.h" 29 30 #define DEBUG_TYPE "orc" 31 32 using namespace llvm; 33 using namespace llvm::orc; 34 35 namespace { 36 37 /// Adds helper function decls and wrapper functions that call the helper with 38 /// some additional prefix arguments. 39 /// 40 /// E.g. For wrapper "foo" with type i8(i8, i64), helper "bar", and prefix 41 /// args i32 4 and i16 12345, this function will add: 42 /// 43 /// declare i8 @bar(i32, i16, i8, i64) 44 /// 45 /// define i8 @foo(i8, i64) { 46 /// entry: 47 /// %2 = call i8 @bar(i32 4, i16 12345, i8 %0, i64 %1) 48 /// ret i8 %2 49 /// } 50 /// 51 Function *addHelperAndWrapper(Module &M, StringRef WrapperName, 52 FunctionType *WrapperFnType, 53 GlobalValue::VisibilityTypes WrapperVisibility, 54 StringRef HelperName, 55 ArrayRef<Value *> HelperPrefixArgs) { 56 std::vector<Type *> HelperArgTypes; 57 for (auto *Arg : HelperPrefixArgs) 58 HelperArgTypes.push_back(Arg->getType()); 59 for (auto *T : WrapperFnType->params()) 60 HelperArgTypes.push_back(T); 61 auto *HelperFnType = 62 FunctionType::get(WrapperFnType->getReturnType(), HelperArgTypes, false); 63 auto *HelperFn = Function::Create(HelperFnType, GlobalValue::ExternalLinkage, 64 HelperName, M); 65 66 auto *WrapperFn = Function::Create( 67 WrapperFnType, GlobalValue::ExternalLinkage, WrapperName, M); 68 WrapperFn->setVisibility(WrapperVisibility); 69 70 auto *EntryBlock = BasicBlock::Create(M.getContext(), "entry", WrapperFn); 71 IRBuilder<> IB(EntryBlock); 72 73 std::vector<Value *> HelperArgs; 74 for (auto *Arg : HelperPrefixArgs) 75 HelperArgs.push_back(Arg); 76 for (auto &Arg : WrapperFn->args()) 77 HelperArgs.push_back(&Arg); 78 auto *HelperResult = IB.CreateCall(HelperFn, HelperArgs); 79 if (HelperFn->getReturnType()->isVoidTy()) 80 IB.CreateRetVoid(); 81 else 82 IB.CreateRet(HelperResult); 83 84 return WrapperFn; 85 } 86 87 class GenericLLVMIRPlatformSupport; 88 89 /// orc::Platform component of Generic LLVM IR Platform support. 90 /// Just forwards calls to the GenericLLVMIRPlatformSupport class below. 91 class GenericLLVMIRPlatform : public Platform { 92 public: 93 GenericLLVMIRPlatform(GenericLLVMIRPlatformSupport &S) : S(S) {} 94 Error setupJITDylib(JITDylib &JD) override; 95 Error teardownJITDylib(JITDylib &JD) override; 96 Error notifyAdding(ResourceTracker &RT, 97 const MaterializationUnit &MU) override; 98 Error notifyRemoving(ResourceTracker &RT) override { 99 // Noop -- Nothing to do (yet). 100 return Error::success(); 101 } 102 103 private: 104 GenericLLVMIRPlatformSupport &S; 105 }; 106 107 /// This transform parses llvm.global_ctors to produce a single initialization 108 /// function for the module, records the function, then deletes 109 /// llvm.global_ctors. 110 class GlobalCtorDtorScraper { 111 public: 112 GlobalCtorDtorScraper(GenericLLVMIRPlatformSupport &PS, 113 StringRef InitFunctionPrefix, 114 StringRef DeInitFunctionPrefix) 115 : PS(PS), InitFunctionPrefix(InitFunctionPrefix), 116 DeInitFunctionPrefix(DeInitFunctionPrefix) {} 117 Expected<ThreadSafeModule> operator()(ThreadSafeModule TSM, 118 MaterializationResponsibility &R); 119 120 private: 121 GenericLLVMIRPlatformSupport &PS; 122 StringRef InitFunctionPrefix; 123 StringRef DeInitFunctionPrefix; 124 }; 125 126 /// Generic IR Platform Support 127 /// 128 /// Scrapes llvm.global_ctors and llvm.global_dtors and replaces them with 129 /// specially named 'init' and 'deinit'. Injects definitions / interposes for 130 /// some runtime API, including __cxa_atexit, dlopen, and dlclose. 131 class GenericLLVMIRPlatformSupport : public LLJIT::PlatformSupport { 132 public: 133 GenericLLVMIRPlatformSupport(LLJIT &J, JITDylib &PlatformJD) 134 : J(J), InitFunctionPrefix(J.mangle("__orc_init_func.")), 135 DeInitFunctionPrefix(J.mangle("__orc_deinit_func.")) { 136 137 getExecutionSession().setPlatform( 138 std::make_unique<GenericLLVMIRPlatform>(*this)); 139 140 setInitTransform(J, GlobalCtorDtorScraper(*this, InitFunctionPrefix, 141 DeInitFunctionPrefix)); 142 143 SymbolMap StdInterposes; 144 145 StdInterposes[J.mangleAndIntern("__lljit.platform_support_instance")] = { 146 ExecutorAddr::fromPtr(this), JITSymbolFlags::Exported}; 147 StdInterposes[J.mangleAndIntern("__lljit.cxa_atexit_helper")] = { 148 ExecutorAddr::fromPtr(registerCxaAtExitHelper), JITSymbolFlags()}; 149 150 cantFail(PlatformJD.define(absoluteSymbols(std::move(StdInterposes)))); 151 cantFail(setupJITDylib(PlatformJD)); 152 cantFail(J.addIRModule(PlatformJD, createPlatformRuntimeModule())); 153 } 154 155 ExecutionSession &getExecutionSession() { return J.getExecutionSession(); } 156 157 /// Adds a module that defines the __dso_handle global. 158 Error setupJITDylib(JITDylib &JD) { 159 160 // Add per-jitdylib standard interposes. 161 SymbolMap PerJDInterposes; 162 PerJDInterposes[J.mangleAndIntern("__lljit.run_atexits_helper")] = { 163 ExecutorAddr::fromPtr(runAtExitsHelper), JITSymbolFlags()}; 164 PerJDInterposes[J.mangleAndIntern("__lljit.atexit_helper")] = { 165 ExecutorAddr::fromPtr(registerAtExitHelper), JITSymbolFlags()}; 166 cantFail(JD.define(absoluteSymbols(std::move(PerJDInterposes)))); 167 168 auto Ctx = std::make_unique<LLVMContext>(); 169 auto M = std::make_unique<Module>("__standard_lib", *Ctx); 170 M->setDataLayout(J.getDataLayout()); 171 172 auto *Int64Ty = Type::getInt64Ty(*Ctx); 173 auto *DSOHandle = new GlobalVariable( 174 *M, Int64Ty, true, GlobalValue::ExternalLinkage, 175 ConstantInt::get(Int64Ty, reinterpret_cast<uintptr_t>(&JD)), 176 "__dso_handle"); 177 DSOHandle->setVisibility(GlobalValue::DefaultVisibility); 178 DSOHandle->setInitializer( 179 ConstantInt::get(Int64Ty, ExecutorAddr::fromPtr(&JD).getValue())); 180 181 auto *GenericIRPlatformSupportTy = 182 StructType::create(*Ctx, "lljit.GenericLLJITIRPlatformSupport"); 183 184 auto *PlatformInstanceDecl = new GlobalVariable( 185 *M, GenericIRPlatformSupportTy, true, GlobalValue::ExternalLinkage, 186 nullptr, "__lljit.platform_support_instance"); 187 188 auto *VoidTy = Type::getVoidTy(*Ctx); 189 addHelperAndWrapper( 190 *M, "__lljit_run_atexits", FunctionType::get(VoidTy, {}, false), 191 GlobalValue::HiddenVisibility, "__lljit.run_atexits_helper", 192 {PlatformInstanceDecl, DSOHandle}); 193 194 auto *IntTy = Type::getIntNTy(*Ctx, sizeof(int) * CHAR_BIT); 195 auto *AtExitCallbackTy = FunctionType::get(VoidTy, {}, false); 196 auto *AtExitCallbackPtrTy = PointerType::getUnqual(AtExitCallbackTy); 197 addHelperAndWrapper(*M, "atexit", 198 FunctionType::get(IntTy, {AtExitCallbackPtrTy}, false), 199 GlobalValue::HiddenVisibility, "__lljit.atexit_helper", 200 {PlatformInstanceDecl, DSOHandle}); 201 202 return J.addIRModule(JD, ThreadSafeModule(std::move(M), std::move(Ctx))); 203 } 204 205 Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU) { 206 auto &JD = RT.getJITDylib(); 207 if (auto &InitSym = MU.getInitializerSymbol()) 208 InitSymbols[&JD].add(InitSym, SymbolLookupFlags::WeaklyReferencedSymbol); 209 else { 210 // If there's no identified init symbol attached, but there is a symbol 211 // with the GenericIRPlatform::InitFunctionPrefix, then treat that as 212 // an init function. Add the symbol to both the InitSymbols map (which 213 // will trigger a lookup to materialize the module) and the InitFunctions 214 // map (which holds the names of the symbols to execute). 215 for (auto &KV : MU.getSymbols()) 216 if ((*KV.first).starts_with(InitFunctionPrefix)) { 217 InitSymbols[&JD].add(KV.first, 218 SymbolLookupFlags::WeaklyReferencedSymbol); 219 InitFunctions[&JD].add(KV.first); 220 } else if ((*KV.first).starts_with(DeInitFunctionPrefix)) { 221 DeInitFunctions[&JD].add(KV.first); 222 } 223 } 224 return Error::success(); 225 } 226 227 Error initialize(JITDylib &JD) override { 228 LLVM_DEBUG({ 229 dbgs() << "GenericLLVMIRPlatformSupport getting initializers to run\n"; 230 }); 231 if (auto Initializers = getInitializers(JD)) { 232 LLVM_DEBUG( 233 { dbgs() << "GenericLLVMIRPlatformSupport running initializers\n"; }); 234 for (auto InitFnAddr : *Initializers) { 235 LLVM_DEBUG({ 236 dbgs() << " Running init " << formatv("{0:x16}", InitFnAddr) 237 << "...\n"; 238 }); 239 auto *InitFn = InitFnAddr.toPtr<void (*)()>(); 240 InitFn(); 241 } 242 } else 243 return Initializers.takeError(); 244 return Error::success(); 245 } 246 247 Error deinitialize(JITDylib &JD) override { 248 LLVM_DEBUG({ 249 dbgs() << "GenericLLVMIRPlatformSupport getting deinitializers to run\n"; 250 }); 251 if (auto Deinitializers = getDeinitializers(JD)) { 252 LLVM_DEBUG({ 253 dbgs() << "GenericLLVMIRPlatformSupport running deinitializers\n"; 254 }); 255 for (auto DeinitFnAddr : *Deinitializers) { 256 LLVM_DEBUG({ 257 dbgs() << " Running deinit " << formatv("{0:x16}", DeinitFnAddr) 258 << "...\n"; 259 }); 260 auto *DeinitFn = DeinitFnAddr.toPtr<void (*)()>(); 261 DeinitFn(); 262 } 263 } else 264 return Deinitializers.takeError(); 265 266 return Error::success(); 267 } 268 269 void registerInitFunc(JITDylib &JD, SymbolStringPtr InitName) { 270 getExecutionSession().runSessionLocked([&]() { 271 InitFunctions[&JD].add(InitName); 272 }); 273 } 274 275 void registerDeInitFunc(JITDylib &JD, SymbolStringPtr DeInitName) { 276 getExecutionSession().runSessionLocked( 277 [&]() { DeInitFunctions[&JD].add(DeInitName); }); 278 } 279 280 private: 281 Expected<std::vector<ExecutorAddr>> getInitializers(JITDylib &JD) { 282 if (auto Err = issueInitLookups(JD)) 283 return std::move(Err); 284 285 DenseMap<JITDylib *, SymbolLookupSet> LookupSymbols; 286 std::vector<JITDylibSP> DFSLinkOrder; 287 288 if (auto Err = getExecutionSession().runSessionLocked([&]() -> Error { 289 if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder()) 290 DFSLinkOrder = std::move(*DFSLinkOrderOrErr); 291 else 292 return DFSLinkOrderOrErr.takeError(); 293 294 for (auto &NextJD : DFSLinkOrder) { 295 auto IFItr = InitFunctions.find(NextJD.get()); 296 if (IFItr != InitFunctions.end()) { 297 LookupSymbols[NextJD.get()] = std::move(IFItr->second); 298 InitFunctions.erase(IFItr); 299 } 300 } 301 return Error::success(); 302 })) 303 return std::move(Err); 304 305 LLVM_DEBUG({ 306 dbgs() << "JITDylib init order is [ "; 307 for (auto &JD : llvm::reverse(DFSLinkOrder)) 308 dbgs() << "\"" << JD->getName() << "\" "; 309 dbgs() << "]\n"; 310 dbgs() << "Looking up init functions:\n"; 311 for (auto &KV : LookupSymbols) 312 dbgs() << " \"" << KV.first->getName() << "\": " << KV.second << "\n"; 313 }); 314 315 auto &ES = getExecutionSession(); 316 auto LookupResult = Platform::lookupInitSymbols(ES, LookupSymbols); 317 318 if (!LookupResult) 319 return LookupResult.takeError(); 320 321 std::vector<ExecutorAddr> Initializers; 322 while (!DFSLinkOrder.empty()) { 323 auto &NextJD = *DFSLinkOrder.back(); 324 DFSLinkOrder.pop_back(); 325 auto InitsItr = LookupResult->find(&NextJD); 326 if (InitsItr == LookupResult->end()) 327 continue; 328 for (auto &KV : InitsItr->second) 329 Initializers.push_back(KV.second.getAddress()); 330 } 331 332 return Initializers; 333 } 334 335 Expected<std::vector<ExecutorAddr>> getDeinitializers(JITDylib &JD) { 336 auto &ES = getExecutionSession(); 337 338 auto LLJITRunAtExits = J.mangleAndIntern("__lljit_run_atexits"); 339 340 DenseMap<JITDylib *, SymbolLookupSet> LookupSymbols; 341 std::vector<JITDylibSP> DFSLinkOrder; 342 343 if (auto Err = ES.runSessionLocked([&]() -> Error { 344 if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder()) 345 DFSLinkOrder = std::move(*DFSLinkOrderOrErr); 346 else 347 return DFSLinkOrderOrErr.takeError(); 348 349 for (auto &NextJD : DFSLinkOrder) { 350 auto &JDLookupSymbols = LookupSymbols[NextJD.get()]; 351 auto DIFItr = DeInitFunctions.find(NextJD.get()); 352 if (DIFItr != DeInitFunctions.end()) { 353 LookupSymbols[NextJD.get()] = std::move(DIFItr->second); 354 DeInitFunctions.erase(DIFItr); 355 } 356 JDLookupSymbols.add(LLJITRunAtExits, 357 SymbolLookupFlags::WeaklyReferencedSymbol); 358 } 359 return Error::success(); 360 })) 361 return std::move(Err); 362 363 LLVM_DEBUG({ 364 dbgs() << "JITDylib deinit order is [ "; 365 for (auto &JD : DFSLinkOrder) 366 dbgs() << "\"" << JD->getName() << "\" "; 367 dbgs() << "]\n"; 368 dbgs() << "Looking up deinit functions:\n"; 369 for (auto &KV : LookupSymbols) 370 dbgs() << " \"" << KV.first->getName() << "\": " << KV.second << "\n"; 371 }); 372 373 auto LookupResult = Platform::lookupInitSymbols(ES, LookupSymbols); 374 375 if (!LookupResult) 376 return LookupResult.takeError(); 377 378 std::vector<ExecutorAddr> DeInitializers; 379 for (auto &NextJD : DFSLinkOrder) { 380 auto DeInitsItr = LookupResult->find(NextJD.get()); 381 assert(DeInitsItr != LookupResult->end() && 382 "Every JD should have at least __lljit_run_atexits"); 383 384 auto RunAtExitsItr = DeInitsItr->second.find(LLJITRunAtExits); 385 if (RunAtExitsItr != DeInitsItr->second.end()) 386 DeInitializers.push_back(RunAtExitsItr->second.getAddress()); 387 388 for (auto &KV : DeInitsItr->second) 389 if (KV.first != LLJITRunAtExits) 390 DeInitializers.push_back(KV.second.getAddress()); 391 } 392 393 return DeInitializers; 394 } 395 396 /// Issue lookups for all init symbols required to initialize JD (and any 397 /// JITDylibs that it depends on). 398 Error issueInitLookups(JITDylib &JD) { 399 DenseMap<JITDylib *, SymbolLookupSet> RequiredInitSymbols; 400 std::vector<JITDylibSP> DFSLinkOrder; 401 402 if (auto Err = getExecutionSession().runSessionLocked([&]() -> Error { 403 if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder()) 404 DFSLinkOrder = std::move(*DFSLinkOrderOrErr); 405 else 406 return DFSLinkOrderOrErr.takeError(); 407 408 for (auto &NextJD : DFSLinkOrder) { 409 auto ISItr = InitSymbols.find(NextJD.get()); 410 if (ISItr != InitSymbols.end()) { 411 RequiredInitSymbols[NextJD.get()] = std::move(ISItr->second); 412 InitSymbols.erase(ISItr); 413 } 414 } 415 return Error::success(); 416 })) 417 return Err; 418 419 return Platform::lookupInitSymbols(getExecutionSession(), 420 RequiredInitSymbols) 421 .takeError(); 422 } 423 424 static void registerCxaAtExitHelper(void *Self, void (*F)(void *), void *Ctx, 425 void *DSOHandle) { 426 LLVM_DEBUG({ 427 dbgs() << "Registering cxa atexit function " << (void *)F << " for JD " 428 << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n"; 429 }); 430 static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.registerAtExit( 431 F, Ctx, DSOHandle); 432 } 433 434 static void registerAtExitHelper(void *Self, void *DSOHandle, void (*F)()) { 435 LLVM_DEBUG({ 436 dbgs() << "Registering atexit function " << (void *)F << " for JD " 437 << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n"; 438 }); 439 static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.registerAtExit( 440 reinterpret_cast<void (*)(void *)>(F), nullptr, DSOHandle); 441 } 442 443 static void runAtExitsHelper(void *Self, void *DSOHandle) { 444 LLVM_DEBUG({ 445 dbgs() << "Running atexit functions for JD " 446 << (*static_cast<JITDylib **>(DSOHandle))->getName() << "\n"; 447 }); 448 static_cast<GenericLLVMIRPlatformSupport *>(Self)->AtExitMgr.runAtExits( 449 DSOHandle); 450 } 451 452 // Constructs an LLVM IR module containing platform runtime globals, 453 // functions, and interposes. 454 ThreadSafeModule createPlatformRuntimeModule() { 455 auto Ctx = std::make_unique<LLVMContext>(); 456 auto M = std::make_unique<Module>("__standard_lib", *Ctx); 457 M->setDataLayout(J.getDataLayout()); 458 459 auto *GenericIRPlatformSupportTy = 460 StructType::create(*Ctx, "lljit.GenericLLJITIRPlatformSupport"); 461 462 auto *PlatformInstanceDecl = new GlobalVariable( 463 *M, GenericIRPlatformSupportTy, true, GlobalValue::ExternalLinkage, 464 nullptr, "__lljit.platform_support_instance"); 465 466 auto *Int8Ty = Type::getInt8Ty(*Ctx); 467 auto *IntTy = Type::getIntNTy(*Ctx, sizeof(int) * CHAR_BIT); 468 auto *VoidTy = Type::getVoidTy(*Ctx); 469 auto *BytePtrTy = PointerType::getUnqual(Int8Ty); 470 auto *CxaAtExitCallbackTy = FunctionType::get(VoidTy, {BytePtrTy}, false); 471 auto *CxaAtExitCallbackPtrTy = PointerType::getUnqual(CxaAtExitCallbackTy); 472 473 addHelperAndWrapper( 474 *M, "__cxa_atexit", 475 FunctionType::get(IntTy, {CxaAtExitCallbackPtrTy, BytePtrTy, BytePtrTy}, 476 false), 477 GlobalValue::DefaultVisibility, "__lljit.cxa_atexit_helper", 478 {PlatformInstanceDecl}); 479 480 return ThreadSafeModule(std::move(M), std::move(Ctx)); 481 } 482 483 LLJIT &J; 484 std::string InitFunctionPrefix; 485 std::string DeInitFunctionPrefix; 486 DenseMap<JITDylib *, SymbolLookupSet> InitSymbols; 487 DenseMap<JITDylib *, SymbolLookupSet> InitFunctions; 488 DenseMap<JITDylib *, SymbolLookupSet> DeInitFunctions; 489 ItaniumCXAAtExitSupport AtExitMgr; 490 }; 491 492 Error GenericLLVMIRPlatform::setupJITDylib(JITDylib &JD) { 493 return S.setupJITDylib(JD); 494 } 495 496 Error GenericLLVMIRPlatform::teardownJITDylib(JITDylib &JD) { 497 return Error::success(); 498 } 499 500 Error GenericLLVMIRPlatform::notifyAdding(ResourceTracker &RT, 501 const MaterializationUnit &MU) { 502 return S.notifyAdding(RT, MU); 503 } 504 505 Expected<ThreadSafeModule> 506 GlobalCtorDtorScraper::operator()(ThreadSafeModule TSM, 507 MaterializationResponsibility &R) { 508 auto Err = TSM.withModuleDo([&](Module &M) -> Error { 509 auto &Ctx = M.getContext(); 510 auto *GlobalCtors = M.getNamedGlobal("llvm.global_ctors"); 511 auto *GlobalDtors = M.getNamedGlobal("llvm.global_dtors"); 512 513 auto RegisterCOrDtors = [&](GlobalVariable *GlobalCOrDtors, 514 bool isCtor) -> Error { 515 // If there's no llvm.global_c/dtor or it's just a decl then skip. 516 if (!GlobalCOrDtors || GlobalCOrDtors->isDeclaration()) 517 return Error::success(); 518 std::string InitOrDeInitFunctionName; 519 if (isCtor) 520 raw_string_ostream(InitOrDeInitFunctionName) 521 << InitFunctionPrefix << M.getModuleIdentifier(); 522 else 523 raw_string_ostream(InitOrDeInitFunctionName) 524 << DeInitFunctionPrefix << M.getModuleIdentifier(); 525 526 MangleAndInterner Mangle(PS.getExecutionSession(), M.getDataLayout()); 527 auto InternedInitOrDeInitName = Mangle(InitOrDeInitFunctionName); 528 if (auto Err = R.defineMaterializing( 529 {{InternedInitOrDeInitName, JITSymbolFlags::Callable}})) 530 return Err; 531 532 auto *InitOrDeInitFunc = Function::Create( 533 FunctionType::get(Type::getVoidTy(Ctx), {}, false), 534 GlobalValue::ExternalLinkage, InitOrDeInitFunctionName, &M); 535 InitOrDeInitFunc->setVisibility(GlobalValue::HiddenVisibility); 536 std::vector<std::pair<Function *, unsigned>> InitsOrDeInits; 537 auto COrDtors = isCtor ? getConstructors(M) : getDestructors(M); 538 539 for (auto E : COrDtors) 540 InitsOrDeInits.push_back(std::make_pair(E.Func, E.Priority)); 541 llvm::sort(InitsOrDeInits, llvm::less_second()); 542 543 auto *InitOrDeInitFuncEntryBlock = 544 BasicBlock::Create(Ctx, "entry", InitOrDeInitFunc); 545 IRBuilder<> IB(InitOrDeInitFuncEntryBlock); 546 for (auto &KV : InitsOrDeInits) 547 IB.CreateCall(KV.first); 548 IB.CreateRetVoid(); 549 550 if (isCtor) 551 PS.registerInitFunc(R.getTargetJITDylib(), InternedInitOrDeInitName); 552 else 553 PS.registerDeInitFunc(R.getTargetJITDylib(), InternedInitOrDeInitName); 554 555 GlobalCOrDtors->eraseFromParent(); 556 return Error::success(); 557 }; 558 559 if (auto Err = RegisterCOrDtors(GlobalCtors, true)) 560 return Err; 561 if (auto Err = RegisterCOrDtors(GlobalDtors, false)) 562 return Err; 563 564 return Error::success(); 565 }); 566 567 if (Err) 568 return std::move(Err); 569 570 return std::move(TSM); 571 } 572 573 /// Inactive Platform Support 574 /// 575 /// Explicitly disables platform support. JITDylibs are not scanned for special 576 /// init/deinit symbols. No runtime API interposes are injected. 577 class InactivePlatformSupport : public LLJIT::PlatformSupport { 578 public: 579 InactivePlatformSupport() = default; 580 581 Error initialize(JITDylib &JD) override { 582 LLVM_DEBUG(dbgs() << "InactivePlatformSupport: no initializers running for " 583 << JD.getName() << "\n"); 584 return Error::success(); 585 } 586 587 Error deinitialize(JITDylib &JD) override { 588 LLVM_DEBUG( 589 dbgs() << "InactivePlatformSupport: no deinitializers running for " 590 << JD.getName() << "\n"); 591 return Error::success(); 592 } 593 }; 594 595 } // end anonymous namespace 596 597 namespace llvm { 598 namespace orc { 599 600 Error ORCPlatformSupport::initialize(orc::JITDylib &JD) { 601 using llvm::orc::shared::SPSExecutorAddr; 602 using llvm::orc::shared::SPSString; 603 using SPSDLOpenSig = SPSExecutorAddr(SPSString, int32_t); 604 enum dlopen_mode : int32_t { 605 ORC_RT_RTLD_LAZY = 0x1, 606 ORC_RT_RTLD_NOW = 0x2, 607 ORC_RT_RTLD_LOCAL = 0x4, 608 ORC_RT_RTLD_GLOBAL = 0x8 609 }; 610 611 auto &ES = J.getExecutionSession(); 612 auto MainSearchOrder = J.getMainJITDylib().withLinkOrderDo( 613 [](const JITDylibSearchOrder &SO) { return SO; }); 614 615 if (auto WrapperAddr = ES.lookup( 616 MainSearchOrder, J.mangleAndIntern("__orc_rt_jit_dlopen_wrapper"))) { 617 return ES.callSPSWrapper<SPSDLOpenSig>(WrapperAddr->getAddress(), 618 DSOHandles[&JD], JD.getName(), 619 int32_t(ORC_RT_RTLD_LAZY)); 620 } else 621 return WrapperAddr.takeError(); 622 } 623 624 Error ORCPlatformSupport::deinitialize(orc::JITDylib &JD) { 625 using llvm::orc::shared::SPSExecutorAddr; 626 using SPSDLCloseSig = int32_t(SPSExecutorAddr); 627 628 auto &ES = J.getExecutionSession(); 629 auto MainSearchOrder = J.getMainJITDylib().withLinkOrderDo( 630 [](const JITDylibSearchOrder &SO) { return SO; }); 631 632 if (auto WrapperAddr = ES.lookup( 633 MainSearchOrder, J.mangleAndIntern("__orc_rt_jit_dlclose_wrapper"))) { 634 int32_t result; 635 auto E = J.getExecutionSession().callSPSWrapper<SPSDLCloseSig>( 636 WrapperAddr->getAddress(), result, DSOHandles[&JD]); 637 if (E) 638 return E; 639 else if (result) 640 return make_error<StringError>("dlclose failed", 641 inconvertibleErrorCode()); 642 DSOHandles.erase(&JD); 643 } else 644 return WrapperAddr.takeError(); 645 return Error::success(); 646 } 647 648 void LLJIT::PlatformSupport::setInitTransform( 649 LLJIT &J, IRTransformLayer::TransformFunction T) { 650 J.InitHelperTransformLayer->setTransform(std::move(T)); 651 } 652 653 LLJIT::PlatformSupport::~PlatformSupport() = default; 654 655 Error LLJITBuilderState::prepareForConstruction() { 656 657 LLVM_DEBUG(dbgs() << "Preparing to create LLJIT instance...\n"); 658 659 if (!JTMB) { 660 LLVM_DEBUG({ 661 dbgs() << " No explicitly set JITTargetMachineBuilder. " 662 "Detecting host...\n"; 663 }); 664 if (auto JTMBOrErr = JITTargetMachineBuilder::detectHost()) 665 JTMB = std::move(*JTMBOrErr); 666 else 667 return JTMBOrErr.takeError(); 668 } 669 670 LLVM_DEBUG({ 671 dbgs() << " JITTargetMachineBuilder is " 672 << JITTargetMachineBuilderPrinter(*JTMB, " ") 673 << " Pre-constructed ExecutionSession: " << (ES ? "Yes" : "No") 674 << "\n" 675 << " DataLayout: "; 676 if (DL) 677 dbgs() << DL->getStringRepresentation() << "\n"; 678 else 679 dbgs() << "None (will be created by JITTargetMachineBuilder)\n"; 680 681 dbgs() << " Custom object-linking-layer creator: " 682 << (CreateObjectLinkingLayer ? "Yes" : "No") << "\n" 683 << " Custom compile-function creator: " 684 << (CreateCompileFunction ? "Yes" : "No") << "\n" 685 << " Custom platform-setup function: " 686 << (SetUpPlatform ? "Yes" : "No") << "\n" 687 << " Number of compile threads: " << NumCompileThreads; 688 if (!NumCompileThreads) 689 dbgs() << " (code will be compiled on the execution thread)\n"; 690 else 691 dbgs() << "\n"; 692 }); 693 694 // Create DL if not specified. 695 if (!DL) { 696 if (auto DLOrErr = JTMB->getDefaultDataLayoutForTarget()) 697 DL = std::move(*DLOrErr); 698 else 699 return DLOrErr.takeError(); 700 } 701 702 // If neither ES nor EPC has been set then create an EPC instance. 703 if (!ES && !EPC) { 704 LLVM_DEBUG({ 705 dbgs() << "ExecutorProcessControl not specified, " 706 "Creating SelfExecutorProcessControl instance\n"; 707 }); 708 if (auto EPCOrErr = SelfExecutorProcessControl::Create()) 709 EPC = std::move(*EPCOrErr); 710 else 711 return EPCOrErr.takeError(); 712 } else if (EPC) { 713 LLVM_DEBUG({ 714 dbgs() << "Using explicitly specified ExecutorProcessControl instance " 715 << EPC.get() << "\n"; 716 }); 717 } else { 718 LLVM_DEBUG({ 719 dbgs() << "Using explicitly specified ExecutionSession instance " 720 << ES.get() << "\n"; 721 }); 722 } 723 724 // If the client didn't configure any linker options then auto-configure the 725 // JIT linker. 726 if (!CreateObjectLinkingLayer) { 727 auto &TT = JTMB->getTargetTriple(); 728 bool UseJITLink = false; 729 switch (TT.getArch()) { 730 case Triple::riscv64: 731 case Triple::loongarch64: 732 UseJITLink = true; 733 break; 734 case Triple::aarch64: 735 UseJITLink = !TT.isOSBinFormatCOFF(); 736 break; 737 case Triple::x86_64: 738 UseJITLink = !TT.isOSBinFormatCOFF(); 739 break; 740 case Triple::ppc64: 741 UseJITLink = TT.isPPC64ELFv2ABI(); 742 break; 743 case Triple::ppc64le: 744 UseJITLink = TT.isOSBinFormatELF(); 745 break; 746 default: 747 break; 748 } 749 if (UseJITLink) { 750 JTMB->setRelocationModel(Reloc::PIC_); 751 JTMB->setCodeModel(CodeModel::Small); 752 CreateObjectLinkingLayer = 753 [](ExecutionSession &ES, 754 const Triple &) -> Expected<std::unique_ptr<ObjectLayer>> { 755 auto ObjLinkingLayer = std::make_unique<ObjectLinkingLayer>(ES); 756 if (auto EHFrameRegistrar = EPCEHFrameRegistrar::Create(ES)) 757 ObjLinkingLayer->addPlugin( 758 std::make_unique<EHFrameRegistrationPlugin>( 759 ES, std::move(*EHFrameRegistrar))); 760 else 761 return EHFrameRegistrar.takeError(); 762 return std::move(ObjLinkingLayer); 763 }; 764 } 765 } 766 767 // If we need a process JITDylib but no setup function has been given then 768 // create a default one. 769 if (!SetupProcessSymbolsJITDylib && LinkProcessSymbolsByDefault) { 770 LLVM_DEBUG(dbgs() << "Creating default Process JD setup function\n"); 771 SetupProcessSymbolsJITDylib = [](LLJIT &J) -> Expected<JITDylibSP> { 772 auto &JD = 773 J.getExecutionSession().createBareJITDylib("<Process Symbols>"); 774 auto G = EPCDynamicLibrarySearchGenerator::GetForTargetProcess( 775 J.getExecutionSession()); 776 if (!G) 777 return G.takeError(); 778 JD.addGenerator(std::move(*G)); 779 return &JD; 780 }; 781 } 782 783 return Error::success(); 784 } 785 786 LLJIT::~LLJIT() { 787 if (CompileThreads) 788 CompileThreads->wait(); 789 if (auto Err = ES->endSession()) 790 ES->reportError(std::move(Err)); 791 } 792 793 JITDylibSP LLJIT::getProcessSymbolsJITDylib() { return ProcessSymbols; } 794 795 JITDylibSP LLJIT::getPlatformJITDylib() { return Platform; } 796 797 Expected<JITDylib &> LLJIT::createJITDylib(std::string Name) { 798 auto JD = ES->createJITDylib(std::move(Name)); 799 if (!JD) 800 return JD.takeError(); 801 802 JD->addToLinkOrder(DefaultLinks); 803 return JD; 804 } 805 806 Expected<JITDylib &> LLJIT::loadPlatformDynamicLibrary(const char *Path) { 807 auto G = EPCDynamicLibrarySearchGenerator::Load(*ES, Path); 808 if (!G) 809 return G.takeError(); 810 811 if (auto *ExistingJD = ES->getJITDylibByName(Path)) 812 return *ExistingJD; 813 814 auto &JD = ES->createBareJITDylib(Path); 815 JD.addGenerator(std::move(*G)); 816 return JD; 817 } 818 819 Error LLJIT::linkStaticLibraryInto(JITDylib &JD, 820 std::unique_ptr<MemoryBuffer> LibBuffer) { 821 auto G = StaticLibraryDefinitionGenerator::Create(*ObjLinkingLayer, 822 std::move(LibBuffer)); 823 if (!G) 824 return G.takeError(); 825 826 JD.addGenerator(std::move(*G)); 827 828 return Error::success(); 829 } 830 831 Error LLJIT::linkStaticLibraryInto(JITDylib &JD, const char *Path) { 832 auto G = StaticLibraryDefinitionGenerator::Load(*ObjLinkingLayer, Path); 833 if (!G) 834 return G.takeError(); 835 836 JD.addGenerator(std::move(*G)); 837 838 return Error::success(); 839 } 840 841 Error LLJIT::addIRModule(ResourceTrackerSP RT, ThreadSafeModule TSM) { 842 assert(TSM && "Can not add null module"); 843 844 if (auto Err = 845 TSM.withModuleDo([&](Module &M) { return applyDataLayout(M); })) 846 return Err; 847 848 return InitHelperTransformLayer->add(std::move(RT), std::move(TSM)); 849 } 850 851 Error LLJIT::addIRModule(JITDylib &JD, ThreadSafeModule TSM) { 852 return addIRModule(JD.getDefaultResourceTracker(), std::move(TSM)); 853 } 854 855 Error LLJIT::addObjectFile(ResourceTrackerSP RT, 856 std::unique_ptr<MemoryBuffer> Obj) { 857 assert(Obj && "Can not add null object"); 858 859 return ObjTransformLayer->add(std::move(RT), std::move(Obj)); 860 } 861 862 Error LLJIT::addObjectFile(JITDylib &JD, std::unique_ptr<MemoryBuffer> Obj) { 863 return addObjectFile(JD.getDefaultResourceTracker(), std::move(Obj)); 864 } 865 866 Expected<ExecutorAddr> LLJIT::lookupLinkerMangled(JITDylib &JD, 867 SymbolStringPtr Name) { 868 if (auto Sym = ES->lookup( 869 makeJITDylibSearchOrder(&JD, JITDylibLookupFlags::MatchAllSymbols), 870 Name)) 871 return Sym->getAddress(); 872 else 873 return Sym.takeError(); 874 } 875 876 Expected<std::unique_ptr<ObjectLayer>> 877 LLJIT::createObjectLinkingLayer(LLJITBuilderState &S, ExecutionSession &ES) { 878 879 // If the config state provided an ObjectLinkingLayer factory then use it. 880 if (S.CreateObjectLinkingLayer) 881 return S.CreateObjectLinkingLayer(ES, S.JTMB->getTargetTriple()); 882 883 // Otherwise default to creating an RTDyldObjectLinkingLayer that constructs 884 // a new SectionMemoryManager for each object. 885 auto GetMemMgr = []() { return std::make_unique<SectionMemoryManager>(); }; 886 auto Layer = 887 std::make_unique<RTDyldObjectLinkingLayer>(ES, std::move(GetMemMgr)); 888 889 if (S.JTMB->getTargetTriple().isOSBinFormatCOFF()) { 890 Layer->setOverrideObjectFlagsWithResponsibilityFlags(true); 891 Layer->setAutoClaimResponsibilityForObjectSymbols(true); 892 } 893 894 if (S.JTMB->getTargetTriple().isOSBinFormatELF() && 895 (S.JTMB->getTargetTriple().getArch() == Triple::ArchType::ppc64 || 896 S.JTMB->getTargetTriple().getArch() == Triple::ArchType::ppc64le)) 897 Layer->setAutoClaimResponsibilityForObjectSymbols(true); 898 899 // FIXME: Explicit conversion to std::unique_ptr<ObjectLayer> added to silence 900 // errors from some GCC / libstdc++ bots. Remove this conversion (i.e. 901 // just return ObjLinkingLayer) once those bots are upgraded. 902 return std::unique_ptr<ObjectLayer>(std::move(Layer)); 903 } 904 905 Expected<std::unique_ptr<IRCompileLayer::IRCompiler>> 906 LLJIT::createCompileFunction(LLJITBuilderState &S, 907 JITTargetMachineBuilder JTMB) { 908 909 /// If there is a custom compile function creator set then use it. 910 if (S.CreateCompileFunction) 911 return S.CreateCompileFunction(std::move(JTMB)); 912 913 // Otherwise default to creating a SimpleCompiler, or ConcurrentIRCompiler, 914 // depending on the number of threads requested. 915 if (S.NumCompileThreads > 0) 916 return std::make_unique<ConcurrentIRCompiler>(std::move(JTMB)); 917 918 auto TM = JTMB.createTargetMachine(); 919 if (!TM) 920 return TM.takeError(); 921 922 return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM)); 923 } 924 925 LLJIT::LLJIT(LLJITBuilderState &S, Error &Err) 926 : DL(std::move(*S.DL)), TT(S.JTMB->getTargetTriple()) { 927 928 ErrorAsOutParameter _(&Err); 929 930 assert(!(S.EPC && S.ES) && "EPC and ES should not both be set"); 931 932 if (S.EPC) { 933 ES = std::make_unique<ExecutionSession>(std::move(S.EPC)); 934 } else if (S.ES) 935 ES = std::move(S.ES); 936 else { 937 if (auto EPC = SelfExecutorProcessControl::Create()) { 938 ES = std::make_unique<ExecutionSession>(std::move(*EPC)); 939 } else { 940 Err = EPC.takeError(); 941 return; 942 } 943 } 944 945 auto ObjLayer = createObjectLinkingLayer(S, *ES); 946 if (!ObjLayer) { 947 Err = ObjLayer.takeError(); 948 return; 949 } 950 ObjLinkingLayer = std::move(*ObjLayer); 951 ObjTransformLayer = 952 std::make_unique<ObjectTransformLayer>(*ES, *ObjLinkingLayer); 953 954 { 955 auto CompileFunction = createCompileFunction(S, std::move(*S.JTMB)); 956 if (!CompileFunction) { 957 Err = CompileFunction.takeError(); 958 return; 959 } 960 CompileLayer = std::make_unique<IRCompileLayer>( 961 *ES, *ObjTransformLayer, std::move(*CompileFunction)); 962 TransformLayer = std::make_unique<IRTransformLayer>(*ES, *CompileLayer); 963 InitHelperTransformLayer = 964 std::make_unique<IRTransformLayer>(*ES, *TransformLayer); 965 } 966 967 if (S.NumCompileThreads > 0) { 968 InitHelperTransformLayer->setCloneToNewContextOnEmit(true); 969 CompileThreads = 970 std::make_unique<ThreadPool>(hardware_concurrency(S.NumCompileThreads)); 971 ES->setDispatchTask([this](std::unique_ptr<Task> T) { 972 // FIXME: We should be able to use move-capture here, but ThreadPool's 973 // AsyncTaskTys are std::functions rather than unique_functions 974 // (because MSVC's std::packaged_tasks don't support move-only types). 975 // Fix this when all the above gets sorted out. 976 CompileThreads->async([UnownedT = T.release()]() mutable { 977 std::unique_ptr<Task> T(UnownedT); 978 T->run(); 979 }); 980 }); 981 } 982 983 if (S.SetupProcessSymbolsJITDylib) { 984 if (auto ProcSymsJD = S.SetupProcessSymbolsJITDylib(*this)) { 985 ProcessSymbols = ProcSymsJD->get(); 986 } else { 987 Err = ProcSymsJD.takeError(); 988 return; 989 } 990 } 991 992 if (S.PrePlatformSetup) { 993 if (auto Err2 = S.PrePlatformSetup(*this)) { 994 Err = std::move(Err2); 995 return; 996 } 997 } 998 999 if (!S.SetUpPlatform) 1000 S.SetUpPlatform = setUpGenericLLVMIRPlatform; 1001 1002 if (auto PlatformJDOrErr = S.SetUpPlatform(*this)) { 1003 Platform = PlatformJDOrErr->get(); 1004 if (Platform) 1005 DefaultLinks.push_back( 1006 {Platform, JITDylibLookupFlags::MatchExportedSymbolsOnly}); 1007 } else { 1008 Err = PlatformJDOrErr.takeError(); 1009 return; 1010 } 1011 1012 if (S.LinkProcessSymbolsByDefault) 1013 DefaultLinks.push_back( 1014 {ProcessSymbols, JITDylibLookupFlags::MatchExportedSymbolsOnly}); 1015 1016 if (auto MainOrErr = createJITDylib("main")) 1017 Main = &*MainOrErr; 1018 else { 1019 Err = MainOrErr.takeError(); 1020 return; 1021 } 1022 } 1023 1024 std::string LLJIT::mangle(StringRef UnmangledName) const { 1025 std::string MangledName; 1026 { 1027 raw_string_ostream MangledNameStream(MangledName); 1028 Mangler::getNameWithPrefix(MangledNameStream, UnmangledName, DL); 1029 } 1030 return MangledName; 1031 } 1032 1033 Error LLJIT::applyDataLayout(Module &M) { 1034 if (M.getDataLayout().isDefault()) 1035 M.setDataLayout(DL); 1036 1037 if (M.getDataLayout() != DL) 1038 return make_error<StringError>( 1039 "Added modules have incompatible data layouts: " + 1040 M.getDataLayout().getStringRepresentation() + " (module) vs " + 1041 DL.getStringRepresentation() + " (jit)", 1042 inconvertibleErrorCode()); 1043 1044 return Error::success(); 1045 } 1046 1047 Error setUpOrcPlatformManually(LLJIT &J) { 1048 LLVM_DEBUG({ dbgs() << "Setting up orc platform support for LLJIT\n"; }); 1049 J.setPlatformSupport(std::make_unique<ORCPlatformSupport>(J)); 1050 return Error::success(); 1051 } 1052 1053 class LoadAndLinkDynLibrary { 1054 public: 1055 LoadAndLinkDynLibrary(LLJIT &J) : J(J) {} 1056 Error operator()(JITDylib &JD, StringRef DLLName) { 1057 if (!DLLName.ends_with_insensitive(".dll")) 1058 return make_error<StringError>("DLLName not ending with .dll", 1059 inconvertibleErrorCode()); 1060 auto DLLNameStr = DLLName.str(); // Guarantees null-termination. 1061 auto DLLJD = J.loadPlatformDynamicLibrary(DLLNameStr.c_str()); 1062 if (!DLLJD) 1063 return DLLJD.takeError(); 1064 JD.addToLinkOrder(*DLLJD); 1065 return Error::success(); 1066 } 1067 1068 private: 1069 LLJIT &J; 1070 }; 1071 1072 Expected<JITDylibSP> ExecutorNativePlatform::operator()(LLJIT &J) { 1073 auto ProcessSymbolsJD = J.getProcessSymbolsJITDylib(); 1074 if (!ProcessSymbolsJD) 1075 return make_error<StringError>( 1076 "Native platforms require a process symbols JITDylib", 1077 inconvertibleErrorCode()); 1078 1079 const Triple &TT = J.getTargetTriple(); 1080 ObjectLinkingLayer *ObjLinkingLayer = 1081 dyn_cast<ObjectLinkingLayer>(&J.getObjLinkingLayer()); 1082 1083 if (!ObjLinkingLayer) 1084 return make_error<StringError>( 1085 "ExecutorNativePlatform requires ObjectLinkingLayer", 1086 inconvertibleErrorCode()); 1087 1088 std::unique_ptr<MemoryBuffer> RuntimeArchiveBuffer; 1089 if (OrcRuntime.index() == 0) { 1090 auto A = errorOrToExpected(MemoryBuffer::getFile(std::get<0>(OrcRuntime))); 1091 if (!A) 1092 return A.takeError(); 1093 RuntimeArchiveBuffer = std::move(*A); 1094 } else 1095 RuntimeArchiveBuffer = std::move(std::get<1>(OrcRuntime)); 1096 1097 auto &ES = J.getExecutionSession(); 1098 auto &PlatformJD = ES.createBareJITDylib("<Platform>"); 1099 PlatformJD.addToLinkOrder(*ProcessSymbolsJD); 1100 1101 J.setPlatformSupport(std::make_unique<ORCPlatformSupport>(J)); 1102 1103 switch (TT.getObjectFormat()) { 1104 case Triple::COFF: { 1105 const char *VCRuntimePath = nullptr; 1106 bool StaticVCRuntime = false; 1107 if (VCRuntime) { 1108 VCRuntimePath = VCRuntime->first.c_str(); 1109 StaticVCRuntime = VCRuntime->second; 1110 } 1111 if (auto P = COFFPlatform::Create( 1112 ES, *ObjLinkingLayer, PlatformJD, std::move(RuntimeArchiveBuffer), 1113 LoadAndLinkDynLibrary(J), StaticVCRuntime, VCRuntimePath)) 1114 J.getExecutionSession().setPlatform(std::move(*P)); 1115 else 1116 return P.takeError(); 1117 break; 1118 } 1119 case Triple::ELF: { 1120 auto G = StaticLibraryDefinitionGenerator::Create( 1121 *ObjLinkingLayer, std::move(RuntimeArchiveBuffer)); 1122 if (!G) 1123 return G.takeError(); 1124 1125 if (auto P = ELFNixPlatform::Create(ES, *ObjLinkingLayer, PlatformJD, 1126 std::move(*G))) 1127 J.getExecutionSession().setPlatform(std::move(*P)); 1128 else 1129 return P.takeError(); 1130 break; 1131 } 1132 case Triple::MachO: { 1133 auto G = StaticLibraryDefinitionGenerator::Create( 1134 *ObjLinkingLayer, std::move(RuntimeArchiveBuffer)); 1135 if (!G) 1136 return G.takeError(); 1137 1138 if (auto P = MachOPlatform::Create(ES, *ObjLinkingLayer, PlatformJD, 1139 std::move(*G))) 1140 ES.setPlatform(std::move(*P)); 1141 else 1142 return P.takeError(); 1143 break; 1144 } 1145 default: 1146 return make_error<StringError>("Unsupported object format in triple " + 1147 TT.str(), 1148 inconvertibleErrorCode()); 1149 } 1150 1151 return &PlatformJD; 1152 } 1153 1154 Expected<JITDylibSP> setUpGenericLLVMIRPlatform(LLJIT &J) { 1155 LLVM_DEBUG( 1156 { dbgs() << "Setting up GenericLLVMIRPlatform support for LLJIT\n"; }); 1157 auto ProcessSymbolsJD = J.getProcessSymbolsJITDylib(); 1158 if (!ProcessSymbolsJD) 1159 return make_error<StringError>( 1160 "Native platforms require a process symbols JITDylib", 1161 inconvertibleErrorCode()); 1162 1163 auto &PlatformJD = J.getExecutionSession().createBareJITDylib("<Platform>"); 1164 PlatformJD.addToLinkOrder(*ProcessSymbolsJD); 1165 1166 J.setPlatformSupport( 1167 std::make_unique<GenericLLVMIRPlatformSupport>(J, PlatformJD)); 1168 1169 return &PlatformJD; 1170 } 1171 1172 Expected<JITDylibSP> setUpInactivePlatform(LLJIT &J) { 1173 LLVM_DEBUG( 1174 { dbgs() << "Explicitly deactivated platform support for LLJIT\n"; }); 1175 J.setPlatformSupport(std::make_unique<InactivePlatformSupport>()); 1176 return nullptr; 1177 } 1178 1179 Error LLLazyJITBuilderState::prepareForConstruction() { 1180 if (auto Err = LLJITBuilderState::prepareForConstruction()) 1181 return Err; 1182 TT = JTMB->getTargetTriple(); 1183 return Error::success(); 1184 } 1185 1186 Error LLLazyJIT::addLazyIRModule(JITDylib &JD, ThreadSafeModule TSM) { 1187 assert(TSM && "Can not add null module"); 1188 1189 if (auto Err = TSM.withModuleDo( 1190 [&](Module &M) -> Error { return applyDataLayout(M); })) 1191 return Err; 1192 1193 return CODLayer->add(JD, std::move(TSM)); 1194 } 1195 1196 LLLazyJIT::LLLazyJIT(LLLazyJITBuilderState &S, Error &Err) : LLJIT(S, Err) { 1197 1198 // If LLJIT construction failed then bail out. 1199 if (Err) 1200 return; 1201 1202 ErrorAsOutParameter _(&Err); 1203 1204 /// Take/Create the lazy-compile callthrough manager. 1205 if (S.LCTMgr) 1206 LCTMgr = std::move(S.LCTMgr); 1207 else { 1208 if (auto LCTMgrOrErr = createLocalLazyCallThroughManager( 1209 S.TT, *ES, S.LazyCompileFailureAddr)) 1210 LCTMgr = std::move(*LCTMgrOrErr); 1211 else { 1212 Err = LCTMgrOrErr.takeError(); 1213 return; 1214 } 1215 } 1216 1217 // Take/Create the indirect stubs manager builder. 1218 auto ISMBuilder = std::move(S.ISMBuilder); 1219 1220 // If none was provided, try to build one. 1221 if (!ISMBuilder) 1222 ISMBuilder = createLocalIndirectStubsManagerBuilder(S.TT); 1223 1224 // No luck. Bail out. 1225 if (!ISMBuilder) { 1226 Err = make_error<StringError>("Could not construct " 1227 "IndirectStubsManagerBuilder for target " + 1228 S.TT.str(), 1229 inconvertibleErrorCode()); 1230 return; 1231 } 1232 1233 // Create the COD layer. 1234 CODLayer = std::make_unique<CompileOnDemandLayer>( 1235 *ES, *InitHelperTransformLayer, *LCTMgr, std::move(ISMBuilder)); 1236 1237 if (S.NumCompileThreads > 0) 1238 CODLayer->setCloneToNewContextOnEmit(true); 1239 } 1240 1241 // In-process LLJIT uses eh-frame section wrappers via EPC, so we need to force 1242 // them to be linked in. 1243 LLVM_ATTRIBUTE_USED void linkComponents() { 1244 errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper 1245 << (void *)&llvm_orc_deregisterEHFrameSectionWrapper; 1246 } 1247 1248 } // End namespace orc. 1249 } // End namespace llvm. 1250