1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
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
7 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "RemoteJITUtils.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/BitcodeReader.h"
19 #include "llvm/CodeGen/CommandFlags.inc"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/ExecutionEngine/Interpreter.h"
24 #include "llvm/ExecutionEngine/JITEventListener.h"
25 #include "llvm/ExecutionEngine/MCJIT.h"
26 #include "llvm/ExecutionEngine/ObjectCache.h"
27 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
28 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
29 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
30 #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
31 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
32 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/IRReader/IRReader.h"
39 #include "llvm/Object/Archive.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/DynamicLibrary.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/ManagedStatic.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/Memory.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Path.h"
51 #include "llvm/Support/PluginLoader.h"
52 #include "llvm/Support/Process.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/SourceMgr.h"
55 #include "llvm/Support/TargetSelect.h"
56 #include "llvm/Support/WithColor.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Instrumentation.h"
62 #include <cygwin/version.h>
63 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
64 #define DO_NOTHING_ATEXIT 1
70 #define DEBUG_TYPE "lli"
74 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
77 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
80 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
82 cl::opt<bool> ForceInterpreter("force-interpreter",
83 cl::desc("Force interpretation: disable JIT"),
86 cl::opt<JITKind> UseJITKind(
87 "jit-kind", cl::desc("Choose underlying JIT kind."),
88 cl::init(JITKind::MCJIT),
89 cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
90 clEnumValN(JITKind::OrcMCJITReplacement, "orc-mcjit",
91 "Orc-based MCJIT replacement "
93 clEnumValN(JITKind::OrcLazy, "orc-lazy",
94 "Orc-based lazy JIT.")));
97 LazyJITCompileThreads("compile-threads",
98 cl::desc("Choose the number of compile threads "
99 "(jit-kind=orc-lazy only)"),
102 cl::list<std::string>
103 ThreadEntryPoints("thread-entry",
104 cl::desc("calls the given entry-point on a new thread "
105 "(jit-kind=orc-lazy only)"));
107 cl::opt<bool> PerModuleLazy(
109 cl::desc("Performs lazy compilation on whole module boundaries "
110 "rather than individual functions"),
113 cl::list<std::string>
115 cl::desc("Specifies the JITDylib to be used for any subsequent "
116 "-extra-module arguments."));
118 // The MCJIT supports building for a target address space separate from
119 // the JIT compilation process. Use a forked process and a copying
120 // memory manager with IPC to execute using this functionality.
121 cl::opt<bool> RemoteMCJIT("remote-mcjit",
122 cl::desc("Execute MCJIT'ed code in a separate process."),
125 // Manually specify the child process for remote execution. This overrides
126 // the simulated remote execution that allocates address space for child
127 // execution. The child process will be executed and will communicate with
128 // lli via stdin/stdout pipes.
130 ChildExecPath("mcjit-remote-process",
131 cl::desc("Specify the filename of the process to launch "
132 "for remote MCJIT execution. If none is specified,"
133 "\n\tremote execution will be simulated in-process."),
134 cl::value_desc("filename"), cl::init(""));
136 // Determine optimization level.
139 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
140 "(default = '-O2')"),
146 TargetTriple("mtriple", cl::desc("Override target triple for module"));
149 EntryFunc("entry-function",
150 cl::desc("Specify the entry function (default = 'main') "
151 "of the executable"),
152 cl::value_desc("function"),
155 cl::list<std::string>
156 ExtraModules("extra-module",
157 cl::desc("Extra modules to be loaded"),
158 cl::value_desc("input bitcode"));
160 cl::list<std::string>
161 ExtraObjects("extra-object",
162 cl::desc("Extra object files to be loaded"),
163 cl::value_desc("input object"));
165 cl::list<std::string>
166 ExtraArchives("extra-archive",
167 cl::desc("Extra archive files to be loaded"),
168 cl::value_desc("input archive"));
171 EnableCacheManager("enable-cache-manager",
172 cl::desc("Use cache manager to save/load modules"),
176 ObjectCacheDir("object-cache-dir",
177 cl::desc("Directory to store cached object files "
178 "(must be user writable)"),
182 FakeArgv0("fake-argv0",
183 cl::desc("Override the 'argv[0]' value passed into the executing"
184 " program"), cl::value_desc("executable"));
187 DisableCoreFiles("disable-core-files", cl::Hidden,
188 cl::desc("Disable emission of core files if possible"));
191 NoLazyCompilation("disable-lazy-compilation",
192 cl::desc("Disable JIT lazy compilation"),
196 GenerateSoftFloatCalls("soft-float",
197 cl::desc("Generate software floating point library calls"),
200 cl::opt<bool> NoProcessSymbols(
202 cl::desc("Do not resolve lli process symbols in JIT'd code"),
205 enum class DumpKind {
212 cl::opt<DumpKind> OrcDumpKind(
213 "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
214 cl::init(DumpKind::NoDump),
215 cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
216 "Don't dump anything."),
217 clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
218 "Dump function names to stdout."),
219 clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
220 "Dump modules to stdout."),
221 clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
222 "Dump modules to the current "
223 "working directory. (WARNING: "
224 "will overwrite existing files).")),
227 ExitOnError ExitOnErr;
230 //===----------------------------------------------------------------------===//
233 // This object cache implementation writes cached objects to disk to the
234 // directory specified by CacheDir, using a filename provided in the module
235 // descriptor. The cache tries to load a saved object using that path if the
236 // file exists. CacheDir defaults to "", in which case objects are cached
237 // alongside their originating bitcodes.
239 class LLIObjectCache : public ObjectCache {
241 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
242 // Add trailing '/' to cache dir if necessary.
243 if (!this->CacheDir.empty() &&
244 this->CacheDir[this->CacheDir.size() - 1] != '/')
245 this->CacheDir += '/';
247 ~LLIObjectCache() override {}
249 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
250 const std::string &ModuleID = M->getModuleIdentifier();
251 std::string CacheName;
252 if (!getCacheFilename(ModuleID, CacheName))
254 if (!CacheDir.empty()) { // Create user-defined cache dir.
255 SmallString<128> dir(sys::path::parent_path(CacheName));
256 sys::fs::create_directories(Twine(dir));
259 raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
260 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
264 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
265 const std::string &ModuleID = M->getModuleIdentifier();
266 std::string CacheName;
267 if (!getCacheFilename(ModuleID, CacheName))
269 // Load the object from the cache filename
270 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
271 MemoryBuffer::getFile(CacheName, -1, false);
272 // If the file isn't there, that's OK.
275 // MCJIT will want to write into this buffer, and we don't want that
276 // because the file has probably just been mmapped. Instead we make
277 // a copy. The filed-based buffer will be released when it goes
279 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
283 std::string CacheDir;
285 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
286 std::string Prefix("file:");
287 size_t PrefixLength = Prefix.length();
288 if (ModID.substr(0, PrefixLength) != Prefix)
290 std::string CacheSubdir = ModID.substr(PrefixLength);
292 // Transform "X:\foo" => "/X\foo" for convenience.
293 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
294 CacheSubdir[1] = CacheSubdir[0];
295 CacheSubdir[0] = '/';
298 CacheName = CacheDir + CacheSubdir;
299 size_t pos = CacheName.rfind('.');
300 CacheName.replace(pos, CacheName.length() - pos, ".o");
305 // On Mingw and Cygwin, an external symbol named '__main' is called from the
306 // generated 'main' function to allow static initialization. To avoid linking
307 // problems with remote targets (because lli's remote target support does not
308 // currently handle external linking) we add a secondary module which defines
309 // an empty '__main' function.
310 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
311 StringRef TargetTripleStr) {
312 IRBuilder<> Builder(Context);
313 Triple TargetTriple(TargetTripleStr);
315 // Create a new module.
316 std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
317 M->setTargetTriple(TargetTripleStr);
319 // Create an empty function named "__main".
321 if (TargetTriple.isArch64Bit())
322 ReturnTy = Type::getInt64Ty(Context);
324 ReturnTy = Type::getInt32Ty(Context);
326 Function::Create(FunctionType::get(ReturnTy, {}, false),
327 GlobalValue::ExternalLinkage, "__main", M.get());
329 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
330 Builder.SetInsertPoint(BB);
331 Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
332 Builder.CreateRet(ReturnVal);
334 // Add this new module to the ExecutionEngine.
335 EE.addModule(std::move(M));
338 CodeGenOpt::Level getOptLevel() {
341 WithColor::error(errs(), "lli") << "invalid optimization level.\n";
343 case '0': return CodeGenOpt::None;
344 case '1': return CodeGenOpt::Less;
346 case '2': return CodeGenOpt::Default;
347 case '3': return CodeGenOpt::Aggressive;
349 llvm_unreachable("Unrecognized opt level.");
352 LLVM_ATTRIBUTE_NORETURN
353 static void reportError(SMDiagnostic Err, const char *ProgName) {
354 Err.print(ProgName, errs());
358 int runOrcLazyJIT(const char *ProgName);
359 void disallowOrcOptions();
361 //===----------------------------------------------------------------------===//
362 // main Driver function
364 int main(int argc, char **argv, char * const *envp) {
365 InitLLVM X(argc, argv);
368 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
370 // If we have a native target, initialize it to ensure it is linked in and
371 // usable by the JIT.
372 InitializeNativeTarget();
373 InitializeNativeTargetAsmPrinter();
374 InitializeNativeTargetAsmParser();
376 cl::ParseCommandLineOptions(argc, argv,
377 "llvm interpreter & dynamic compiler\n");
379 // If the user doesn't want core files, disable them.
380 if (DisableCoreFiles)
381 sys::Process::PreventCoreFiles();
383 if (UseJITKind == JITKind::OrcLazy)
384 return runOrcLazyJIT(argv[0]);
386 disallowOrcOptions();
390 // Load the bitcode...
392 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
393 Module *Mod = Owner.get();
395 reportError(Err, argv[0]);
397 if (EnableCacheManager) {
398 std::string CacheName("file:");
399 CacheName.append(InputFile);
400 Mod->setModuleIdentifier(CacheName);
403 // If not jitting lazily, load the whole bitcode file eagerly too.
404 if (NoLazyCompilation) {
405 // Use *argv instead of argv[0] to work around a wrong GCC warning.
406 ExitOnError ExitOnErr(std::string(*argv) +
407 ": bitcode didn't read correctly: ");
408 ExitOnErr(Mod->materializeAll());
411 std::string ErrorMsg;
412 EngineBuilder builder(std::move(Owner));
413 builder.setMArch(MArch);
414 builder.setMCPU(getCPUStr());
415 builder.setMAttrs(getFeatureList());
416 if (RelocModel.getNumOccurrences())
417 builder.setRelocationModel(RelocModel);
418 if (CMModel.getNumOccurrences())
419 builder.setCodeModel(CMModel);
420 builder.setErrorStr(&ErrorMsg);
421 builder.setEngineKind(ForceInterpreter
422 ? EngineKind::Interpreter
424 builder.setUseOrcMCJITReplacement(AcknowledgeORCv1Deprecation,
425 UseJITKind == JITKind::OrcMCJITReplacement);
427 // If we are supposed to override the target triple, do so now.
428 if (!TargetTriple.empty())
429 Mod->setTargetTriple(Triple::normalize(TargetTriple));
431 // Enable MCJIT if desired.
432 RTDyldMemoryManager *RTDyldMM = nullptr;
433 if (!ForceInterpreter) {
435 RTDyldMM = new ForwardingMemoryManager();
437 RTDyldMM = new SectionMemoryManager();
439 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
440 // RTDyldMM: We still use it below, even though we don't own it.
441 builder.setMCJITMemoryManager(
442 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
443 } else if (RemoteMCJIT) {
444 WithColor::error(errs(), argv[0])
445 << "remote process execution does not work with the interpreter.\n";
449 builder.setOptLevel(getOptLevel());
451 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
452 if (FloatABIForCalls != FloatABI::Default)
453 Options.FloatABIType = FloatABIForCalls;
455 builder.setTargetOptions(Options);
457 std::unique_ptr<ExecutionEngine> EE(builder.create());
459 if (!ErrorMsg.empty())
460 WithColor::error(errs(), argv[0])
461 << "error creating EE: " << ErrorMsg << "\n";
463 WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
467 std::unique_ptr<LLIObjectCache> CacheManager;
468 if (EnableCacheManager) {
469 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
470 EE->setObjectCache(CacheManager.get());
473 // Load any additional modules specified on the command line.
474 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
475 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
477 reportError(Err, argv[0]);
478 if (EnableCacheManager) {
479 std::string CacheName("file:");
480 CacheName.append(ExtraModules[i]);
481 XMod->setModuleIdentifier(CacheName);
483 EE->addModule(std::move(XMod));
486 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
487 Expected<object::OwningBinary<object::ObjectFile>> Obj =
488 object::ObjectFile::createObjectFile(ExtraObjects[i]);
490 // TODO: Actually report errors helpfully.
491 consumeError(Obj.takeError());
492 reportError(Err, argv[0]);
494 object::OwningBinary<object::ObjectFile> &O = Obj.get();
495 EE->addObjectFile(std::move(O));
498 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
499 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
500 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
502 reportError(Err, argv[0]);
503 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
505 Expected<std::unique_ptr<object::Archive>> ArOrErr =
506 object::Archive::create(ArBuf->getMemBufferRef());
509 raw_string_ostream OS(Buf);
510 logAllUnhandledErrors(ArOrErr.takeError(), OS);
515 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
517 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
519 EE->addArchive(std::move(OB));
522 // If the target is Cygwin/MingW and we are generating remote code, we
523 // need an extra module to help out with linking.
524 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
525 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
528 // The following functions have no effect if their respective profiling
529 // support wasn't enabled in the build configuration.
530 EE->RegisterJITEventListener(
531 JITEventListener::createOProfileJITEventListener());
532 EE->RegisterJITEventListener(
533 JITEventListener::createIntelJITEventListener());
535 EE->RegisterJITEventListener(
536 JITEventListener::createPerfJITEventListener());
538 if (!NoLazyCompilation && RemoteMCJIT) {
539 WithColor::warning(errs(), argv[0])
540 << "remote mcjit does not support lazy compilation\n";
541 NoLazyCompilation = true;
543 EE->DisableLazyCompilation(NoLazyCompilation);
545 // If the user specifically requested an argv[0] to pass into the program,
547 if (!FakeArgv0.empty()) {
548 InputFile = static_cast<std::string>(FakeArgv0);
550 // Otherwise, if there is a .bc suffix on the executable strip it off, it
551 // might confuse the program.
552 if (StringRef(InputFile).endswith(".bc"))
553 InputFile.erase(InputFile.length() - 3);
556 // Add the module's name to the start of the vector of arguments to main().
557 InputArgv.insert(InputArgv.begin(), InputFile);
559 // Call the main function from M as if its signature were:
560 // int main (int argc, char **argv, const char **envp)
561 // using the contents of Args to determine argc & argv, and the contents of
562 // EnvVars to determine envp.
564 Function *EntryFn = Mod->getFunction(EntryFunc);
566 WithColor::error(errs(), argv[0])
567 << '\'' << EntryFunc << "\' function not found in module.\n";
571 // Reset errno to zero on entry to main.
576 // Sanity check use of remote-jit: LLI currently only supports use of the
577 // remote JIT on Unix platforms.
580 WithColor::warning(errs(), argv[0])
581 << "host does not support external remote targets.\n";
582 WithColor::note() << "defaulting to local execution\n";
585 if (ChildExecPath.empty()) {
586 WithColor::error(errs(), argv[0])
587 << "-remote-mcjit requires -mcjit-remote-process.\n";
589 } else if (!sys::fs::can_execute(ChildExecPath)) {
590 WithColor::error(errs(), argv[0])
591 << "unable to find usable child executable: '" << ChildExecPath
599 // If the program doesn't explicitly call exit, we will need the Exit
600 // function later on to make an explicit call, so get the function now.
601 FunctionCallee Exit = Mod->getOrInsertFunction(
602 "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
604 // Run static constructors.
605 if (!ForceInterpreter) {
606 // Give MCJIT a chance to apply relocations and set page permissions.
607 EE->finalizeObject();
609 EE->runStaticConstructorsDestructors(false);
611 // Trigger compilation separately so code regions that need to be
612 // invalidated will be known.
613 (void)EE->getPointerToFunction(EntryFn);
614 // Clear instruction cache before code will be executed.
616 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
619 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
621 // Run static destructors.
622 EE->runStaticConstructorsDestructors(true);
624 // If the program didn't call exit explicitly, we should call it now.
625 // This ensures that any atexit handlers get called correctly.
626 if (Function *ExitF =
627 dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
628 if (ExitF->getFunctionType() == Exit.getFunctionType()) {
629 std::vector<GenericValue> Args;
630 GenericValue ResultGV;
631 ResultGV.IntVal = APInt(32, Result);
632 Args.push_back(ResultGV);
633 EE->runFunction(ExitF, Args);
634 WithColor::error(errs(), argv[0])
635 << "exit(" << Result << ") returned!\n";
639 WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
642 // else == "if (RemoteMCJIT)"
644 // Remote target MCJIT doesn't (yet) support static constructors. No reason
645 // it couldn't. This is a limitation of the LLI implementation, not the
646 // MCJIT itself. FIXME.
648 // Lanch the remote process and get a channel to it.
649 std::unique_ptr<FDRawChannel> C = launchRemote();
651 WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
655 // Create a remote target client running over the channel.
656 llvm::orc::ExecutionSession ES;
657 ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
658 typedef orc::remote::OrcRemoteTargetClient MyRemote;
659 auto R = ExitOnErr(MyRemote::Create(*C, ES));
661 // Create a remote memory manager.
662 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
664 // Forward MCJIT's memory manager calls to the remote memory manager.
665 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
666 std::move(RemoteMM));
668 // Forward MCJIT's symbol resolution calls to the remote.
669 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
670 orc::createLambdaResolver(
671 AcknowledgeORCv1Deprecation,
672 [](const std::string &Name) { return nullptr; },
673 [&](const std::string &Name) {
674 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
675 return JITSymbol(Addr, JITSymbolFlags::Exported);
676 return JITSymbol(nullptr);
679 // Grab the target address of the JIT'd main function on the remote and call
681 // FIXME: argv and envp handling.
682 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
683 EE->finalizeObject();
684 LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
685 << format("%llx", Entry) << "\n");
686 Result = ExitOnErr(R->callIntVoid(Entry));
688 // Like static constructors, the remote target MCJIT support doesn't handle
689 // this yet. It could. FIXME.
691 // Delete the EE - we need to tear it down *before* we terminate the session
692 // with the remote, otherwise it'll crash when it tries to release resources
693 // on a remote that has already been disconnected.
696 // Signal the remote target that we're done JITing.
697 ExitOnErr(R->terminateSession());
703 static std::function<void(Module &)> createDebugDumper() {
704 switch (OrcDumpKind) {
705 case DumpKind::NoDump:
706 return [](Module &M) {};
708 case DumpKind::DumpFuncsToStdOut:
709 return [](Module &M) {
712 for (const auto &F : M) {
713 if (F.isDeclaration())
717 std::string Name(F.getName());
718 printf("%s ", Name.c_str());
726 case DumpKind::DumpModsToStdOut:
727 return [](Module &M) {
728 outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
731 case DumpKind::DumpModsToDisk:
732 return [](Module &M) {
734 raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC, sys::fs::OF_Text);
736 errs() << "Couldn't open " << M.getModuleIdentifier()
737 << " for dumping.\nError:" << EC.message() << "\n";
743 llvm_unreachable("Unknown DumpKind");
746 static void exitOnLazyCallThroughFailure() { exit(1); }
748 int runOrcLazyJIT(const char *ProgName) {
749 // Start setting up the JIT environment.
751 // Parse the main module.
752 orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
754 auto MainModule = parseIRFile(InputFile, Err, *TSCtx.getContext());
756 reportError(Err, ProgName);
758 const auto &TT = MainModule->getTargetTriple();
759 orc::LLLazyJITBuilder Builder;
761 Builder.setJITTargetMachineBuilder(
762 TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
763 : orc::JITTargetMachineBuilder(Triple(TT)));
766 Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(MArch);
768 Builder.getJITTargetMachineBuilder()
769 ->setCPU(getCPUStr())
770 .addFeatures(getFeatureList())
771 .setRelocationModel(RelocModel.getNumOccurrences()
772 ? Optional<Reloc::Model>(RelocModel)
774 .setCodeModel(CMModel.getNumOccurrences()
775 ? Optional<CodeModel::Model>(CMModel)
778 Builder.setLazyCompileFailureAddr(
779 pointerToJITTargetAddress(exitOnLazyCallThroughFailure));
780 Builder.setNumCompileThreads(LazyJITCompileThreads);
782 auto J = ExitOnErr(Builder.create());
785 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
787 auto Dump = createDebugDumper();
789 J->setLazyCompileTransform([&](orc::ThreadSafeModule TSM,
790 const orc::MaterializationResponsibility &R) {
791 TSM.withModuleDo([&](Module &M) {
792 if (verifyModule(M, &dbgs())) {
793 dbgs() << "Bad module: " << &M << "\n";
801 orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
803 // Unless they've been explicitly disabled, make process symbols available to
805 if (!NoProcessSymbols)
806 J->getMainJITDylib().addGenerator(
807 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
808 J->getDataLayout().getGlobalPrefix(),
809 [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) {
810 return Name != MainName;
813 orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
814 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
816 // Add the main module.
818 J->addLazyIRModule(orc::ThreadSafeModule(std::move(MainModule), TSCtx)));
820 // Create JITDylibs and add any extra modules.
822 // Create JITDylibs, keep a map from argument index to dylib. We will use
823 // -extra-module argument indexes to determine what dylib to use for each
825 std::map<unsigned, orc::JITDylib *> IdxToDylib;
826 IdxToDylib[0] = &J->getMainJITDylib();
827 for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
828 JDItr != JDEnd; ++JDItr) {
829 orc::JITDylib *JD = J->getJITDylibByName(*JDItr);
831 JD = &J->createJITDylib(*JDItr);
832 IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;
835 for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
836 EMItr != EMEnd; ++EMItr) {
837 auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
839 reportError(Err, ProgName);
841 auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
842 assert(EMIdx != 0 && "ExtraModule should have index > 0");
843 auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
844 auto &JD = *JDItr->second;
846 J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
849 for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
850 EAItr != EAEnd; ++EAItr) {
851 auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());
852 assert(EAIdx != 0 && "ExtraArchive should have index > 0");
853 auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));
854 auto &JD = *JDItr->second;
855 JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load(
856 J->getObjLinkingLayer(), EAItr->c_str())));
861 for (auto &ObjPath : ExtraObjects) {
862 auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
863 ExitOnErr(J->addObjectFile(std::move(Obj)));
866 // Run any static constructors.
867 ExitOnErr(J->runConstructors());
869 // Run any -thread-entry points.
870 std::vector<std::thread> AltEntryThreads;
871 for (auto &ThreadEntryPoint : ThreadEntryPoints) {
872 auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
873 typedef void (*EntryPointPtr)();
875 reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
876 AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
880 auto MainSym = ExitOnErr(J->lookup("main"));
882 typedef int (*MainFnPtr)(int, char *[]);
883 auto Result = orc::runAsMain(
884 jitTargetAddressToFunction<MainFnPtr>(MainSym.getAddress()), InputArgv,
885 StringRef(InputFile));
887 // Wait for -entry-point threads.
888 for (auto &AltEntryThread : AltEntryThreads)
889 AltEntryThread.join();
892 ExitOnErr(J->runDestructors());
893 CXXRuntimeOverrides.runDestructors();
898 void disallowOrcOptions() {
899 // Make sure nobody used an orc-lazy specific option accidentally.
901 if (LazyJITCompileThreads != 0) {
902 errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
906 if (!ThreadEntryPoints.empty()) {
907 errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
912 errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
917 std::unique_ptr<FDRawChannel> launchRemote() {
919 llvm_unreachable("launchRemote not supported on non-Unix platforms");
925 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
926 perror("Error creating pipe: ");
933 // Close the parent ends of the pipes
938 // Execute the child process.
939 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
941 ChildPath.reset(new char[ChildExecPath.size() + 1]);
942 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
943 ChildPath[ChildExecPath.size()] = '\0';
944 std::string ChildInStr = utostr(PipeFD[0][0]);
945 ChildIn.reset(new char[ChildInStr.size() + 1]);
946 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
947 ChildIn[ChildInStr.size()] = '\0';
948 std::string ChildOutStr = utostr(PipeFD[1][1]);
949 ChildOut.reset(new char[ChildOutStr.size() + 1]);
950 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
951 ChildOut[ChildOutStr.size()] = '\0';
954 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
955 int rc = execv(ChildExecPath.c_str(), args);
957 perror("Error executing child process: ");
958 llvm_unreachable("Error executing child process");
960 // else we're the parent...
962 // Close the child ends of the pipes
966 // Return an RPC channel connected to our end of the pipes.
967 return std::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);