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