1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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.inc"
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/JITEventListener.h"
26 #include "llvm/ExecutionEngine/MCJIT.h"
27 #include "llvm/ExecutionEngine/ObjectCache.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/OrcRemoteTargetClient.h"
32 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
33 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/IRReader/IRReader.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/ObjectFile.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/DynamicLibrary.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/InitLLVM.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/Memory.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/Path.h"
52 #include "llvm/Support/PluginLoader.h"
53 #include "llvm/Support/Process.h"
54 #include "llvm/Support/Program.h"
55 #include "llvm/Support/SourceMgr.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/WithColor.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/Instrumentation.h"
63 #include <cygwin/version.h>
64 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
65 #define DO_NOTHING_ATEXIT 1
71 #define DEBUG_TYPE "lli"
75 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
78 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
81 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
83 cl::opt<bool> ForceInterpreter("force-interpreter",
84 cl::desc("Force interpretation: disable JIT"),
87 cl::opt<JITKind> UseJITKind("jit-kind",
88 cl::desc("Choose underlying JIT kind."),
89 cl::init(JITKind::MCJIT),
91 clEnumValN(JITKind::MCJIT, "mcjit",
93 clEnumValN(JITKind::OrcMCJITReplacement,
95 "Orc-based MCJIT replacement"),
96 clEnumValN(JITKind::OrcLazy,
98 "Orc-based lazy JIT.")));
101 LazyJITCompileThreads("compile-threads",
102 cl::desc("Choose the number of compile threads "
103 "(jit-kind=orc-lazy only)"),
106 cl::list<std::string>
107 ThreadEntryPoints("thread-entry",
108 cl::desc("calls the given entry-point on a new thread "
109 "(jit-kind=orc-lazy only)"));
111 cl::opt<bool> PerModuleLazy(
113 cl::desc("Performs lazy compilation on whole module boundaries "
114 "rather than individual functions"),
117 cl::list<std::string>
119 cl::desc("Specifies the JITDylib to be used for any subsequent "
120 "-extra-module arguments."));
122 // The MCJIT supports building for a target address space separate from
123 // the JIT compilation process. Use a forked process and a copying
124 // memory manager with IPC to execute using this functionality.
125 cl::opt<bool> RemoteMCJIT("remote-mcjit",
126 cl::desc("Execute MCJIT'ed code in a separate process."),
129 // Manually specify the child process for remote execution. This overrides
130 // the simulated remote execution that allocates address space for child
131 // execution. The child process will be executed and will communicate with
132 // lli via stdin/stdout pipes.
134 ChildExecPath("mcjit-remote-process",
135 cl::desc("Specify the filename of the process to launch "
136 "for remote MCJIT execution. If none is specified,"
137 "\n\tremote execution will be simulated in-process."),
138 cl::value_desc("filename"), cl::init(""));
140 // Determine optimization level.
143 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
144 "(default = '-O2')"),
150 TargetTriple("mtriple", cl::desc("Override target triple for module"));
153 EntryFunc("entry-function",
154 cl::desc("Specify the entry function (default = 'main') "
155 "of the executable"),
156 cl::value_desc("function"),
159 cl::list<std::string>
160 ExtraModules("extra-module",
161 cl::desc("Extra modules to be loaded"),
162 cl::value_desc("input bitcode"));
164 cl::list<std::string>
165 ExtraObjects("extra-object",
166 cl::desc("Extra object files to be loaded"),
167 cl::value_desc("input object"));
169 cl::list<std::string>
170 ExtraArchives("extra-archive",
171 cl::desc("Extra archive files to be loaded"),
172 cl::value_desc("input archive"));
175 EnableCacheManager("enable-cache-manager",
176 cl::desc("Use cache manager to save/load mdoules"),
180 ObjectCacheDir("object-cache-dir",
181 cl::desc("Directory to store cached object files "
182 "(must be user writable)"),
186 FakeArgv0("fake-argv0",
187 cl::desc("Override the 'argv[0]' value passed into the executing"
188 " program"), cl::value_desc("executable"));
191 DisableCoreFiles("disable-core-files", cl::Hidden,
192 cl::desc("Disable emission of core files if possible"));
195 NoLazyCompilation("disable-lazy-compilation",
196 cl::desc("Disable JIT lazy compilation"),
200 GenerateSoftFloatCalls("soft-float",
201 cl::desc("Generate software floating point library calls"),
204 enum class DumpKind {
211 cl::opt<DumpKind> OrcDumpKind(
212 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
213 cl::init(DumpKind::NoDump),
214 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
215 "Don't dump anything."),
216 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
217 "Dump function names to stdout."),
218 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
219 "Dump modules to stdout."),
220 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
221 "Dump modules to the current "
222 "working directory. (WARNING: "
223 "will overwrite existing files).")),
226 ExitOnError ExitOnErr;
229 //===----------------------------------------------------------------------===//
232 // This object cache implementation writes cached objects to disk to the
233 // directory specified by CacheDir, using a filename provided in the module
234 // descriptor. The cache tries to load a saved object using that path if the
235 // file exists. CacheDir defaults to "", in which case objects are cached
236 // alongside their originating bitcodes.
238 class LLIObjectCache : public ObjectCache {
240 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
241 // Add trailing '/' to cache dir if necessary.
242 if (!this->CacheDir.empty() &&
243 this->CacheDir[this->CacheDir.size() - 1] != '/')
244 this->CacheDir += '/';
246 ~LLIObjectCache() override {}
248 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
249 const std::string &ModuleID = M->getModuleIdentifier();
250 std::string CacheName;
251 if (!getCacheFilename(ModuleID, CacheName))
253 if (!CacheDir.empty()) { // Create user-defined cache dir.
254 SmallString<128> dir(sys::path::parent_path(CacheName));
255 sys::fs::create_directories(Twine(dir));
258 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
259 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
263 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
264 const std::string &ModuleID = M->getModuleIdentifier();
265 std::string CacheName;
266 if (!getCacheFilename(ModuleID, CacheName))
268 // Load the object from the cache filename
269 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
270 MemoryBuffer::getFile(CacheName, -1, false);
271 // If the file isn't there, that's OK.
274 // MCJIT will want to write into this buffer, and we don't want that
275 // because the file has probably just been mmapped. Instead we make
276 // a copy. The filed-based buffer will be released when it goes
278 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
282 std::string CacheDir;
284 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
285 std::string Prefix("file:");
286 size_t PrefixLength = Prefix.length();
287 if (ModID.substr(0, PrefixLength) != Prefix)
289 std::string CacheSubdir = ModID.substr(PrefixLength);
291 // Transform "X:\foo" => "/X\foo" for convenience.
292 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
293 CacheSubdir[1] = CacheSubdir[0];
294 CacheSubdir[0] = '/';
297 CacheName = CacheDir + CacheSubdir;
298 size_t pos = CacheName.rfind('.');
299 CacheName.replace(pos, CacheName.length() - pos, ".o");
304 // On Mingw and Cygwin, an external symbol named '__main' is called from the
305 // generated 'main' function to allow static initialization. To avoid linking
306 // problems with remote targets (because lli's remote target support does not
307 // currently handle external linking) we add a secondary module which defines
308 // an empty '__main' function.
309 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
310 StringRef TargetTripleStr) {
311 IRBuilder<> Builder(Context);
312 Triple TargetTriple(TargetTripleStr);
314 // Create a new module.
315 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
316 M->setTargetTriple(TargetTripleStr);
318 // Create an empty function named "__main".
320 if (TargetTriple.isArch64Bit())
321 ReturnTy = Type::getInt64Ty(Context);
323 ReturnTy = Type::getInt32Ty(Context);
325 Function::Create(FunctionType::get(ReturnTy, {}, false),
326 GlobalValue::ExternalLinkage, "__main", M.get());
328 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
329 Builder.SetInsertPoint(BB);
330 Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
331 Builder.CreateRet(ReturnVal);
333 // Add this new module to the ExecutionEngine.
334 EE.addModule(std::move(M));
337 CodeGenOpt::Level getOptLevel() {
340 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
342 case '0': return CodeGenOpt::None;
343 case '1': return CodeGenOpt::Less;
345 case '2': return CodeGenOpt::Default;
346 case '3': return CodeGenOpt::Aggressive;
348 llvm_unreachable("Unrecognized opt level.");
351 LLVM_ATTRIBUTE_NORETURN
352 static void reportError(SMDiagnostic Err, const char *ProgName) {
353 Err.print(ProgName, errs());
357 int runOrcLazyJIT(const char *ProgName);
358 void disallowOrcOptions();
360 //===----------------------------------------------------------------------===//
361 // main Driver function
363 int main(int argc, char **argv, char * const *envp) {
364 InitLLVM X(argc, argv);
367 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
369 // If we have a native target, initialize it to ensure it is linked in and
370 // usable by the JIT.
371 InitializeNativeTarget();
372 InitializeNativeTargetAsmPrinter();
373 InitializeNativeTargetAsmParser();
375 cl::ParseCommandLineOptions(argc, argv,
376 "llvm interpreter & dynamic compiler\n");
378 // If the user doesn't want core files, disable them.
379 if (DisableCoreFiles)
380 sys::Process::PreventCoreFiles();
382 if (UseJITKind == JITKind::OrcLazy)
383 return runOrcLazyJIT(argv[0]);
385 disallowOrcOptions();
389 // Load the bitcode...
391 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
392 Module *Mod = Owner.get();
394 reportError(Err, argv[0]);
396 if (EnableCacheManager) {
397 std::string CacheName("file:");
398 CacheName.append(InputFile);
399 Mod->setModuleIdentifier(CacheName);
402 // If not jitting lazily, load the whole bitcode file eagerly too.
403 if (NoLazyCompilation) {
404 // Use *argv instead of argv[0] to work around a wrong GCC warning.
405 ExitOnError ExitOnErr(std::string(*argv) +
406 ": bitcode didn't read correctly: ");
407 ExitOnErr(Mod->materializeAll());
410 std::string ErrorMsg;
411 EngineBuilder builder(std::move(Owner));
412 builder.setMArch(MArch);
413 builder.setMCPU(getCPUStr());
414 builder.setMAttrs(getFeatureList());
415 if (RelocModel.getNumOccurrences())
416 builder.setRelocationModel(RelocModel);
417 if (CMModel.getNumOccurrences())
418 builder.setCodeModel(CMModel);
419 builder.setErrorStr(&ErrorMsg);
420 builder.setEngineKind(ForceInterpreter
421 ? EngineKind::Interpreter
423 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
425 // If we are supposed to override the target triple, do so now.
426 if (!TargetTriple.empty())
427 Mod->setTargetTriple(Triple::normalize(TargetTriple));
429 // Enable MCJIT if desired.
430 RTDyldMemoryManager *RTDyldMM = nullptr;
431 if (!ForceInterpreter) {
433 RTDyldMM = new ForwardingMemoryManager();
435 RTDyldMM = new SectionMemoryManager();
437 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
438 // RTDyldMM: We still use it below, even though we don't own it.
439 builder.setMCJITMemoryManager(
440 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
441 } else if (RemoteMCJIT) {
442 WithColor::error(errs(), argv[0])
443 << "remote process execution does not work with the interpreter.\n";
447 builder.setOptLevel(getOptLevel());
449 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
450 if (FloatABIForCalls != FloatABI::Default)
451 Options.FloatABIType = FloatABIForCalls;
453 builder.setTargetOptions(Options);
455 std::unique_ptr<ExecutionEngine> EE(builder.create());
457 if (!ErrorMsg.empty())
458 WithColor::error(errs(), argv[0])
459 << "error creating EE: " << ErrorMsg << "\n";
461 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
465 std::unique_ptr<LLIObjectCache> CacheManager;
466 if (EnableCacheManager) {
467 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
468 EE->setObjectCache(CacheManager.get());
471 // Load any additional modules specified on the command line.
472 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
473 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
475 reportError(Err, argv[0]);
476 if (EnableCacheManager) {
477 std::string CacheName("file:");
478 CacheName.append(ExtraModules[i]);
479 XMod->setModuleIdentifier(CacheName);
481 EE->addModule(std::move(XMod));
484 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
485 Expected<object::OwningBinary<object::ObjectFile>> Obj =
486 object::ObjectFile::createObjectFile(ExtraObjects[i]);
488 // TODO: Actually report errors helpfully.
489 consumeError(Obj.takeError());
490 reportError(Err, argv[0]);
492 object::OwningBinary<object::ObjectFile> &O = Obj.get();
493 EE->addObjectFile(std::move(O));
496 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
497 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
498 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
500 reportError(Err, argv[0]);
501 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
503 Expected<std::unique_ptr<object::Archive>> ArOrErr =
504 object::Archive::create(ArBuf->getMemBufferRef());
507 raw_string_ostream OS(Buf);
508 logAllUnhandledErrors(ArOrErr.takeError(), OS);
513 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
515 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
517 EE->addArchive(std::move(OB));
520 // If the target is Cygwin/MingW and we are generating remote code, we
521 // need an extra module to help out with linking.
522 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
523 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
526 // The following functions have no effect if their respective profiling
527 // support wasn't enabled in the build configuration.
528 EE->RegisterJITEventListener(
529 JITEventListener::createOProfileJITEventListener());
530 EE->RegisterJITEventListener(
531 JITEventListener::createIntelJITEventListener());
533 EE->RegisterJITEventListener(
534 JITEventListener::createPerfJITEventListener());
536 if (!NoLazyCompilation && RemoteMCJIT) {
537 WithColor::warning(errs(), argv[0])
538 << "remote mcjit does not support lazy compilation\n";
539 NoLazyCompilation = true;
541 EE->DisableLazyCompilation(NoLazyCompilation);
543 // If the user specifically requested an argv[0] to pass into the program,
545 if (!FakeArgv0.empty()) {
546 InputFile = static_cast<std::string>(FakeArgv0);
548 // Otherwise, if there is a .bc suffix on the executable strip it off, it
549 // might confuse the program.
550 if (StringRef(InputFile).endswith(".bc"))
551 InputFile.erase(InputFile.length() - 3);
554 // Add the module's name to the start of the vector of arguments to main().
555 InputArgv.insert(InputArgv.begin(), InputFile);
557 // Call the main function from M as if its signature were:
558 // int main (int argc, char **argv, const char **envp)
559 // using the contents of Args to determine argc & argv, and the contents of
560 // EnvVars to determine envp.
562 Function *EntryFn = Mod->getFunction(EntryFunc);
564 WithColor::error(errs(), argv[0])
565 << '\'' << EntryFunc << "\' function not found in module.\n";
569 // Reset errno to zero on entry to main.
574 // Sanity check use of remote-jit: LLI currently only supports use of the
575 // remote JIT on Unix platforms.
578 WithColor::warning(errs(), argv[0])
579 << "host does not support external remote targets.\n";
580 WithColor::note() << "defaulting to local execution\n";
583 if (ChildExecPath.empty()) {
584 WithColor::error(errs(), argv[0])
585 << "-remote-mcjit requires -mcjit-remote-process.\n";
587 } else if (!sys::fs::can_execute(ChildExecPath)) {
588 WithColor::error(errs(), argv[0])
589 << "unable to find usable child executable: '" << ChildExecPath
597 // If the program doesn't explicitly call exit, we will need the Exit
598 // function later on to make an explicit call, so get the function now.
599 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
600 Type::getInt32Ty(Context));
602 // Run static constructors.
603 if (!ForceInterpreter) {
604 // Give MCJIT a chance to apply relocations and set page permissions.
605 EE->finalizeObject();
607 EE->runStaticConstructorsDestructors(false);
609 // Trigger compilation separately so code regions that need to be
610 // invalidated will be known.
611 (void)EE->getPointerToFunction(EntryFn);
612 // Clear instruction cache before code will be executed.
614 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
617 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
619 // Run static destructors.
620 EE->runStaticConstructorsDestructors(true);
622 // If the program didn't call exit explicitly, we should call it now.
623 // This ensures that any atexit handlers get called correctly.
624 if (Function *ExitF = dyn_cast<Function>(Exit)) {
625 std::vector<GenericValue> Args;
626 GenericValue ResultGV;
627 ResultGV.IntVal = APInt(32, Result);
628 Args.push_back(ResultGV);
629 EE->runFunction(ExitF, Args);
630 WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
633 WithColor::error(errs(), argv[0])
634 << "exit defined with wrong prototype!\n";
638 // else == "if (RemoteMCJIT)"
640 // Remote target MCJIT doesn't (yet) support static constructors. No reason
641 // it couldn't. This is a limitation of the LLI implementation, not the
642 // MCJIT itself. FIXME.
644 // Lanch the remote process and get a channel to it.
645 std::unique_ptr<FDRawChannel> C = launchRemote();
647 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
651 // Create a remote target client running over the channel.
652 llvm::orc::ExecutionSession ES;
653 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
654 typedef orc::remote::OrcRemoteTargetClient MyRemote;
655 auto R = ExitOnErr(MyRemote::Create(*C, ES));
657 // Create a remote memory manager.
658 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
660 // Forward MCJIT's memory manager calls to the remote memory manager.
661 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
662 std::move(RemoteMM));
664 // Forward MCJIT's symbol resolution calls to the remote.
665 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
666 orc::createLambdaResolver(
667 [](const std::string &Name) { return nullptr; },
668 [&](const std::string &Name) {
669 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
670 return JITSymbol(Addr, JITSymbolFlags::Exported);
671 return JITSymbol(nullptr);
674 // Grab the target address of the JIT'd main function on the remote and call
676 // FIXME: argv and envp handling.
677 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
678 EE->finalizeObject();
679 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
680 << format("%llx", Entry) << "\n");
681 Result = ExitOnErr(R->callIntVoid(Entry));
683 // Like static constructors, the remote target MCJIT support doesn't handle
684 // this yet. It could. FIXME.
686 // Delete the EE - we need to tear it down *before* we terminate the session
687 // with the remote, otherwise it'll crash when it tries to release resources
688 // on a remote that has already been disconnected.
691 // Signal the remote target that we're done JITing.
692 ExitOnErr(R->terminateSession());
698 static orc::IRTransformLayer::TransformFunction createDebugDumper() {
699 switch (OrcDumpKind) {
700 case DumpKind::NoDump:
701 return [](orc::ThreadSafeModule TSM,
702 const orc::MaterializationResponsibility &R) { return TSM; };
704 case DumpKind::DumpFuncsToStdOut:
705 return [](orc::ThreadSafeModule TSM,
706 const orc::MaterializationResponsibility &R) {
709 for (const auto &F : *TSM.getModule()) {
710 if (F.isDeclaration())
714 std::string Name(F.getName());
715 printf("%s ", Name.c_str());
724 case DumpKind::DumpModsToStdOut:
725 return [](orc::ThreadSafeModule TSM,
726 const orc::MaterializationResponsibility &R) {
727 outs() << "----- Module Start -----\n"
728 << *TSM.getModule() << "----- Module End -----\n";
733 case DumpKind::DumpModsToDisk:
734 return [](orc::ThreadSafeModule TSM,
735 const orc::MaterializationResponsibility &R) {
737 raw_fd_ostream Out(TSM.getModule()->getModuleIdentifier() + ".ll", EC,
740 errs() << "Couldn't open " << TSM.getModule()->getModuleIdentifier()
741 << " for dumping.\nError:" << EC.message() << "\n";
744 Out << *TSM.getModule();
748 llvm_unreachable("Unknown DumpKind");
751 static void exitOnLazyCallThroughFailure() { exit(1); }
753 int runOrcLazyJIT(const char *ProgName) {
754 // Start setting up the JIT environment.
756 // Parse the main module.
757 orc::ThreadSafeContext TSCtx(llvm::make_unique<LLVMContext>());
759 auto MainModule = orc::ThreadSafeModule(
760 parseIRFile(InputFile, Err, *TSCtx.getContext()), TSCtx);
762 reportError(Err, ProgName);
764 const auto &TT = MainModule.getModule()->getTargetTriple();
765 orc::JITTargetMachineBuilder JTMB =
766 TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
767 : orc::JITTargetMachineBuilder(Triple(TT));
770 JTMB.getTargetTriple().setArchName(MArch);
772 JTMB.setCPU(getCPUStr())
773 .addFeatures(getFeatureList())
774 .setRelocationModel(RelocModel.getNumOccurrences()
775 ? Optional<Reloc::Model>(RelocModel)
777 .setCodeModel(CMModel.getNumOccurrences()
778 ? Optional<CodeModel::Model>(CMModel)
781 DataLayout DL = ExitOnErr(JTMB.getDefaultDataLayoutForTarget());
783 auto J = ExitOnErr(orc::LLLazyJIT::Create(
785 pointerToJITTargetAddress(exitOnLazyCallThroughFailure),
786 LazyJITCompileThreads));
789 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
791 auto Dump = createDebugDumper();
793 J->setLazyCompileTransform([&](orc::ThreadSafeModule TSM,
794 const orc::MaterializationResponsibility &R) {
795 if (verifyModule(*TSM.getModule(), &dbgs())) {
796 dbgs() << "Bad module: " << *TSM.getModule() << "\n";
799 return Dump(std::move(TSM), R);
801 J->getMainJITDylib().setGenerator(
802 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(DL)));
804 orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
805 orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
806 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
808 // Add the main module.
809 ExitOnErr(J->addLazyIRModule(std::move(MainModule)));
811 // Create JITDylibs and add any extra modules.
813 // Create JITDylibs, keep a map from argument index to dylib. We will use
814 // -extra-module argument indexes to determine what dylib to use for each
816 std::map<unsigned, orc::JITDylib *> IdxToDylib;
817 IdxToDylib[0] = &J->getMainJITDylib();
818 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
819 JDItr != JDEnd; ++JDItr) {
820 IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] =
821 &J->createJITDylib(*JDItr);
824 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
825 EMItr != EMEnd; ++EMItr) {
826 auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
828 reportError(Err, ProgName);
830 auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
831 assert(EMIdx != 0 && "ExtraModule should have index > 0");
832 auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
833 auto &JD = *JDItr->second;
835 J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
840 for (auto &ObjPath : ExtraObjects) {
841 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
842 ExitOnErr(J->addObjectFile(std::move(Obj)));
845 // Generate a argument string.
846 std::vector<std::string> Args;
847 Args.push_back(InputFile);
848 for (auto &Arg : InputArgv)
851 // Run any static constructors.
852 ExitOnErr(J->runConstructors());
854 // Run any -thread-entry points.
855 std::vector<std::thread> AltEntryThreads;
856 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
857 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
858 typedef void (*EntryPointPtr)();
860 reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
861 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
864 J->getExecutionSession().dump(llvm::dbgs());
867 auto MainSym = ExitOnErr(J->lookup("main"));
868 typedef int (*MainFnPtr)(int, const char *[]);
869 std::vector<const char *> ArgV;
870 for (auto &Arg : Args)
871 ArgV.push_back(Arg.c_str());
872 ArgV.push_back(nullptr);
874 int ArgC = ArgV.size() - 1;
876 reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
877 auto Result = Main(ArgC, (const char **)ArgV.data());
879 // Wait for -entry-point threads.
880 for (auto &AltEntryThread : AltEntryThreads)
881 AltEntryThread.join();
884 ExitOnErr(J->runDestructors());
885 CXXRuntimeOverrides.runDestructors();
890 void disallowOrcOptions() {
891 // Make sure nobody used an orc-lazy specific option accidentally.
893 if (LazyJITCompileThreads != 0) {
894 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
898 if (!ThreadEntryPoints.empty()) {
899 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
904 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
909 std::unique_ptr<FDRawChannel> launchRemote() {
911 llvm_unreachable("launchRemote not supported on non-Unix platforms");
917 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
918 perror("Error creating pipe: ");
925 // Close the parent ends of the pipes
930 // Execute the child process.
931 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
933 ChildPath.reset(new char[ChildExecPath.size() + 1]);
934 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
935 ChildPath[ChildExecPath.size()] = '\0';
936 std::string ChildInStr = utostr(PipeFD[0][0]);
937 ChildIn.reset(new char[ChildInStr.size() + 1]);
938 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
939 ChildIn[ChildInStr.size()] = '\0';
940 std::string ChildOutStr = utostr(PipeFD[1][1]);
941 ChildOut.reset(new char[ChildOutStr.size() + 1]);
942 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
943 ChildOut[ChildOutStr.size()] = '\0';
946 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
947 int rc = execv(ChildExecPath.c_str(), args);
949 perror("Error executing child process: ");
950 llvm_unreachable("Error executing child process");
952 // else we're the parent...
954 // Close the child ends of the pipes
958 // Return an RPC channel connected to our end of the pipes.
959 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);