1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This utility provides a simple wrapper around the LLVM Execution Engines, 11 // which allow the direct execution of LLVM programs through a Just-In-Time 12 // compiler, or through an interpreter if no JIT is available for this platform. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "OrcLazyJIT.h" 17 #include "RemoteJITUtils.h" 18 #include "llvm/IR/LLVMContext.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/Bitcode/ReaderWriter.h" 22 #include "llvm/CodeGen/LinkAllCodegenComponents.h" 23 #include "llvm/ExecutionEngine/GenericValue.h" 24 #include "llvm/ExecutionEngine/Interpreter.h" 25 #include "llvm/ExecutionEngine/JITEventListener.h" 26 #include "llvm/ExecutionEngine/MCJIT.h" 27 #include "llvm/ExecutionEngine/ObjectCache.h" 28 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h" 29 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 30 #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h" 31 #include "llvm/IR/IRBuilder.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/TypeBuilder.h" 35 #include "llvm/IRReader/IRReader.h" 36 #include "llvm/Object/Archive.h" 37 #include "llvm/Object/ObjectFile.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/DynamicLibrary.h" 41 #include "llvm/Support/Format.h" 42 #include "llvm/Support/ManagedStatic.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/Memory.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/PluginLoader.h" 48 #include "llvm/Support/PrettyStackTrace.h" 49 #include "llvm/Support/Process.h" 50 #include "llvm/Support/Program.h" 51 #include "llvm/Support/Signals.h" 52 #include "llvm/Support/SourceMgr.h" 53 #include "llvm/Support/TargetSelect.h" 54 #include "llvm/Support/raw_ostream.h" 55 #include "llvm/Transforms/Instrumentation.h" 56 #include <cerrno> 57 58 #ifdef __CYGWIN__ 59 #include <cygwin/version.h> 60 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 61 #define DO_NOTHING_ATEXIT 1 62 #endif 63 #endif 64 65 using namespace llvm; 66 67 #define DEBUG_TYPE "lli" 68 69 namespace { 70 71 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy }; 72 73 cl::opt<std::string> 74 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); 75 76 cl::list<std::string> 77 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); 78 79 cl::opt<bool> ForceInterpreter("force-interpreter", 80 cl::desc("Force interpretation: disable JIT"), 81 cl::init(false)); 82 83 cl::opt<JITKind> UseJITKind("jit-kind", 84 cl::desc("Choose underlying JIT kind."), 85 cl::init(JITKind::MCJIT), 86 cl::values( 87 clEnumValN(JITKind::MCJIT, "mcjit", 88 "MCJIT"), 89 clEnumValN(JITKind::OrcMCJITReplacement, 90 "orc-mcjit", 91 "Orc-based MCJIT replacement"), 92 clEnumValN(JITKind::OrcLazy, 93 "orc-lazy", 94 "Orc-based lazy JIT."), 95 clEnumValEnd)); 96 97 // The MCJIT supports building for a target address space separate from 98 // the JIT compilation process. Use a forked process and a copying 99 // memory manager with IPC to execute using this functionality. 100 cl::opt<bool> RemoteMCJIT("remote-mcjit", 101 cl::desc("Execute MCJIT'ed code in a separate process."), 102 cl::init(false)); 103 104 // Manually specify the child process for remote execution. This overrides 105 // the simulated remote execution that allocates address space for child 106 // execution. The child process will be executed and will communicate with 107 // lli via stdin/stdout pipes. 108 cl::opt<std::string> 109 ChildExecPath("mcjit-remote-process", 110 cl::desc("Specify the filename of the process to launch " 111 "for remote MCJIT execution. If none is specified," 112 "\n\tremote execution will be simulated in-process."), 113 cl::value_desc("filename"), cl::init("")); 114 115 // Determine optimization level. 116 cl::opt<char> 117 OptLevel("O", 118 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 119 "(default = '-O2')"), 120 cl::Prefix, 121 cl::ZeroOrMore, 122 cl::init(' ')); 123 124 cl::opt<std::string> 125 TargetTriple("mtriple", cl::desc("Override target triple for module")); 126 127 cl::opt<std::string> 128 MArch("march", 129 cl::desc("Architecture to generate assembly for (see --version)")); 130 131 cl::opt<std::string> 132 MCPU("mcpu", 133 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 134 cl::value_desc("cpu-name"), 135 cl::init("")); 136 137 cl::list<std::string> 138 MAttrs("mattr", 139 cl::CommaSeparated, 140 cl::desc("Target specific attributes (-mattr=help for details)"), 141 cl::value_desc("a1,+a2,-a3,...")); 142 143 cl::opt<std::string> 144 EntryFunc("entry-function", 145 cl::desc("Specify the entry function (default = 'main') " 146 "of the executable"), 147 cl::value_desc("function"), 148 cl::init("main")); 149 150 cl::list<std::string> 151 ExtraModules("extra-module", 152 cl::desc("Extra modules to be loaded"), 153 cl::value_desc("input bitcode")); 154 155 cl::list<std::string> 156 ExtraObjects("extra-object", 157 cl::desc("Extra object files to be loaded"), 158 cl::value_desc("input object")); 159 160 cl::list<std::string> 161 ExtraArchives("extra-archive", 162 cl::desc("Extra archive files to be loaded"), 163 cl::value_desc("input archive")); 164 165 cl::opt<bool> 166 EnableCacheManager("enable-cache-manager", 167 cl::desc("Use cache manager to save/load mdoules"), 168 cl::init(false)); 169 170 cl::opt<std::string> 171 ObjectCacheDir("object-cache-dir", 172 cl::desc("Directory to store cached object files " 173 "(must be user writable)"), 174 cl::init("")); 175 176 cl::opt<std::string> 177 FakeArgv0("fake-argv0", 178 cl::desc("Override the 'argv[0]' value passed into the executing" 179 " program"), cl::value_desc("executable")); 180 181 cl::opt<bool> 182 DisableCoreFiles("disable-core-files", cl::Hidden, 183 cl::desc("Disable emission of core files if possible")); 184 185 cl::opt<bool> 186 NoLazyCompilation("disable-lazy-compilation", 187 cl::desc("Disable JIT lazy compilation"), 188 cl::init(false)); 189 190 cl::opt<Reloc::Model> 191 RelocModel("relocation-model", 192 cl::desc("Choose relocation model"), 193 cl::init(Reloc::Default), 194 cl::values( 195 clEnumValN(Reloc::Default, "default", 196 "Target default relocation model"), 197 clEnumValN(Reloc::Static, "static", 198 "Non-relocatable code"), 199 clEnumValN(Reloc::PIC_, "pic", 200 "Fully relocatable, position independent code"), 201 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", 202 "Relocatable external references, non-relocatable code"), 203 clEnumValEnd)); 204 205 cl::opt<llvm::CodeModel::Model> 206 CMModel("code-model", 207 cl::desc("Choose code model"), 208 cl::init(CodeModel::JITDefault), 209 cl::values(clEnumValN(CodeModel::JITDefault, "default", 210 "Target default JIT code model"), 211 clEnumValN(CodeModel::Small, "small", 212 "Small code model"), 213 clEnumValN(CodeModel::Kernel, "kernel", 214 "Kernel code model"), 215 clEnumValN(CodeModel::Medium, "medium", 216 "Medium code model"), 217 clEnumValN(CodeModel::Large, "large", 218 "Large code model"), 219 clEnumValEnd)); 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<llvm::FloatABI::ABIType> 227 FloatABIForCalls("float-abi", 228 cl::desc("Choose float ABI type"), 229 cl::init(FloatABI::Default), 230 cl::values( 231 clEnumValN(FloatABI::Default, "default", 232 "Target default float ABI type"), 233 clEnumValN(FloatABI::Soft, "soft", 234 "Soft float ABI (implied by -soft-float)"), 235 clEnumValN(FloatABI::Hard, "hard", 236 "Hard float ABI (uses FP registers)"), 237 clEnumValEnd)); 238 } 239 240 //===----------------------------------------------------------------------===// 241 // Object cache 242 // 243 // This object cache implementation writes cached objects to disk to the 244 // directory specified by CacheDir, using a filename provided in the module 245 // descriptor. The cache tries to load a saved object using that path if the 246 // file exists. CacheDir defaults to "", in which case objects are cached 247 // alongside their originating bitcodes. 248 // 249 class LLIObjectCache : public ObjectCache { 250 public: 251 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) { 252 // Add trailing '/' to cache dir if necessary. 253 if (!this->CacheDir.empty() && 254 this->CacheDir[this->CacheDir.size() - 1] != '/') 255 this->CacheDir += '/'; 256 } 257 ~LLIObjectCache() override {} 258 259 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override { 260 const std::string ModuleID = M->getModuleIdentifier(); 261 std::string CacheName; 262 if (!getCacheFilename(ModuleID, CacheName)) 263 return; 264 if (!CacheDir.empty()) { // Create user-defined cache dir. 265 SmallString<128> dir(sys::path::parent_path(CacheName)); 266 sys::fs::create_directories(Twine(dir)); 267 } 268 std::error_code EC; 269 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None); 270 outfile.write(Obj.getBufferStart(), Obj.getBufferSize()); 271 outfile.close(); 272 } 273 274 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override { 275 const std::string ModuleID = M->getModuleIdentifier(); 276 std::string CacheName; 277 if (!getCacheFilename(ModuleID, CacheName)) 278 return nullptr; 279 // Load the object from the cache filename 280 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer = 281 MemoryBuffer::getFile(CacheName.c_str(), -1, false); 282 // If the file isn't there, that's OK. 283 if (!IRObjectBuffer) 284 return nullptr; 285 // MCJIT will want to write into this buffer, and we don't want that 286 // because the file has probably just been mmapped. Instead we make 287 // a copy. The filed-based buffer will be released when it goes 288 // out of scope. 289 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer()); 290 } 291 292 private: 293 std::string CacheDir; 294 295 bool getCacheFilename(const std::string &ModID, std::string &CacheName) { 296 std::string Prefix("file:"); 297 size_t PrefixLength = Prefix.length(); 298 if (ModID.substr(0, PrefixLength) != Prefix) 299 return false; 300 std::string CacheSubdir = ModID.substr(PrefixLength); 301 #if defined(_WIN32) 302 // Transform "X:\foo" => "/X\foo" for convenience. 303 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') { 304 CacheSubdir[1] = CacheSubdir[0]; 305 CacheSubdir[0] = '/'; 306 } 307 #endif 308 CacheName = CacheDir + CacheSubdir; 309 size_t pos = CacheName.rfind('.'); 310 CacheName.replace(pos, CacheName.length() - pos, ".o"); 311 return true; 312 } 313 }; 314 315 static ExecutionEngine *EE = nullptr; 316 static LLIObjectCache *CacheManager = nullptr; 317 318 static void do_shutdown() { 319 // Cygwin-1.5 invokes DLL's dtors before atexit handler. 320 #ifndef DO_NOTHING_ATEXIT 321 delete EE; 322 if (CacheManager) 323 delete CacheManager; 324 llvm_shutdown(); 325 #endif 326 } 327 328 // On Mingw and Cygwin, an external symbol named '__main' is called from the 329 // generated 'main' function to allow static intialization. To avoid linking 330 // problems with remote targets (because lli's remote target support does not 331 // currently handle external linking) we add a secondary module which defines 332 // an empty '__main' function. 333 static void addCygMingExtraModule(ExecutionEngine *EE, 334 LLVMContext &Context, 335 StringRef TargetTripleStr) { 336 IRBuilder<> Builder(Context); 337 Triple TargetTriple(TargetTripleStr); 338 339 // Create a new module. 340 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context); 341 M->setTargetTriple(TargetTripleStr); 342 343 // Create an empty function named "__main". 344 Function *Result; 345 if (TargetTriple.isArch64Bit()) { 346 Result = Function::Create( 347 TypeBuilder<int64_t(void), false>::get(Context), 348 GlobalValue::ExternalLinkage, "__main", M.get()); 349 } else { 350 Result = Function::Create( 351 TypeBuilder<int32_t(void), false>::get(Context), 352 GlobalValue::ExternalLinkage, "__main", M.get()); 353 } 354 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result); 355 Builder.SetInsertPoint(BB); 356 Value *ReturnVal; 357 if (TargetTriple.isArch64Bit()) 358 ReturnVal = ConstantInt::get(Context, APInt(64, 0)); 359 else 360 ReturnVal = ConstantInt::get(Context, APInt(32, 0)); 361 Builder.CreateRet(ReturnVal); 362 363 // Add this new module to the ExecutionEngine. 364 EE->addModule(std::move(M)); 365 } 366 367 CodeGenOpt::Level getOptLevel() { 368 switch (OptLevel) { 369 default: 370 errs() << "lli: Invalid optimization level.\n"; 371 exit(1); 372 case '0': return CodeGenOpt::None; 373 case '1': return CodeGenOpt::Less; 374 case ' ': 375 case '2': return CodeGenOpt::Default; 376 case '3': return CodeGenOpt::Aggressive; 377 } 378 llvm_unreachable("Unrecognized opt level."); 379 } 380 381 //===----------------------------------------------------------------------===// 382 // main Driver function 383 // 384 int main(int argc, char **argv, char * const *envp) { 385 sys::PrintStackTraceOnErrorSignal(); 386 PrettyStackTraceProgram X(argc, argv); 387 388 LLVMContext &Context = getGlobalContext(); 389 atexit(do_shutdown); // Call llvm_shutdown() on exit. 390 391 // If we have a native target, initialize it to ensure it is linked in and 392 // usable by the JIT. 393 InitializeNativeTarget(); 394 InitializeNativeTargetAsmPrinter(); 395 InitializeNativeTargetAsmParser(); 396 397 cl::ParseCommandLineOptions(argc, argv, 398 "llvm interpreter & dynamic compiler\n"); 399 400 // If the user doesn't want core files, disable them. 401 if (DisableCoreFiles) 402 sys::Process::PreventCoreFiles(); 403 404 // Load the bitcode... 405 SMDiagnostic Err; 406 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context); 407 Module *Mod = Owner.get(); 408 if (!Mod) { 409 Err.print(argv[0], errs()); 410 return 1; 411 } 412 413 if (UseJITKind == JITKind::OrcLazy) 414 return runOrcLazyJIT(std::move(Owner), argc, argv); 415 416 if (EnableCacheManager) { 417 std::string CacheName("file:"); 418 CacheName.append(InputFile); 419 Mod->setModuleIdentifier(CacheName); 420 } 421 422 // If not jitting lazily, load the whole bitcode file eagerly too. 423 if (NoLazyCompilation) { 424 if (std::error_code EC = Mod->materializeAll()) { 425 errs() << argv[0] << ": bitcode didn't read correctly.\n"; 426 errs() << "Reason: " << EC.message() << "\n"; 427 exit(1); 428 } 429 } 430 431 std::string ErrorMsg; 432 EngineBuilder builder(std::move(Owner)); 433 builder.setMArch(MArch); 434 builder.setMCPU(MCPU); 435 builder.setMAttrs(MAttrs); 436 builder.setRelocationModel(RelocModel); 437 builder.setCodeModel(CMModel); 438 builder.setErrorStr(&ErrorMsg); 439 builder.setEngineKind(ForceInterpreter 440 ? EngineKind::Interpreter 441 : EngineKind::JIT); 442 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement); 443 444 // If we are supposed to override the target triple, do so now. 445 if (!TargetTriple.empty()) 446 Mod->setTargetTriple(Triple::normalize(TargetTriple)); 447 448 // Enable MCJIT if desired. 449 RTDyldMemoryManager *RTDyldMM = nullptr; 450 if (!ForceInterpreter) { 451 if (RemoteMCJIT) 452 RTDyldMM = new ForwardingMemoryManager(); 453 else 454 RTDyldMM = new SectionMemoryManager(); 455 456 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out 457 // RTDyldMM: We still use it below, even though we don't own it. 458 builder.setMCJITMemoryManager( 459 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM)); 460 } else if (RemoteMCJIT) { 461 errs() << "error: Remote process execution does not work with the " 462 "interpreter.\n"; 463 exit(1); 464 } 465 466 builder.setOptLevel(getOptLevel()); 467 468 TargetOptions Options; 469 if (FloatABIForCalls != FloatABI::Default) 470 Options.FloatABIType = FloatABIForCalls; 471 472 builder.setTargetOptions(Options); 473 474 EE = builder.create(); 475 if (!EE) { 476 if (!ErrorMsg.empty()) 477 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; 478 else 479 errs() << argv[0] << ": unknown error creating EE!\n"; 480 exit(1); 481 } 482 483 if (EnableCacheManager) { 484 CacheManager = new LLIObjectCache(ObjectCacheDir); 485 EE->setObjectCache(CacheManager); 486 } 487 488 // Load any additional modules specified on the command line. 489 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) { 490 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context); 491 if (!XMod) { 492 Err.print(argv[0], errs()); 493 return 1; 494 } 495 if (EnableCacheManager) { 496 std::string CacheName("file:"); 497 CacheName.append(ExtraModules[i]); 498 XMod->setModuleIdentifier(CacheName); 499 } 500 EE->addModule(std::move(XMod)); 501 } 502 503 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) { 504 ErrorOr<object::OwningBinary<object::ObjectFile>> Obj = 505 object::ObjectFile::createObjectFile(ExtraObjects[i]); 506 if (!Obj) { 507 Err.print(argv[0], errs()); 508 return 1; 509 } 510 object::OwningBinary<object::ObjectFile> &O = Obj.get(); 511 EE->addObjectFile(std::move(O)); 512 } 513 514 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) { 515 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr = 516 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]); 517 if (!ArBufOrErr) { 518 Err.print(argv[0], errs()); 519 return 1; 520 } 521 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get(); 522 523 ErrorOr<std::unique_ptr<object::Archive>> ArOrErr = 524 object::Archive::create(ArBuf->getMemBufferRef()); 525 if (std::error_code EC = ArOrErr.getError()) { 526 errs() << EC.message(); 527 return 1; 528 } 529 std::unique_ptr<object::Archive> &Ar = ArOrErr.get(); 530 531 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf)); 532 533 EE->addArchive(std::move(OB)); 534 } 535 536 // If the target is Cygwin/MingW and we are generating remote code, we 537 // need an extra module to help out with linking. 538 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) { 539 addCygMingExtraModule(EE, Context, Mod->getTargetTriple()); 540 } 541 542 // The following functions have no effect if their respective profiling 543 // support wasn't enabled in the build configuration. 544 EE->RegisterJITEventListener( 545 JITEventListener::createOProfileJITEventListener()); 546 EE->RegisterJITEventListener( 547 JITEventListener::createIntelJITEventListener()); 548 549 if (!NoLazyCompilation && RemoteMCJIT) { 550 errs() << "warning: remote mcjit does not support lazy compilation\n"; 551 NoLazyCompilation = true; 552 } 553 EE->DisableLazyCompilation(NoLazyCompilation); 554 555 // If the user specifically requested an argv[0] to pass into the program, 556 // do it now. 557 if (!FakeArgv0.empty()) { 558 InputFile = static_cast<std::string>(FakeArgv0); 559 } else { 560 // Otherwise, if there is a .bc suffix on the executable strip it off, it 561 // might confuse the program. 562 if (StringRef(InputFile).endswith(".bc")) 563 InputFile.erase(InputFile.length() - 3); 564 } 565 566 // Add the module's name to the start of the vector of arguments to main(). 567 InputArgv.insert(InputArgv.begin(), InputFile); 568 569 // Call the main function from M as if its signature were: 570 // int main (int argc, char **argv, const char **envp) 571 // using the contents of Args to determine argc & argv, and the contents of 572 // EnvVars to determine envp. 573 // 574 Function *EntryFn = Mod->getFunction(EntryFunc); 575 if (!EntryFn) { 576 errs() << '\'' << EntryFunc << "\' function not found in module.\n"; 577 return -1; 578 } 579 580 // Reset errno to zero on entry to main. 581 errno = 0; 582 583 int Result; 584 585 // Sanity check use of remote-jit: LLI currently only supports use of the 586 // remote JIT on Unix platforms. 587 if (RemoteMCJIT) { 588 #ifndef LLVM_ON_UNIX 589 errs() << "Warning: host does not support external remote targets.\n" 590 << " Defaulting to local execution execution\n"; 591 return -1; 592 #else 593 if (ChildExecPath.empty()) { 594 errs() << "-remote-mcjit requires -mcjit-remote-process.\n"; 595 exit(1); 596 } else if (!sys::fs::can_execute(ChildExecPath)) { 597 errs() << "Unable to find usable child executable: '" << ChildExecPath 598 << "'\n"; 599 return -1; 600 } 601 #endif 602 } 603 604 if (!RemoteMCJIT) { 605 // If the program doesn't explicitly call exit, we will need the Exit 606 // function later on to make an explicit call, so get the function now. 607 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), 608 Type::getInt32Ty(Context), 609 nullptr); 610 611 // Run static constructors. 612 if (!ForceInterpreter) { 613 // Give MCJIT a chance to apply relocations and set page permissions. 614 EE->finalizeObject(); 615 } 616 EE->runStaticConstructorsDestructors(false); 617 618 // Trigger compilation separately so code regions that need to be 619 // invalidated will be known. 620 (void)EE->getPointerToFunction(EntryFn); 621 // Clear instruction cache before code will be executed. 622 if (RTDyldMM) 623 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache(); 624 625 // Run main. 626 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); 627 628 // Run static destructors. 629 EE->runStaticConstructorsDestructors(true); 630 631 // If the program didn't call exit explicitly, we should call it now. 632 // This ensures that any atexit handlers get called correctly. 633 if (Function *ExitF = dyn_cast<Function>(Exit)) { 634 std::vector<GenericValue> Args; 635 GenericValue ResultGV; 636 ResultGV.IntVal = APInt(32, Result); 637 Args.push_back(ResultGV); 638 EE->runFunction(ExitF, Args); 639 errs() << "ERROR: exit(" << Result << ") returned!\n"; 640 abort(); 641 } else { 642 errs() << "ERROR: exit defined with wrong prototype!\n"; 643 abort(); 644 } 645 } else { 646 // else == "if (RemoteMCJIT)" 647 648 // Remote target MCJIT doesn't (yet) support static constructors. No reason 649 // it couldn't. This is a limitation of the LLI implemantation, not the 650 // MCJIT itself. FIXME. 651 652 // Lanch the remote process and get a channel to it. 653 std::unique_ptr<FDRPCChannel> C = launchRemote(); 654 if (!C) { 655 errs() << "Failed to launch remote JIT.\n"; 656 exit(1); 657 } 658 659 // Create a remote target client running over the channel. 660 typedef orc::remote::OrcRemoteTargetClient<orc::remote::RPCChannel> MyRemote; 661 ErrorOr<MyRemote> R = MyRemote::Create(*C); 662 if (!R) { 663 errs() << "Could not create remote: " << R.getError().message() << "\n"; 664 exit(1); 665 } 666 667 // Create a remote memory manager. 668 std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM; 669 if (auto EC = R->createRemoteMemoryManager(RemoteMM)) { 670 errs() << "Could not create remote memory manager: " << EC.message() << "\n"; 671 exit(1); 672 } 673 674 // Forward MCJIT's memory manager calls to the remote memory manager. 675 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr( 676 std::move(RemoteMM)); 677 678 // Forward MCJIT's symbol resolution calls to the remote. 679 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setResolver( 680 orc::createLambdaResolver( 681 [&](const std::string &Name) { 682 orc::TargetAddress Addr = 0; 683 if (auto EC = R->getSymbolAddress(Addr, Name)) { 684 errs() << "Failure during symbol lookup: " << EC.message() << "\n"; 685 exit(1); 686 } 687 return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported); 688 }, 689 [](const std::string &Name) { return nullptr; } 690 )); 691 692 // Grab the target address of the JIT'd main function on the remote and call 693 // it. 694 // FIXME: argv and envp handling. 695 orc::TargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str()); 696 EE->finalizeObject(); 697 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x" 698 << format("%llx", Entry) << "\n"); 699 if (auto EC = R->callIntVoid(Result, Entry)) 700 errs() << "ERROR: " << EC.message() << "\n"; 701 702 // Like static constructors, the remote target MCJIT support doesn't handle 703 // this yet. It could. FIXME. 704 705 // Delete the EE - we need to tear it down *before* we terminate the session 706 // with the remote, otherwise it'll crash when it tries to release resources 707 // on a remote that has already been disconnected. 708 delete EE; 709 EE = nullptr; 710 711 // Signal the remote target that we're done JITing. 712 R->terminateSession(); 713 } 714 715 return Result; 716 } 717 718 std::unique_ptr<FDRPCChannel> launchRemote() { 719 #ifndef LLVM_ON_UNIX 720 llvm_unreachable("launchRemote not supported on non-Unix platforms"); 721 #else 722 int PipeFD[2][2]; 723 pid_t ChildPID; 724 725 // Create two pipes. 726 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0) 727 perror("Error creating pipe: "); 728 729 ChildPID = fork(); 730 731 if (ChildPID == 0) { 732 // In the child... 733 734 // Close the parent ends of the pipes 735 close(PipeFD[0][1]); 736 close(PipeFD[1][0]); 737 738 739 // Execute the child process. 740 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut; 741 { 742 ChildPath.reset(new char[ChildExecPath.size() + 1]); 743 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]); 744 ChildPath[ChildExecPath.size()] = '\0'; 745 std::string ChildInStr = utostr(PipeFD[0][0]); 746 ChildIn.reset(new char[ChildInStr.size() + 1]); 747 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]); 748 ChildIn[ChildInStr.size()] = '\0'; 749 std::string ChildOutStr = utostr(PipeFD[1][1]); 750 ChildOut.reset(new char[ChildOutStr.size() + 1]); 751 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]); 752 ChildOut[ChildOutStr.size()] = '\0'; 753 } 754 755 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr }; 756 int rc = execv(ChildExecPath.c_str(), args); 757 if (rc != 0) 758 perror("Error executing child process: "); 759 llvm_unreachable("Error executing child process"); 760 } 761 // else we're the parent... 762 763 // Close the child ends of the pipes 764 close(PipeFD[0][0]); 765 close(PipeFD[1][1]); 766 767 // Return an RPC channel connected to our end of the pipes. 768 return llvm::make_unique<FDRPCChannel>(PipeFD[1][0], PipeFD[0][1]); 769 #endif 770 } 771