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