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