1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// 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 // This utility provides a simple wrapper around the LLVM Execution Engines, 10 // which allow the direct execution of LLVM programs through a Just-In-Time 11 // compiler, or through an interpreter if no JIT is available for this platform. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ExecutionUtils.h" 16 #include "ForwardingMemoryManager.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/Bitcode/BitcodeReader.h" 20 #include "llvm/CodeGen/CommandFlags.h" 21 #include "llvm/CodeGen/LinkAllCodegenComponents.h" 22 #include "llvm/Config/llvm-config.h" 23 #include "llvm/ExecutionEngine/GenericValue.h" 24 #include "llvm/ExecutionEngine/Interpreter.h" 25 #include "llvm/ExecutionEngine/JITEventListener.h" 26 #include "llvm/ExecutionEngine/JITSymbol.h" 27 #include "llvm/ExecutionEngine/MCJIT.h" 28 #include "llvm/ExecutionEngine/ObjectCache.h" 29 #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h" 30 #include "llvm/ExecutionEngine/Orc/DebugUtils.h" 31 #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h" 32 #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h" 33 #include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h" 34 #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h" 35 #include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h" 36 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" 37 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" 38 #include "llvm/ExecutionEngine/Orc/LLJIT.h" 39 #include "llvm/ExecutionEngine/Orc/MachOPlatform.h" 40 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 41 #include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h" 42 #include "llvm/ExecutionEngine/Orc/SymbolStringPool.h" 43 #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h" 44 #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h" 45 #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h" 46 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 47 #include "llvm/IR/IRBuilder.h" 48 #include "llvm/IR/LLVMContext.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/IR/Type.h" 51 #include "llvm/IR/Verifier.h" 52 #include "llvm/IRReader/IRReader.h" 53 #include "llvm/Object/Archive.h" 54 #include "llvm/Object/ObjectFile.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/DynamicLibrary.h" 58 #include "llvm/Support/Format.h" 59 #include "llvm/Support/InitLLVM.h" 60 #include "llvm/Support/MathExtras.h" 61 #include "llvm/Support/Memory.h" 62 #include "llvm/Support/MemoryBuffer.h" 63 #include "llvm/Support/Path.h" 64 #include "llvm/Support/PluginLoader.h" 65 #include "llvm/Support/Process.h" 66 #include "llvm/Support/Program.h" 67 #include "llvm/Support/SourceMgr.h" 68 #include "llvm/Support/TargetSelect.h" 69 #include "llvm/Support/WithColor.h" 70 #include "llvm/Support/raw_ostream.h" 71 #include "llvm/Transforms/Instrumentation.h" 72 #include <cerrno> 73 74 #if !defined(_MSC_VER) && !defined(__MINGW32__) 75 #include <unistd.h> 76 #else 77 #include <io.h> 78 #endif 79 80 #ifdef __CYGWIN__ 81 #include <cygwin/version.h> 82 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 83 #define DO_NOTHING_ATEXIT 1 84 #endif 85 #endif 86 87 using namespace llvm; 88 89 static codegen::RegisterCodeGenFlags CGF; 90 91 #define DEBUG_TYPE "lli" 92 93 namespace { 94 95 enum class JITKind { MCJIT, Orc, OrcLazy }; 96 enum class JITLinkerKind { Default, RuntimeDyld, JITLink }; 97 98 cl::opt<std::string> 99 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); 100 101 cl::list<std::string> 102 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); 103 104 cl::opt<bool> ForceInterpreter("force-interpreter", 105 cl::desc("Force interpretation: disable JIT"), 106 cl::init(false)); 107 108 cl::opt<JITKind> UseJITKind( 109 "jit-kind", cl::desc("Choose underlying JIT kind."), 110 cl::init(JITKind::Orc), 111 cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"), 112 clEnumValN(JITKind::Orc, "orc", "Orc JIT"), 113 clEnumValN(JITKind::OrcLazy, "orc-lazy", 114 "Orc-based lazy JIT."))); 115 116 cl::opt<JITLinkerKind> 117 JITLinker("jit-linker", cl::desc("Choose the dynamic linker/loader."), 118 cl::init(JITLinkerKind::Default), 119 cl::values(clEnumValN(JITLinkerKind::Default, "default", 120 "Default for platform and JIT-kind"), 121 clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld", 122 "RuntimeDyld"), 123 clEnumValN(JITLinkerKind::JITLink, "jitlink", 124 "Orc-specific linker"))); 125 cl::opt<std::string> OrcRuntime("orc-runtime", 126 cl::desc("Use ORC runtime from given path"), 127 cl::init("")); 128 129 cl::opt<unsigned> 130 LazyJITCompileThreads("compile-threads", 131 cl::desc("Choose the number of compile threads " 132 "(jit-kind=orc-lazy only)"), 133 cl::init(0)); 134 135 cl::list<std::string> 136 ThreadEntryPoints("thread-entry", 137 cl::desc("calls the given entry-point on a new thread " 138 "(jit-kind=orc-lazy only)")); 139 140 cl::opt<bool> PerModuleLazy( 141 "per-module-lazy", 142 cl::desc("Performs lazy compilation on whole module boundaries " 143 "rather than individual functions"), 144 cl::init(false)); 145 146 cl::list<std::string> 147 JITDylibs("jd", 148 cl::desc("Specifies the JITDylib to be used for any subsequent " 149 "-extra-module arguments.")); 150 151 cl::list<std::string> 152 Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking")); 153 154 // The MCJIT supports building for a target address space separate from 155 // the JIT compilation process. Use a forked process and a copying 156 // memory manager with IPC to execute using this functionality. 157 cl::opt<bool> RemoteMCJIT("remote-mcjit", 158 cl::desc("Execute MCJIT'ed code in a separate process."), 159 cl::init(false)); 160 161 // Manually specify the child process for remote execution. This overrides 162 // the simulated remote execution that allocates address space for child 163 // execution. The child process will be executed and will communicate with 164 // lli via stdin/stdout pipes. 165 cl::opt<std::string> 166 ChildExecPath("mcjit-remote-process", 167 cl::desc("Specify the filename of the process to launch " 168 "for remote MCJIT execution. If none is specified," 169 "\n\tremote execution will be simulated in-process."), 170 cl::value_desc("filename"), cl::init("")); 171 172 // Determine optimization level. 173 cl::opt<char> OptLevel("O", 174 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 175 "(default = '-O2')"), 176 cl::Prefix, cl::init(' ')); 177 178 cl::opt<std::string> 179 TargetTriple("mtriple", cl::desc("Override target triple for module")); 180 181 cl::opt<std::string> 182 EntryFunc("entry-function", 183 cl::desc("Specify the entry function (default = 'main') " 184 "of the executable"), 185 cl::value_desc("function"), 186 cl::init("main")); 187 188 cl::list<std::string> 189 ExtraModules("extra-module", 190 cl::desc("Extra modules to be loaded"), 191 cl::value_desc("input bitcode")); 192 193 cl::list<std::string> 194 ExtraObjects("extra-object", 195 cl::desc("Extra object files to be loaded"), 196 cl::value_desc("input object")); 197 198 cl::list<std::string> 199 ExtraArchives("extra-archive", 200 cl::desc("Extra archive files to be loaded"), 201 cl::value_desc("input archive")); 202 203 cl::opt<bool> 204 EnableCacheManager("enable-cache-manager", 205 cl::desc("Use cache manager to save/load modules"), 206 cl::init(false)); 207 208 cl::opt<std::string> 209 ObjectCacheDir("object-cache-dir", 210 cl::desc("Directory to store cached object files " 211 "(must be user writable)"), 212 cl::init("")); 213 214 cl::opt<std::string> 215 FakeArgv0("fake-argv0", 216 cl::desc("Override the 'argv[0]' value passed into the executing" 217 " program"), cl::value_desc("executable")); 218 219 cl::opt<bool> 220 DisableCoreFiles("disable-core-files", cl::Hidden, 221 cl::desc("Disable emission of core files if possible")); 222 223 cl::opt<bool> 224 NoLazyCompilation("disable-lazy-compilation", 225 cl::desc("Disable JIT lazy compilation"), 226 cl::init(false)); 227 228 cl::opt<bool> 229 GenerateSoftFloatCalls("soft-float", 230 cl::desc("Generate software floating point library calls"), 231 cl::init(false)); 232 233 cl::opt<bool> NoProcessSymbols( 234 "no-process-syms", 235 cl::desc("Do not resolve lli process symbols in JIT'd code"), 236 cl::init(false)); 237 238 enum class LLJITPlatform { Inactive, DetectHost, ORC, GenericIR }; 239 240 cl::opt<LLJITPlatform> 241 Platform("lljit-platform", cl::desc("Platform to use with LLJIT"), 242 cl::init(LLJITPlatform::DetectHost), 243 cl::values(clEnumValN(LLJITPlatform::DetectHost, "DetectHost", 244 "Select based on JIT target triple"), 245 clEnumValN(LLJITPlatform::ORC, "ORC", 246 "Use ORCPlatform with the ORC runtime"), 247 clEnumValN(LLJITPlatform::GenericIR, "GenericIR", 248 "Use LLJITGenericIRPlatform"), 249 clEnumValN(LLJITPlatform::Inactive, "Inactive", 250 "Disable platform support explicitly")), 251 cl::Hidden); 252 253 enum class DumpKind { 254 NoDump, 255 DumpFuncsToStdOut, 256 DumpModsToStdOut, 257 DumpModsToDisk 258 }; 259 260 cl::opt<DumpKind> OrcDumpKind( 261 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."), 262 cl::init(DumpKind::NoDump), 263 cl::values(clEnumValN(DumpKind::NoDump, "no-dump", 264 "Don't dump anything."), 265 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout", 266 "Dump function names to stdout."), 267 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout", 268 "Dump modules to stdout."), 269 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk", 270 "Dump modules to the current " 271 "working directory. (WARNING: " 272 "will overwrite existing files).")), 273 cl::Hidden); 274 275 cl::list<BuiltinFunctionKind> GenerateBuiltinFunctions( 276 "generate", 277 cl::desc("Provide built-in functions for access by JITed code " 278 "(jit-kind=orc-lazy only)"), 279 cl::values(clEnumValN(BuiltinFunctionKind::DumpDebugDescriptor, 280 "__dump_jit_debug_descriptor", 281 "Dump __jit_debug_descriptor contents to stdout"), 282 clEnumValN(BuiltinFunctionKind::DumpDebugObjects, 283 "__dump_jit_debug_objects", 284 "Dump __jit_debug_descriptor in-memory debug " 285 "objects as tool output")), 286 cl::Hidden); 287 288 ExitOnError ExitOnErr; 289 } 290 291 LLVM_ATTRIBUTE_USED void linkComponents() { 292 errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper 293 << (void *)&llvm_orc_deregisterEHFrameSectionWrapper 294 << (void *)&llvm_orc_registerJITLoaderGDBWrapper; 295 } 296 297 //===----------------------------------------------------------------------===// 298 // Object cache 299 // 300 // This object cache implementation writes cached objects to disk to the 301 // directory specified by CacheDir, using a filename provided in the module 302 // descriptor. The cache tries to load a saved object using that path if the 303 // file exists. CacheDir defaults to "", in which case objects are cached 304 // alongside their originating bitcodes. 305 // 306 class LLIObjectCache : public ObjectCache { 307 public: 308 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) { 309 // Add trailing '/' to cache dir if necessary. 310 if (!this->CacheDir.empty() && 311 this->CacheDir[this->CacheDir.size() - 1] != '/') 312 this->CacheDir += '/'; 313 } 314 ~LLIObjectCache() override {} 315 316 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override { 317 const std::string &ModuleID = M->getModuleIdentifier(); 318 std::string CacheName; 319 if (!getCacheFilename(ModuleID, CacheName)) 320 return; 321 if (!CacheDir.empty()) { // Create user-defined cache dir. 322 SmallString<128> dir(sys::path::parent_path(CacheName)); 323 sys::fs::create_directories(Twine(dir)); 324 } 325 326 std::error_code EC; 327 raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None); 328 outfile.write(Obj.getBufferStart(), Obj.getBufferSize()); 329 outfile.close(); 330 } 331 332 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override { 333 const std::string &ModuleID = M->getModuleIdentifier(); 334 std::string CacheName; 335 if (!getCacheFilename(ModuleID, CacheName)) 336 return nullptr; 337 // Load the object from the cache filename 338 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer = 339 MemoryBuffer::getFile(CacheName, /*IsText=*/false, 340 /*RequiresNullTerminator=*/false); 341 // If the file isn't there, that's OK. 342 if (!IRObjectBuffer) 343 return nullptr; 344 // MCJIT will want to write into this buffer, and we don't want that 345 // because the file has probably just been mmapped. Instead we make 346 // a copy. The filed-based buffer will be released when it goes 347 // out of scope. 348 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer()); 349 } 350 351 private: 352 std::string CacheDir; 353 354 bool getCacheFilename(const std::string &ModID, std::string &CacheName) { 355 std::string Prefix("file:"); 356 size_t PrefixLength = Prefix.length(); 357 if (ModID.substr(0, PrefixLength) != Prefix) 358 return false; 359 360 std::string CacheSubdir = ModID.substr(PrefixLength); 361 // Transform "X:\foo" => "/X\foo" for convenience on Windows. 362 if (is_style_windows(llvm::sys::path::Style::native) && 363 isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') { 364 CacheSubdir[1] = CacheSubdir[0]; 365 CacheSubdir[0] = '/'; 366 } 367 368 CacheName = CacheDir + CacheSubdir; 369 size_t pos = CacheName.rfind('.'); 370 CacheName.replace(pos, CacheName.length() - pos, ".o"); 371 return true; 372 } 373 }; 374 375 class ORCPlatformSupport : public orc::LLJIT::PlatformSupport { 376 public: 377 ORCPlatformSupport(orc::LLJIT &J) : J(J) {} 378 379 Error initialize(orc::JITDylib &JD) override { 380 using llvm::orc::shared::SPSExecutorAddr; 381 using llvm::orc::shared::SPSString; 382 using SPSDLOpenSig = SPSExecutorAddr(SPSString, int32_t); 383 enum dlopen_mode : int32_t { 384 ORC_RT_RTLD_LAZY = 0x1, 385 ORC_RT_RTLD_NOW = 0x2, 386 ORC_RT_RTLD_LOCAL = 0x4, 387 ORC_RT_RTLD_GLOBAL = 0x8 388 }; 389 390 if (auto WrapperAddr = J.lookup("__orc_rt_jit_dlopen_wrapper")) { 391 return J.getExecutionSession().callSPSWrapper<SPSDLOpenSig>( 392 *WrapperAddr, DSOHandles[&JD], JD.getName(), 393 int32_t(ORC_RT_RTLD_LAZY)); 394 } else 395 return WrapperAddr.takeError(); 396 } 397 398 Error deinitialize(orc::JITDylib &JD) override { 399 using llvm::orc::shared::SPSExecutorAddr; 400 using SPSDLCloseSig = int32_t(SPSExecutorAddr); 401 402 if (auto WrapperAddr = J.lookup("__orc_rt_jit_dlclose_wrapper")) { 403 int32_t result; 404 auto E = J.getExecutionSession().callSPSWrapper<SPSDLCloseSig>( 405 *WrapperAddr, result, DSOHandles[&JD]); 406 if (E) 407 return E; 408 else if (result) 409 return make_error<StringError>("dlclose failed", 410 inconvertibleErrorCode()); 411 DSOHandles.erase(&JD); 412 } else 413 return WrapperAddr.takeError(); 414 return Error::success(); 415 } 416 417 private: 418 orc::LLJIT &J; 419 DenseMap<orc::JITDylib *, orc::ExecutorAddr> DSOHandles; 420 }; 421 422 // On Mingw and Cygwin, an external symbol named '__main' is called from the 423 // generated 'main' function to allow static initialization. To avoid linking 424 // problems with remote targets (because lli's remote target support does not 425 // currently handle external linking) we add a secondary module which defines 426 // an empty '__main' function. 427 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context, 428 StringRef TargetTripleStr) { 429 IRBuilder<> Builder(Context); 430 Triple TargetTriple(TargetTripleStr); 431 432 // Create a new module. 433 std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context); 434 M->setTargetTriple(TargetTripleStr); 435 436 // Create an empty function named "__main". 437 Type *ReturnTy; 438 if (TargetTriple.isArch64Bit()) 439 ReturnTy = Type::getInt64Ty(Context); 440 else 441 ReturnTy = Type::getInt32Ty(Context); 442 Function *Result = 443 Function::Create(FunctionType::get(ReturnTy, {}, false), 444 GlobalValue::ExternalLinkage, "__main", M.get()); 445 446 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result); 447 Builder.SetInsertPoint(BB); 448 Value *ReturnVal = ConstantInt::get(ReturnTy, 0); 449 Builder.CreateRet(ReturnVal); 450 451 // Add this new module to the ExecutionEngine. 452 EE.addModule(std::move(M)); 453 } 454 455 CodeGenOpt::Level getOptLevel() { 456 switch (OptLevel) { 457 default: 458 WithColor::error(errs(), "lli") << "invalid optimization level.\n"; 459 exit(1); 460 case '0': return CodeGenOpt::None; 461 case '1': return CodeGenOpt::Less; 462 case ' ': 463 case '2': return CodeGenOpt::Default; 464 case '3': return CodeGenOpt::Aggressive; 465 } 466 llvm_unreachable("Unrecognized opt level."); 467 } 468 469 [[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) { 470 Err.print(ProgName, errs()); 471 exit(1); 472 } 473 474 Error loadDylibs(); 475 int runOrcJIT(const char *ProgName); 476 void disallowOrcOptions(); 477 Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote(); 478 479 //===----------------------------------------------------------------------===// 480 // main Driver function 481 // 482 int main(int argc, char **argv, char * const *envp) { 483 InitLLVM X(argc, argv); 484 485 if (argc > 1) 486 ExitOnErr.setBanner(std::string(argv[0]) + ": "); 487 488 // If we have a native target, initialize it to ensure it is linked in and 489 // usable by the JIT. 490 InitializeNativeTarget(); 491 InitializeNativeTargetAsmPrinter(); 492 InitializeNativeTargetAsmParser(); 493 494 cl::ParseCommandLineOptions(argc, argv, 495 "llvm interpreter & dynamic compiler\n"); 496 497 // If the user doesn't want core files, disable them. 498 if (DisableCoreFiles) 499 sys::Process::PreventCoreFiles(); 500 501 ExitOnErr(loadDylibs()); 502 503 if (UseJITKind == JITKind::MCJIT) 504 disallowOrcOptions(); 505 else 506 return runOrcJIT(argv[0]); 507 508 // Old lli implementation based on ExecutionEngine and MCJIT. 509 LLVMContext Context; 510 511 // Load the bitcode... 512 SMDiagnostic Err; 513 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context); 514 Module *Mod = Owner.get(); 515 if (!Mod) 516 reportError(Err, argv[0]); 517 518 if (EnableCacheManager) { 519 std::string CacheName("file:"); 520 CacheName.append(InputFile); 521 Mod->setModuleIdentifier(CacheName); 522 } 523 524 // If not jitting lazily, load the whole bitcode file eagerly too. 525 if (NoLazyCompilation) { 526 // Use *argv instead of argv[0] to work around a wrong GCC warning. 527 ExitOnError ExitOnErr(std::string(*argv) + 528 ": bitcode didn't read correctly: "); 529 ExitOnErr(Mod->materializeAll()); 530 } 531 532 std::string ErrorMsg; 533 EngineBuilder builder(std::move(Owner)); 534 builder.setMArch(codegen::getMArch()); 535 builder.setMCPU(codegen::getCPUStr()); 536 builder.setMAttrs(codegen::getFeatureList()); 537 if (auto RM = codegen::getExplicitRelocModel()) 538 builder.setRelocationModel(RM.value()); 539 if (auto CM = codegen::getExplicitCodeModel()) 540 builder.setCodeModel(CM.value()); 541 builder.setErrorStr(&ErrorMsg); 542 builder.setEngineKind(ForceInterpreter 543 ? EngineKind::Interpreter 544 : EngineKind::JIT); 545 546 // If we are supposed to override the target triple, do so now. 547 if (!TargetTriple.empty()) 548 Mod->setTargetTriple(Triple::normalize(TargetTriple)); 549 550 // Enable MCJIT if desired. 551 RTDyldMemoryManager *RTDyldMM = nullptr; 552 if (!ForceInterpreter) { 553 if (RemoteMCJIT) 554 RTDyldMM = new ForwardingMemoryManager(); 555 else 556 RTDyldMM = new SectionMemoryManager(); 557 558 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out 559 // RTDyldMM: We still use it below, even though we don't own it. 560 builder.setMCJITMemoryManager( 561 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM)); 562 } else if (RemoteMCJIT) { 563 WithColor::error(errs(), argv[0]) 564 << "remote process execution does not work with the interpreter.\n"; 565 exit(1); 566 } 567 568 builder.setOptLevel(getOptLevel()); 569 570 TargetOptions Options = 571 codegen::InitTargetOptionsFromCodeGenFlags(Triple(TargetTriple)); 572 if (codegen::getFloatABIForCalls() != FloatABI::Default) 573 Options.FloatABIType = codegen::getFloatABIForCalls(); 574 575 builder.setTargetOptions(Options); 576 577 std::unique_ptr<ExecutionEngine> EE(builder.create()); 578 if (!EE) { 579 if (!ErrorMsg.empty()) 580 WithColor::error(errs(), argv[0]) 581 << "error creating EE: " << ErrorMsg << "\n"; 582 else 583 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n"; 584 exit(1); 585 } 586 587 std::unique_ptr<LLIObjectCache> CacheManager; 588 if (EnableCacheManager) { 589 CacheManager.reset(new LLIObjectCache(ObjectCacheDir)); 590 EE->setObjectCache(CacheManager.get()); 591 } 592 593 // Load any additional modules specified on the command line. 594 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) { 595 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context); 596 if (!XMod) 597 reportError(Err, argv[0]); 598 if (EnableCacheManager) { 599 std::string CacheName("file:"); 600 CacheName.append(ExtraModules[i]); 601 XMod->setModuleIdentifier(CacheName); 602 } 603 EE->addModule(std::move(XMod)); 604 } 605 606 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) { 607 Expected<object::OwningBinary<object::ObjectFile>> Obj = 608 object::ObjectFile::createObjectFile(ExtraObjects[i]); 609 if (!Obj) { 610 // TODO: Actually report errors helpfully. 611 consumeError(Obj.takeError()); 612 reportError(Err, argv[0]); 613 } 614 object::OwningBinary<object::ObjectFile> &O = Obj.get(); 615 EE->addObjectFile(std::move(O)); 616 } 617 618 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) { 619 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr = 620 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]); 621 if (!ArBufOrErr) 622 reportError(Err, argv[0]); 623 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get(); 624 625 Expected<std::unique_ptr<object::Archive>> ArOrErr = 626 object::Archive::create(ArBuf->getMemBufferRef()); 627 if (!ArOrErr) { 628 std::string Buf; 629 raw_string_ostream OS(Buf); 630 logAllUnhandledErrors(ArOrErr.takeError(), OS); 631 OS.flush(); 632 errs() << Buf; 633 exit(1); 634 } 635 std::unique_ptr<object::Archive> &Ar = ArOrErr.get(); 636 637 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf)); 638 639 EE->addArchive(std::move(OB)); 640 } 641 642 // If the target is Cygwin/MingW and we are generating remote code, we 643 // need an extra module to help out with linking. 644 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) { 645 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple()); 646 } 647 648 // The following functions have no effect if their respective profiling 649 // support wasn't enabled in the build configuration. 650 EE->RegisterJITEventListener( 651 JITEventListener::createOProfileJITEventListener()); 652 EE->RegisterJITEventListener( 653 JITEventListener::createIntelJITEventListener()); 654 if (!RemoteMCJIT) 655 EE->RegisterJITEventListener( 656 JITEventListener::createPerfJITEventListener()); 657 658 if (!NoLazyCompilation && RemoteMCJIT) { 659 WithColor::warning(errs(), argv[0]) 660 << "remote mcjit does not support lazy compilation\n"; 661 NoLazyCompilation = true; 662 } 663 EE->DisableLazyCompilation(NoLazyCompilation); 664 665 // If the user specifically requested an argv[0] to pass into the program, 666 // do it now. 667 if (!FakeArgv0.empty()) { 668 InputFile = static_cast<std::string>(FakeArgv0); 669 } else { 670 // Otherwise, if there is a .bc suffix on the executable strip it off, it 671 // might confuse the program. 672 if (StringRef(InputFile).endswith(".bc")) 673 InputFile.erase(InputFile.length() - 3); 674 } 675 676 // Add the module's name to the start of the vector of arguments to main(). 677 InputArgv.insert(InputArgv.begin(), InputFile); 678 679 // Call the main function from M as if its signature were: 680 // int main (int argc, char **argv, const char **envp) 681 // using the contents of Args to determine argc & argv, and the contents of 682 // EnvVars to determine envp. 683 // 684 Function *EntryFn = Mod->getFunction(EntryFunc); 685 if (!EntryFn) { 686 WithColor::error(errs(), argv[0]) 687 << '\'' << EntryFunc << "\' function not found in module.\n"; 688 return -1; 689 } 690 691 // Reset errno to zero on entry to main. 692 errno = 0; 693 694 int Result = -1; 695 696 // Sanity check use of remote-jit: LLI currently only supports use of the 697 // remote JIT on Unix platforms. 698 if (RemoteMCJIT) { 699 #ifndef LLVM_ON_UNIX 700 WithColor::warning(errs(), argv[0]) 701 << "host does not support external remote targets.\n"; 702 WithColor::note() << "defaulting to local execution\n"; 703 return -1; 704 #else 705 if (ChildExecPath.empty()) { 706 WithColor::error(errs(), argv[0]) 707 << "-remote-mcjit requires -mcjit-remote-process.\n"; 708 exit(1); 709 } else if (!sys::fs::can_execute(ChildExecPath)) { 710 WithColor::error(errs(), argv[0]) 711 << "unable to find usable child executable: '" << ChildExecPath 712 << "'\n"; 713 return -1; 714 } 715 #endif 716 } 717 718 std::unique_ptr<orc::ExecutorProcessControl> EPC = 719 RemoteMCJIT ? ExitOnErr(launchRemote()) 720 : ExitOnErr(orc::SelfExecutorProcessControl::Create()); 721 722 if (!RemoteMCJIT) { 723 // If the program doesn't explicitly call exit, we will need the Exit 724 // function later on to make an explicit call, so get the function now. 725 FunctionCallee Exit = Mod->getOrInsertFunction( 726 "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context)); 727 728 // Run static constructors. 729 if (!ForceInterpreter) { 730 // Give MCJIT a chance to apply relocations and set page permissions. 731 EE->finalizeObject(); 732 } 733 EE->runStaticConstructorsDestructors(false); 734 735 // Trigger compilation separately so code regions that need to be 736 // invalidated will be known. 737 (void)EE->getPointerToFunction(EntryFn); 738 // Clear instruction cache before code will be executed. 739 if (RTDyldMM) 740 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache(); 741 742 // Run main. 743 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); 744 745 // Run static destructors. 746 EE->runStaticConstructorsDestructors(true); 747 748 // If the program didn't call exit explicitly, we should call it now. 749 // This ensures that any atexit handlers get called correctly. 750 if (Function *ExitF = 751 dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) { 752 if (ExitF->getFunctionType() == Exit.getFunctionType()) { 753 std::vector<GenericValue> Args; 754 GenericValue ResultGV; 755 ResultGV.IntVal = APInt(32, Result); 756 Args.push_back(ResultGV); 757 EE->runFunction(ExitF, Args); 758 WithColor::error(errs(), argv[0]) 759 << "exit(" << Result << ") returned!\n"; 760 abort(); 761 } 762 } 763 WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n"; 764 abort(); 765 } else { 766 // else == "if (RemoteMCJIT)" 767 768 // Remote target MCJIT doesn't (yet) support static constructors. No reason 769 // it couldn't. This is a limitation of the LLI implementation, not the 770 // MCJIT itself. FIXME. 771 772 // Create a remote memory manager. 773 auto RemoteMM = ExitOnErr( 774 orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols( 775 *EPC)); 776 777 // Forward MCJIT's memory manager calls to the remote memory manager. 778 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr( 779 std::move(RemoteMM)); 780 781 // Forward MCJIT's symbol resolution calls to the remote. 782 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver( 783 ExitOnErr(RemoteResolver::Create(*EPC))); 784 // Grab the target address of the JIT'd main function on the remote and call 785 // it. 786 // FIXME: argv and envp handling. 787 auto Entry = 788 orc::ExecutorAddr(EE->getFunctionAddress(EntryFn->getName().str())); 789 EE->finalizeObject(); 790 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x" 791 << format("%llx", Entry.getValue()) << "\n"); 792 Result = ExitOnErr(EPC->runAsMain(Entry, {})); 793 794 // Like static constructors, the remote target MCJIT support doesn't handle 795 // this yet. It could. FIXME. 796 797 // Delete the EE - we need to tear it down *before* we terminate the session 798 // with the remote, otherwise it'll crash when it tries to release resources 799 // on a remote that has already been disconnected. 800 EE.reset(); 801 802 // Signal the remote target that we're done JITing. 803 ExitOnErr(EPC->disconnect()); 804 } 805 806 return Result; 807 } 808 809 static std::function<void(Module &)> createDebugDumper() { 810 switch (OrcDumpKind) { 811 case DumpKind::NoDump: 812 return [](Module &M) {}; 813 814 case DumpKind::DumpFuncsToStdOut: 815 return [](Module &M) { 816 printf("[ "); 817 818 for (const auto &F : M) { 819 if (F.isDeclaration()) 820 continue; 821 822 if (F.hasName()) { 823 std::string Name(std::string(F.getName())); 824 printf("%s ", Name.c_str()); 825 } else 826 printf("<anon> "); 827 } 828 829 printf("]\n"); 830 }; 831 832 case DumpKind::DumpModsToStdOut: 833 return [](Module &M) { 834 outs() << "----- Module Start -----\n" << M << "----- Module End -----\n"; 835 }; 836 837 case DumpKind::DumpModsToDisk: 838 return [](Module &M) { 839 std::error_code EC; 840 raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC, 841 sys::fs::OF_TextWithCRLF); 842 if (EC) { 843 errs() << "Couldn't open " << M.getModuleIdentifier() 844 << " for dumping.\nError:" << EC.message() << "\n"; 845 exit(1); 846 } 847 Out << M; 848 }; 849 } 850 llvm_unreachable("Unknown DumpKind"); 851 } 852 853 Error loadDylibs() { 854 for (const auto &Dylib : Dylibs) { 855 std::string ErrMsg; 856 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg)) 857 return make_error<StringError>(ErrMsg, inconvertibleErrorCode()); 858 } 859 860 return Error::success(); 861 } 862 863 static void exitOnLazyCallThroughFailure() { exit(1); } 864 865 Expected<orc::ThreadSafeModule> 866 loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) { 867 SMDiagnostic Err; 868 auto M = parseIRFile(Path, Err, *TSCtx.getContext()); 869 if (!M) { 870 std::string ErrMsg; 871 { 872 raw_string_ostream ErrMsgStream(ErrMsg); 873 Err.print("lli", ErrMsgStream); 874 } 875 return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode()); 876 } 877 878 if (EnableCacheManager) 879 M->setModuleIdentifier("file:" + M->getModuleIdentifier()); 880 881 return orc::ThreadSafeModule(std::move(M), std::move(TSCtx)); 882 } 883 884 int runOrcJIT(const char *ProgName) { 885 // Start setting up the JIT environment. 886 887 // Parse the main module. 888 orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>()); 889 auto MainModule = ExitOnErr(loadModule(InputFile, TSCtx)); 890 891 // Get TargetTriple and DataLayout from the main module if they're explicitly 892 // set. 893 Optional<Triple> TT; 894 Optional<DataLayout> DL; 895 MainModule.withModuleDo([&](Module &M) { 896 if (!M.getTargetTriple().empty()) 897 TT = Triple(M.getTargetTriple()); 898 if (!M.getDataLayout().isDefault()) 899 DL = M.getDataLayout(); 900 }); 901 902 orc::LLLazyJITBuilder Builder; 903 904 Builder.setJITTargetMachineBuilder( 905 TT ? orc::JITTargetMachineBuilder(*TT) 906 : ExitOnErr(orc::JITTargetMachineBuilder::detectHost())); 907 908 TT = Builder.getJITTargetMachineBuilder()->getTargetTriple(); 909 if (DL) 910 Builder.setDataLayout(DL); 911 912 if (!codegen::getMArch().empty()) 913 Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName( 914 codegen::getMArch()); 915 916 Builder.getJITTargetMachineBuilder() 917 ->setCPU(codegen::getCPUStr()) 918 .addFeatures(codegen::getFeatureList()) 919 .setRelocationModel(codegen::getExplicitRelocModel()) 920 .setCodeModel(codegen::getExplicitCodeModel()); 921 922 // FIXME: Setting a dummy call-through manager in non-lazy mode prevents the 923 // JIT builder to instantiate a default (which would fail with an error for 924 // unsupported architectures). 925 if (UseJITKind != JITKind::OrcLazy) { 926 auto ES = std::make_unique<orc::ExecutionSession>( 927 ExitOnErr(orc::SelfExecutorProcessControl::Create())); 928 Builder.setLazyCallthroughManager( 929 std::make_unique<orc::LazyCallThroughManager>(*ES, 0, nullptr)); 930 Builder.setExecutionSession(std::move(ES)); 931 } 932 933 Builder.setLazyCompileFailureAddr( 934 orc::ExecutorAddr::fromPtr(exitOnLazyCallThroughFailure)); 935 Builder.setNumCompileThreads(LazyJITCompileThreads); 936 937 // If the object cache is enabled then set a custom compile function 938 // creator to use the cache. 939 std::unique_ptr<LLIObjectCache> CacheManager; 940 if (EnableCacheManager) { 941 942 CacheManager = std::make_unique<LLIObjectCache>(ObjectCacheDir); 943 944 Builder.setCompileFunctionCreator( 945 [&](orc::JITTargetMachineBuilder JTMB) 946 -> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> { 947 if (LazyJITCompileThreads > 0) 948 return std::make_unique<orc::ConcurrentIRCompiler>(std::move(JTMB), 949 CacheManager.get()); 950 951 auto TM = JTMB.createTargetMachine(); 952 if (!TM) 953 return TM.takeError(); 954 955 return std::make_unique<orc::TMOwningSimpleCompiler>(std::move(*TM), 956 CacheManager.get()); 957 }); 958 } 959 960 // Set up LLJIT platform. 961 LLJITPlatform P = Platform; 962 if (P == LLJITPlatform::DetectHost) { 963 if (JITLinker == JITLinkerKind::JITLink && !OrcRuntime.empty() && 964 (TT->isOSBinFormatMachO() || TT->isOSBinFormatELF())) 965 P = LLJITPlatform::ORC; 966 else 967 P = LLJITPlatform::GenericIR; 968 } 969 switch (P) { 970 case LLJITPlatform::ORC: 971 Builder.setPlatformSetUp([](llvm::orc::LLJIT &J) -> llvm::Error { 972 J.setPlatformSupport(std::make_unique<ORCPlatformSupport>(J)); 973 return Error::success(); 974 }); 975 break; 976 case LLJITPlatform::GenericIR: 977 // Nothing to do: LLJITBuilder will use this by default. 978 break; 979 case LLJITPlatform::Inactive: 980 Builder.setPlatformSetUp(orc::setUpInactivePlatform); 981 break; 982 default: 983 llvm_unreachable("Unrecognized platform value"); 984 } 985 986 std::unique_ptr<orc::ExecutorProcessControl> EPC = nullptr; 987 if (JITLinker == JITLinkerKind::JITLink) { 988 EPC = ExitOnErr(orc::SelfExecutorProcessControl::Create( 989 std::make_shared<orc::SymbolStringPool>())); 990 991 Builder.setObjectLinkingLayerCreator([&EPC, &P](orc::ExecutionSession &ES, 992 const Triple &TT) { 993 auto L = std::make_unique<orc::ObjectLinkingLayer>(ES, EPC->getMemMgr()); 994 if (P != LLJITPlatform::ORC) { 995 L->addPlugin(std::make_unique<orc::EHFrameRegistrationPlugin>( 996 ES, ExitOnErr(orc::EPCEHFrameRegistrar::Create(ES)))); 997 L->addPlugin(std::make_unique<orc::DebugObjectManagerPlugin>( 998 ES, ExitOnErr(orc::createJITLoaderGDBRegistrar(ES)))); 999 } 1000 return L; 1001 }); 1002 } 1003 1004 auto J = ExitOnErr(Builder.create()); 1005 1006 auto *ObjLayer = &J->getObjLinkingLayer(); 1007 if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(ObjLayer)) 1008 RTDyldObjLayer->registerJITEventListener( 1009 *JITEventListener::createGDBRegistrationListener()); 1010 1011 if (PerModuleLazy) 1012 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule); 1013 1014 auto Dump = createDebugDumper(); 1015 1016 J->getIRTransformLayer().setTransform( 1017 [&](orc::ThreadSafeModule TSM, 1018 const orc::MaterializationResponsibility &R) { 1019 TSM.withModuleDo([&](Module &M) { 1020 if (verifyModule(M, &dbgs())) { 1021 dbgs() << "Bad module: " << &M << "\n"; 1022 exit(1); 1023 } 1024 Dump(M); 1025 }); 1026 return TSM; 1027 }); 1028 1029 orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout()); 1030 1031 // Unless they've been explicitly disabled, make process symbols available to 1032 // JIT'd code. 1033 if (!NoProcessSymbols) 1034 J->getMainJITDylib().addGenerator( 1035 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( 1036 J->getDataLayout().getGlobalPrefix(), 1037 [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) { 1038 return Name != MainName; 1039 }))); 1040 1041 if (GenerateBuiltinFunctions.size() > 0) 1042 J->getMainJITDylib().addGenerator( 1043 std::make_unique<LLIBuiltinFunctionGenerator>(GenerateBuiltinFunctions, 1044 Mangle)); 1045 1046 if (P == LLJITPlatform::ORC) { 1047 if (auto *OLL = llvm::dyn_cast<llvm::orc::ObjectLinkingLayer>(ObjLayer)) { 1048 auto &ES = J->getExecutionSession(); 1049 if (TT->isOSBinFormatMachO()) { 1050 if (auto P = llvm::orc::MachOPlatform::Create( 1051 ES, *OLL, J->getMainJITDylib(), OrcRuntime.c_str())) 1052 ES.setPlatform(std::move(*P)); 1053 else 1054 ExitOnErr(P.takeError()); 1055 } else if (TT->isOSBinFormatELF()) { 1056 if (auto P = llvm::orc::ELFNixPlatform::Create( 1057 ES, *OLL, J->getMainJITDylib(), OrcRuntime.c_str())) 1058 ES.setPlatform(std::move(*P)); 1059 else 1060 ExitOnErr(P.takeError()); 1061 } else { 1062 errs() << "No ORC platform support\n"; 1063 exit(1); 1064 } 1065 } else { 1066 errs() << "ORC platform requires JITLink\n"; 1067 exit(1); 1068 } 1069 } 1070 1071 // Regular modules are greedy: They materialize as a whole and trigger 1072 // materialization for all required symbols recursively. Lazy modules go 1073 // through partitioning and they replace outgoing calls with reexport stubs 1074 // that resolve on call-through. 1075 auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) { 1076 return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, std::move(M)) 1077 : J->addIRModule(JD, std::move(M)); 1078 }; 1079 1080 // Add the main module. 1081 ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule))); 1082 1083 // Create JITDylibs and add any extra modules. 1084 { 1085 // Create JITDylibs, keep a map from argument index to dylib. We will use 1086 // -extra-module argument indexes to determine what dylib to use for each 1087 // -extra-module. 1088 std::map<unsigned, orc::JITDylib *> IdxToDylib; 1089 IdxToDylib[0] = &J->getMainJITDylib(); 1090 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end(); 1091 JDItr != JDEnd; ++JDItr) { 1092 orc::JITDylib *JD = J->getJITDylibByName(*JDItr); 1093 if (!JD) { 1094 JD = &ExitOnErr(J->createJITDylib(*JDItr)); 1095 J->getMainJITDylib().addToLinkOrder(*JD); 1096 JD->addToLinkOrder(J->getMainJITDylib()); 1097 } 1098 IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD; 1099 } 1100 1101 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end(); 1102 EMItr != EMEnd; ++EMItr) { 1103 auto M = ExitOnErr(loadModule(*EMItr, TSCtx)); 1104 1105 auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin()); 1106 assert(EMIdx != 0 && "ExtraModule should have index > 0"); 1107 auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx)); 1108 auto &JD = *JDItr->second; 1109 ExitOnErr(AddModule(JD, std::move(M))); 1110 } 1111 1112 for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end(); 1113 EAItr != EAEnd; ++EAItr) { 1114 auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin()); 1115 assert(EAIdx != 0 && "ExtraArchive should have index > 0"); 1116 auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx)); 1117 auto &JD = *JDItr->second; 1118 JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load( 1119 J->getObjLinkingLayer(), EAItr->c_str(), *TT))); 1120 } 1121 } 1122 1123 // Add the objects. 1124 for (auto &ObjPath : ExtraObjects) { 1125 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath))); 1126 ExitOnErr(J->addObjectFile(std::move(Obj))); 1127 } 1128 1129 // Run any static constructors. 1130 ExitOnErr(J->initialize(J->getMainJITDylib())); 1131 1132 // Run any -thread-entry points. 1133 std::vector<std::thread> AltEntryThreads; 1134 for (auto &ThreadEntryPoint : ThreadEntryPoints) { 1135 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint)); 1136 typedef void (*EntryPointPtr)(); 1137 auto EntryPoint = EntryPointSym.toPtr<EntryPointPtr>(); 1138 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); })); 1139 } 1140 1141 // Resolve and run the main function. 1142 auto MainAddr = ExitOnErr(J->lookup(EntryFunc)); 1143 int Result; 1144 1145 if (EPC) { 1146 // ExecutorProcessControl-based execution with JITLink. 1147 Result = ExitOnErr(EPC->runAsMain(MainAddr, InputArgv)); 1148 } else { 1149 // Manual in-process execution with RuntimeDyld. 1150 using MainFnTy = int(int, char *[]); 1151 auto MainFn = MainAddr.toPtr<MainFnTy *>(); 1152 Result = orc::runAsMain(MainFn, InputArgv, StringRef(InputFile)); 1153 } 1154 1155 // Wait for -entry-point threads. 1156 for (auto &AltEntryThread : AltEntryThreads) 1157 AltEntryThread.join(); 1158 1159 // Run destructors. 1160 ExitOnErr(J->deinitialize(J->getMainJITDylib())); 1161 1162 return Result; 1163 } 1164 1165 void disallowOrcOptions() { 1166 // Make sure nobody used an orc-lazy specific option accidentally. 1167 1168 if (LazyJITCompileThreads != 0) { 1169 errs() << "-compile-threads requires -jit-kind=orc-lazy\n"; 1170 exit(1); 1171 } 1172 1173 if (!ThreadEntryPoints.empty()) { 1174 errs() << "-thread-entry requires -jit-kind=orc-lazy\n"; 1175 exit(1); 1176 } 1177 1178 if (PerModuleLazy) { 1179 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n"; 1180 exit(1); 1181 } 1182 } 1183 1184 Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() { 1185 #ifndef LLVM_ON_UNIX 1186 llvm_unreachable("launchRemote not supported on non-Unix platforms"); 1187 #else 1188 int PipeFD[2][2]; 1189 pid_t ChildPID; 1190 1191 // Create two pipes. 1192 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0) 1193 perror("Error creating pipe: "); 1194 1195 ChildPID = fork(); 1196 1197 if (ChildPID == 0) { 1198 // In the child... 1199 1200 // Close the parent ends of the pipes 1201 close(PipeFD[0][1]); 1202 close(PipeFD[1][0]); 1203 1204 1205 // Execute the child process. 1206 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut; 1207 { 1208 ChildPath.reset(new char[ChildExecPath.size() + 1]); 1209 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]); 1210 ChildPath[ChildExecPath.size()] = '\0'; 1211 std::string ChildInStr = utostr(PipeFD[0][0]); 1212 ChildIn.reset(new char[ChildInStr.size() + 1]); 1213 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]); 1214 ChildIn[ChildInStr.size()] = '\0'; 1215 std::string ChildOutStr = utostr(PipeFD[1][1]); 1216 ChildOut.reset(new char[ChildOutStr.size() + 1]); 1217 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]); 1218 ChildOut[ChildOutStr.size()] = '\0'; 1219 } 1220 1221 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr }; 1222 int rc = execv(ChildExecPath.c_str(), args); 1223 if (rc != 0) 1224 perror("Error executing child process: "); 1225 llvm_unreachable("Error executing child process"); 1226 } 1227 // else we're the parent... 1228 1229 // Close the child ends of the pipes 1230 close(PipeFD[0][0]); 1231 close(PipeFD[1][1]); 1232 1233 // Return a SimpleRemoteEPC instance connected to our end of the pipes. 1234 return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>( 1235 std::make_unique<llvm::orc::InPlaceTaskDispatcher>(), 1236 llvm::orc::SimpleRemoteEPC::Setup(), PipeFD[1][0], PipeFD[0][1]); 1237 #endif 1238 } 1239