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