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