xref: /freebsd/contrib/llvm-project/llvm/tools/lli/lli.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
10b57cec5SDimitry Andric //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This utility provides a simple wrapper around the LLVM Execution Engines,
100b57cec5SDimitry Andric // which allow the direct execution of LLVM programs through a Just-In-Time
110b57cec5SDimitry Andric // compiler, or through an interpreter if no JIT is available for this platform.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
15fe6060f1SDimitry Andric #include "ExecutionUtils.h"
16349cc55cSDimitry Andric #include "ForwardingMemoryManager.h"
170b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
190b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
205ffd83dbSDimitry Andric #include "llvm/CodeGen/CommandFlags.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllCodegenComponents.h"
220b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
230b57cec5SDimitry Andric #include "llvm/ExecutionEngine/GenericValue.h"
240b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Interpreter.h"
250b57cec5SDimitry Andric #include "llvm/ExecutionEngine/JITEventListener.h"
26fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/JITSymbol.h"
270b57cec5SDimitry Andric #include "llvm/ExecutionEngine/MCJIT.h"
280b57cec5SDimitry Andric #include "llvm/ExecutionEngine/ObjectCache.h"
29fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
305ffd83dbSDimitry Andric #include "llvm/ExecutionEngine/Orc/DebugUtils.h"
31*81ad6265SDimitry Andric #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h"
32fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h"
33*81ad6265SDimitry Andric #include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
34fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
35349cc55cSDimitry Andric #include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h"
360b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
370b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
380b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/LLJIT.h"
39*81ad6265SDimitry Andric #include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
405ffd83dbSDimitry Andric #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
41349cc55cSDimitry Andric #include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
42fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/SymbolStringPool.h"
43fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
44fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
45e8d8bef9SDimitry Andric #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
460b57cec5SDimitry Andric #include "llvm/ExecutionEngine/SectionMemoryManager.h"
470b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
480b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
490b57cec5SDimitry Andric #include "llvm/IR/Module.h"
500b57cec5SDimitry Andric #include "llvm/IR/Type.h"
510b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
520b57cec5SDimitry Andric #include "llvm/IRReader/IRReader.h"
530b57cec5SDimitry Andric #include "llvm/Object/Archive.h"
540b57cec5SDimitry Andric #include "llvm/Object/ObjectFile.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
570b57cec5SDimitry Andric #include "llvm/Support/DynamicLibrary.h"
580b57cec5SDimitry Andric #include "llvm/Support/Format.h"
590b57cec5SDimitry Andric #include "llvm/Support/InitLLVM.h"
600b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
610b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
620b57cec5SDimitry Andric #include "llvm/Support/Memory.h"
630b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
640b57cec5SDimitry Andric #include "llvm/Support/Path.h"
650b57cec5SDimitry Andric #include "llvm/Support/PluginLoader.h"
660b57cec5SDimitry Andric #include "llvm/Support/Process.h"
670b57cec5SDimitry Andric #include "llvm/Support/Program.h"
680b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
690b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
700b57cec5SDimitry Andric #include "llvm/Support/WithColor.h"
710b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
720b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
730b57cec5SDimitry Andric #include <cerrno>
740b57cec5SDimitry Andric 
75349cc55cSDimitry Andric #if !defined(_MSC_VER) && !defined(__MINGW32__)
76349cc55cSDimitry Andric #include <unistd.h>
77349cc55cSDimitry Andric #else
78349cc55cSDimitry Andric #include <io.h>
79349cc55cSDimitry Andric #endif
80349cc55cSDimitry Andric 
810b57cec5SDimitry Andric #ifdef __CYGWIN__
820b57cec5SDimitry Andric #include <cygwin/version.h>
830b57cec5SDimitry Andric #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
840b57cec5SDimitry Andric #define DO_NOTHING_ATEXIT 1
850b57cec5SDimitry Andric #endif
860b57cec5SDimitry Andric #endif
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric using namespace llvm;
890b57cec5SDimitry Andric 
905ffd83dbSDimitry Andric static codegen::RegisterCodeGenFlags CGF;
915ffd83dbSDimitry Andric 
920b57cec5SDimitry Andric #define DEBUG_TYPE "lli"
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric namespace {
950b57cec5SDimitry Andric 
96fe6060f1SDimitry Andric   enum class JITKind { MCJIT, Orc, OrcLazy };
97fe6060f1SDimitry Andric   enum class JITLinkerKind { Default, RuntimeDyld, JITLink };
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   cl::opt<std::string>
1000b57cec5SDimitry Andric   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   cl::list<std::string>
1030b57cec5SDimitry Andric   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   cl::opt<bool> ForceInterpreter("force-interpreter",
1060b57cec5SDimitry Andric                                  cl::desc("Force interpretation: disable JIT"),
1070b57cec5SDimitry Andric                                  cl::init(false));
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   cl::opt<JITKind> UseJITKind(
1100b57cec5SDimitry Andric       "jit-kind", cl::desc("Choose underlying JIT kind."),
111fe6060f1SDimitry Andric       cl::init(JITKind::Orc),
1120b57cec5SDimitry Andric       cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
113fe6060f1SDimitry Andric                  clEnumValN(JITKind::Orc, "orc", "Orc JIT"),
1140b57cec5SDimitry Andric                  clEnumValN(JITKind::OrcLazy, "orc-lazy",
1150b57cec5SDimitry Andric                             "Orc-based lazy JIT.")));
1160b57cec5SDimitry Andric 
117fe6060f1SDimitry Andric   cl::opt<JITLinkerKind>
118fe6060f1SDimitry Andric       JITLinker("jit-linker", cl::desc("Choose the dynamic linker/loader."),
119fe6060f1SDimitry Andric                 cl::init(JITLinkerKind::Default),
120fe6060f1SDimitry Andric                 cl::values(clEnumValN(JITLinkerKind::Default, "default",
121fe6060f1SDimitry Andric                                       "Default for platform and JIT-kind"),
122fe6060f1SDimitry Andric                            clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld",
123fe6060f1SDimitry Andric                                       "RuntimeDyld"),
124fe6060f1SDimitry Andric                            clEnumValN(JITLinkerKind::JITLink, "jitlink",
125fe6060f1SDimitry Andric                                       "Orc-specific linker")));
126*81ad6265SDimitry Andric   cl::opt<std::string> OrcRuntime("orc-runtime",
127*81ad6265SDimitry Andric                                   cl::desc("Use ORC runtime from given path"),
128*81ad6265SDimitry Andric                                   cl::init(""));
129fe6060f1SDimitry Andric 
1300b57cec5SDimitry Andric   cl::opt<unsigned>
1310b57cec5SDimitry Andric   LazyJITCompileThreads("compile-threads",
1320b57cec5SDimitry Andric                         cl::desc("Choose the number of compile threads "
1330b57cec5SDimitry Andric                                  "(jit-kind=orc-lazy only)"),
1340b57cec5SDimitry Andric                         cl::init(0));
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   cl::list<std::string>
1370b57cec5SDimitry Andric   ThreadEntryPoints("thread-entry",
1380b57cec5SDimitry Andric                     cl::desc("calls the given entry-point on a new thread "
1390b57cec5SDimitry Andric                              "(jit-kind=orc-lazy only)"));
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   cl::opt<bool> PerModuleLazy(
1420b57cec5SDimitry Andric       "per-module-lazy",
1430b57cec5SDimitry Andric       cl::desc("Performs lazy compilation on whole module boundaries "
1440b57cec5SDimitry Andric                "rather than individual functions"),
1450b57cec5SDimitry Andric       cl::init(false));
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   cl::list<std::string>
1480b57cec5SDimitry Andric       JITDylibs("jd",
1490b57cec5SDimitry Andric                 cl::desc("Specifies the JITDylib to be used for any subsequent "
1500b57cec5SDimitry Andric                          "-extra-module arguments."));
1510b57cec5SDimitry Andric 
1525ffd83dbSDimitry Andric   cl::list<std::string>
153*81ad6265SDimitry Andric       Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"));
1545ffd83dbSDimitry Andric 
1550b57cec5SDimitry Andric   // The MCJIT supports building for a target address space separate from
1560b57cec5SDimitry Andric   // the JIT compilation process. Use a forked process and a copying
1570b57cec5SDimitry Andric   // memory manager with IPC to execute using this functionality.
1580b57cec5SDimitry Andric   cl::opt<bool> RemoteMCJIT("remote-mcjit",
1590b57cec5SDimitry Andric     cl::desc("Execute MCJIT'ed code in a separate process."),
1600b57cec5SDimitry Andric     cl::init(false));
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   // Manually specify the child process for remote execution. This overrides
1630b57cec5SDimitry Andric   // the simulated remote execution that allocates address space for child
1640b57cec5SDimitry Andric   // execution. The child process will be executed and will communicate with
1650b57cec5SDimitry Andric   // lli via stdin/stdout pipes.
1660b57cec5SDimitry Andric   cl::opt<std::string>
1670b57cec5SDimitry Andric   ChildExecPath("mcjit-remote-process",
1680b57cec5SDimitry Andric                 cl::desc("Specify the filename of the process to launch "
1690b57cec5SDimitry Andric                          "for remote MCJIT execution.  If none is specified,"
1700b57cec5SDimitry Andric                          "\n\tremote execution will be simulated in-process."),
1710b57cec5SDimitry Andric                 cl::value_desc("filename"), cl::init(""));
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // Determine optimization level.
174*81ad6265SDimitry Andric   cl::opt<char> OptLevel("O",
1750b57cec5SDimitry Andric                          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
1760b57cec5SDimitry Andric                                   "(default = '-O2')"),
177*81ad6265SDimitry Andric                          cl::Prefix, cl::init(' '));
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   cl::opt<std::string>
1800b57cec5SDimitry Andric   TargetTriple("mtriple", cl::desc("Override target triple for module"));
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   cl::opt<std::string>
1830b57cec5SDimitry Andric   EntryFunc("entry-function",
1840b57cec5SDimitry Andric             cl::desc("Specify the entry function (default = 'main') "
1850b57cec5SDimitry Andric                      "of the executable"),
1860b57cec5SDimitry Andric             cl::value_desc("function"),
1870b57cec5SDimitry Andric             cl::init("main"));
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   cl::list<std::string>
1900b57cec5SDimitry Andric   ExtraModules("extra-module",
1910b57cec5SDimitry Andric          cl::desc("Extra modules to be loaded"),
1920b57cec5SDimitry Andric          cl::value_desc("input bitcode"));
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   cl::list<std::string>
1950b57cec5SDimitry Andric   ExtraObjects("extra-object",
1960b57cec5SDimitry Andric          cl::desc("Extra object files to be loaded"),
1970b57cec5SDimitry Andric          cl::value_desc("input object"));
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   cl::list<std::string>
2000b57cec5SDimitry Andric   ExtraArchives("extra-archive",
2010b57cec5SDimitry Andric          cl::desc("Extra archive files to be loaded"),
2020b57cec5SDimitry Andric          cl::value_desc("input archive"));
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   cl::opt<bool>
2050b57cec5SDimitry Andric   EnableCacheManager("enable-cache-manager",
2060b57cec5SDimitry Andric         cl::desc("Use cache manager to save/load modules"),
2070b57cec5SDimitry Andric         cl::init(false));
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   cl::opt<std::string>
2100b57cec5SDimitry Andric   ObjectCacheDir("object-cache-dir",
2110b57cec5SDimitry Andric                   cl::desc("Directory to store cached object files "
2120b57cec5SDimitry Andric                            "(must be user writable)"),
2130b57cec5SDimitry Andric                   cl::init(""));
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   cl::opt<std::string>
2160b57cec5SDimitry Andric   FakeArgv0("fake-argv0",
2170b57cec5SDimitry Andric             cl::desc("Override the 'argv[0]' value passed into the executing"
2180b57cec5SDimitry Andric                      " program"), cl::value_desc("executable"));
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric   cl::opt<bool>
2210b57cec5SDimitry Andric   DisableCoreFiles("disable-core-files", cl::Hidden,
2220b57cec5SDimitry Andric                    cl::desc("Disable emission of core files if possible"));
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   cl::opt<bool>
2250b57cec5SDimitry Andric   NoLazyCompilation("disable-lazy-compilation",
2260b57cec5SDimitry Andric                   cl::desc("Disable JIT lazy compilation"),
2270b57cec5SDimitry Andric                   cl::init(false));
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   cl::opt<bool>
2300b57cec5SDimitry Andric   GenerateSoftFloatCalls("soft-float",
2310b57cec5SDimitry Andric     cl::desc("Generate software floating point library calls"),
2320b57cec5SDimitry Andric     cl::init(false));
2330b57cec5SDimitry Andric 
23413138422SDimitry Andric   cl::opt<bool> NoProcessSymbols(
23513138422SDimitry Andric       "no-process-syms",
23613138422SDimitry Andric       cl::desc("Do not resolve lli process symbols in JIT'd code"),
23713138422SDimitry Andric       cl::init(false));
23813138422SDimitry Andric 
239*81ad6265SDimitry Andric   enum class LLJITPlatform { Inactive, DetectHost, ORC, GenericIR };
2405ffd83dbSDimitry Andric 
2415ffd83dbSDimitry Andric   cl::opt<LLJITPlatform>
2425ffd83dbSDimitry Andric       Platform("lljit-platform", cl::desc("Platform to use with LLJIT"),
2435ffd83dbSDimitry Andric                cl::init(LLJITPlatform::DetectHost),
2445ffd83dbSDimitry Andric                cl::values(clEnumValN(LLJITPlatform::DetectHost, "DetectHost",
2455ffd83dbSDimitry Andric                                      "Select based on JIT target triple"),
246*81ad6265SDimitry Andric                           clEnumValN(LLJITPlatform::ORC, "ORC",
247*81ad6265SDimitry Andric                                      "Use ORCPlatform with the ORC runtime"),
2485ffd83dbSDimitry Andric                           clEnumValN(LLJITPlatform::GenericIR, "GenericIR",
2495ffd83dbSDimitry Andric                                      "Use LLJITGenericIRPlatform"),
250fe6060f1SDimitry Andric                           clEnumValN(LLJITPlatform::Inactive, "Inactive",
251fe6060f1SDimitry Andric                                      "Disable platform support explicitly")),
2525ffd83dbSDimitry Andric                cl::Hidden);
2535ffd83dbSDimitry Andric 
2540b57cec5SDimitry Andric   enum class DumpKind {
2550b57cec5SDimitry Andric     NoDump,
2560b57cec5SDimitry Andric     DumpFuncsToStdOut,
2570b57cec5SDimitry Andric     DumpModsToStdOut,
2580b57cec5SDimitry Andric     DumpModsToDisk
2590b57cec5SDimitry Andric   };
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   cl::opt<DumpKind> OrcDumpKind(
2620b57cec5SDimitry Andric       "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
2630b57cec5SDimitry Andric       cl::init(DumpKind::NoDump),
2640b57cec5SDimitry Andric       cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
2650b57cec5SDimitry Andric                             "Don't dump anything."),
2660b57cec5SDimitry Andric                  clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
2670b57cec5SDimitry Andric                             "Dump function names to stdout."),
2680b57cec5SDimitry Andric                  clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
2690b57cec5SDimitry Andric                             "Dump modules to stdout."),
2700b57cec5SDimitry Andric                  clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
2710b57cec5SDimitry Andric                             "Dump modules to the current "
2720b57cec5SDimitry Andric                             "working directory. (WARNING: "
2730b57cec5SDimitry Andric                             "will overwrite existing files).")),
2740b57cec5SDimitry Andric       cl::Hidden);
2750b57cec5SDimitry Andric 
276fe6060f1SDimitry Andric   cl::list<BuiltinFunctionKind> GenerateBuiltinFunctions(
277fe6060f1SDimitry Andric       "generate",
278fe6060f1SDimitry Andric       cl::desc("Provide built-in functions for access by JITed code "
279fe6060f1SDimitry Andric                "(jit-kind=orc-lazy only)"),
280fe6060f1SDimitry Andric       cl::values(clEnumValN(BuiltinFunctionKind::DumpDebugDescriptor,
281fe6060f1SDimitry Andric                             "__dump_jit_debug_descriptor",
282fe6060f1SDimitry Andric                             "Dump __jit_debug_descriptor contents to stdout"),
283fe6060f1SDimitry Andric                  clEnumValN(BuiltinFunctionKind::DumpDebugObjects,
284fe6060f1SDimitry Andric                             "__dump_jit_debug_objects",
285fe6060f1SDimitry Andric                             "Dump __jit_debug_descriptor in-memory debug "
286fe6060f1SDimitry Andric                             "objects as tool output")),
287fe6060f1SDimitry Andric       cl::Hidden);
288fe6060f1SDimitry Andric 
2890b57cec5SDimitry Andric   ExitOnError ExitOnErr;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
292fe6060f1SDimitry Andric LLVM_ATTRIBUTE_USED void linkComponents() {
293fe6060f1SDimitry Andric   errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
294fe6060f1SDimitry Andric          << (void *)&llvm_orc_deregisterEHFrameSectionWrapper
295fe6060f1SDimitry Andric          << (void *)&llvm_orc_registerJITLoaderGDBWrapper;
296fe6060f1SDimitry Andric }
297fe6060f1SDimitry Andric 
2980b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2990b57cec5SDimitry Andric // Object cache
3000b57cec5SDimitry Andric //
3010b57cec5SDimitry Andric // This object cache implementation writes cached objects to disk to the
3020b57cec5SDimitry Andric // directory specified by CacheDir, using a filename provided in the module
3030b57cec5SDimitry Andric // descriptor. The cache tries to load a saved object using that path if the
3040b57cec5SDimitry Andric // file exists. CacheDir defaults to "", in which case objects are cached
3050b57cec5SDimitry Andric // alongside their originating bitcodes.
3060b57cec5SDimitry Andric //
3070b57cec5SDimitry Andric class LLIObjectCache : public ObjectCache {
3080b57cec5SDimitry Andric public:
3090b57cec5SDimitry Andric   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
3100b57cec5SDimitry Andric     // Add trailing '/' to cache dir if necessary.
3110b57cec5SDimitry Andric     if (!this->CacheDir.empty() &&
3120b57cec5SDimitry Andric         this->CacheDir[this->CacheDir.size() - 1] != '/')
3130b57cec5SDimitry Andric       this->CacheDir += '/';
3140b57cec5SDimitry Andric   }
3150b57cec5SDimitry Andric   ~LLIObjectCache() override {}
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
3180b57cec5SDimitry Andric     const std::string &ModuleID = M->getModuleIdentifier();
3190b57cec5SDimitry Andric     std::string CacheName;
3200b57cec5SDimitry Andric     if (!getCacheFilename(ModuleID, CacheName))
3210b57cec5SDimitry Andric       return;
3220b57cec5SDimitry Andric     if (!CacheDir.empty()) { // Create user-defined cache dir.
3230b57cec5SDimitry Andric       SmallString<128> dir(sys::path::parent_path(CacheName));
3240b57cec5SDimitry Andric       sys::fs::create_directories(Twine(dir));
3250b57cec5SDimitry Andric     }
3265ffd83dbSDimitry Andric 
3270b57cec5SDimitry Andric     std::error_code EC;
3288bcb0991SDimitry Andric     raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
3290b57cec5SDimitry Andric     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
3300b57cec5SDimitry Andric     outfile.close();
3310b57cec5SDimitry Andric   }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
3340b57cec5SDimitry Andric     const std::string &ModuleID = M->getModuleIdentifier();
3350b57cec5SDimitry Andric     std::string CacheName;
3360b57cec5SDimitry Andric     if (!getCacheFilename(ModuleID, CacheName))
3370b57cec5SDimitry Andric       return nullptr;
3380b57cec5SDimitry Andric     // Load the object from the cache filename
3390b57cec5SDimitry Andric     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
340fe6060f1SDimitry Andric         MemoryBuffer::getFile(CacheName, /*IsText=*/false,
341fe6060f1SDimitry Andric                               /*RequiresNullTerminator=*/false);
3420b57cec5SDimitry Andric     // If the file isn't there, that's OK.
3430b57cec5SDimitry Andric     if (!IRObjectBuffer)
3440b57cec5SDimitry Andric       return nullptr;
3450b57cec5SDimitry Andric     // MCJIT will want to write into this buffer, and we don't want that
3460b57cec5SDimitry Andric     // because the file has probably just been mmapped.  Instead we make
3470b57cec5SDimitry Andric     // a copy.  The filed-based buffer will be released when it goes
3480b57cec5SDimitry Andric     // out of scope.
3490b57cec5SDimitry Andric     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
3500b57cec5SDimitry Andric   }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric private:
3530b57cec5SDimitry Andric   std::string CacheDir;
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
3560b57cec5SDimitry Andric     std::string Prefix("file:");
3570b57cec5SDimitry Andric     size_t PrefixLength = Prefix.length();
3580b57cec5SDimitry Andric     if (ModID.substr(0, PrefixLength) != Prefix)
3590b57cec5SDimitry Andric       return false;
3605ffd83dbSDimitry Andric 
3610b57cec5SDimitry Andric     std::string CacheSubdir = ModID.substr(PrefixLength);
362349cc55cSDimitry Andric     // Transform "X:\foo" => "/X\foo" for convenience on Windows.
363349cc55cSDimitry Andric     if (is_style_windows(llvm::sys::path::Style::native) &&
364349cc55cSDimitry Andric         isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
3650b57cec5SDimitry Andric       CacheSubdir[1] = CacheSubdir[0];
3660b57cec5SDimitry Andric       CacheSubdir[0] = '/';
3670b57cec5SDimitry Andric     }
3685ffd83dbSDimitry Andric 
3690b57cec5SDimitry Andric     CacheName = CacheDir + CacheSubdir;
3700b57cec5SDimitry Andric     size_t pos = CacheName.rfind('.');
3710b57cec5SDimitry Andric     CacheName.replace(pos, CacheName.length() - pos, ".o");
3720b57cec5SDimitry Andric     return true;
3730b57cec5SDimitry Andric   }
3740b57cec5SDimitry Andric };
3750b57cec5SDimitry Andric 
376*81ad6265SDimitry Andric class ORCPlatformSupport : public orc::LLJIT::PlatformSupport {
377*81ad6265SDimitry Andric public:
378*81ad6265SDimitry Andric   ORCPlatformSupport(orc::LLJIT &J) : J(J) {}
379*81ad6265SDimitry Andric 
380*81ad6265SDimitry Andric   Error initialize(orc::JITDylib &JD) override {
381*81ad6265SDimitry Andric     using llvm::orc::shared::SPSExecutorAddr;
382*81ad6265SDimitry Andric     using llvm::orc::shared::SPSString;
383*81ad6265SDimitry Andric     using SPSDLOpenSig = SPSExecutorAddr(SPSString, int32_t);
384*81ad6265SDimitry Andric     enum dlopen_mode : int32_t {
385*81ad6265SDimitry Andric       ORC_RT_RTLD_LAZY = 0x1,
386*81ad6265SDimitry Andric       ORC_RT_RTLD_NOW = 0x2,
387*81ad6265SDimitry Andric       ORC_RT_RTLD_LOCAL = 0x4,
388*81ad6265SDimitry Andric       ORC_RT_RTLD_GLOBAL = 0x8
389*81ad6265SDimitry Andric     };
390*81ad6265SDimitry Andric 
391*81ad6265SDimitry Andric     if (auto WrapperAddr = J.lookup("__orc_rt_jit_dlopen_wrapper")) {
392*81ad6265SDimitry Andric       return J.getExecutionSession().callSPSWrapper<SPSDLOpenSig>(
393*81ad6265SDimitry Andric           *WrapperAddr, DSOHandles[&JD], JD.getName(),
394*81ad6265SDimitry Andric           int32_t(ORC_RT_RTLD_LAZY));
395*81ad6265SDimitry Andric     } else
396*81ad6265SDimitry Andric       return WrapperAddr.takeError();
397*81ad6265SDimitry Andric   }
398*81ad6265SDimitry Andric 
399*81ad6265SDimitry Andric   Error deinitialize(orc::JITDylib &JD) override {
400*81ad6265SDimitry Andric     using llvm::orc::shared::SPSExecutorAddr;
401*81ad6265SDimitry Andric     using SPSDLCloseSig = int32_t(SPSExecutorAddr);
402*81ad6265SDimitry Andric 
403*81ad6265SDimitry Andric     if (auto WrapperAddr = J.lookup("__orc_rt_jit_dlclose_wrapper")) {
404*81ad6265SDimitry Andric       int32_t result;
405*81ad6265SDimitry Andric       auto E = J.getExecutionSession().callSPSWrapper<SPSDLCloseSig>(
406*81ad6265SDimitry Andric           *WrapperAddr, result, DSOHandles[&JD]);
407*81ad6265SDimitry Andric       if (E)
408*81ad6265SDimitry Andric         return E;
409*81ad6265SDimitry Andric       else if (result)
410*81ad6265SDimitry Andric         return make_error<StringError>("dlclose failed",
411*81ad6265SDimitry Andric                                        inconvertibleErrorCode());
412*81ad6265SDimitry Andric       DSOHandles.erase(&JD);
413*81ad6265SDimitry Andric     } else
414*81ad6265SDimitry Andric       return WrapperAddr.takeError();
415*81ad6265SDimitry Andric     return Error::success();
416*81ad6265SDimitry Andric   }
417*81ad6265SDimitry Andric 
418*81ad6265SDimitry Andric private:
419*81ad6265SDimitry Andric   orc::LLJIT &J;
420*81ad6265SDimitry Andric   DenseMap<orc::JITDylib *, orc::ExecutorAddr> DSOHandles;
421*81ad6265SDimitry Andric };
422*81ad6265SDimitry Andric 
4230b57cec5SDimitry Andric // On Mingw and Cygwin, an external symbol named '__main' is called from the
4240b57cec5SDimitry Andric // generated 'main' function to allow static initialization.  To avoid linking
4250b57cec5SDimitry Andric // problems with remote targets (because lli's remote target support does not
4260b57cec5SDimitry Andric // currently handle external linking) we add a secondary module which defines
4270b57cec5SDimitry Andric // an empty '__main' function.
4280b57cec5SDimitry Andric static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
4290b57cec5SDimitry Andric                                   StringRef TargetTripleStr) {
4300b57cec5SDimitry Andric   IRBuilder<> Builder(Context);
4310b57cec5SDimitry Andric   Triple TargetTriple(TargetTripleStr);
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   // Create a new module.
4348bcb0991SDimitry Andric   std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
4350b57cec5SDimitry Andric   M->setTargetTriple(TargetTripleStr);
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   // Create an empty function named "__main".
4380b57cec5SDimitry Andric   Type *ReturnTy;
4390b57cec5SDimitry Andric   if (TargetTriple.isArch64Bit())
4400b57cec5SDimitry Andric     ReturnTy = Type::getInt64Ty(Context);
4410b57cec5SDimitry Andric   else
4420b57cec5SDimitry Andric     ReturnTy = Type::getInt32Ty(Context);
4430b57cec5SDimitry Andric   Function *Result =
4440b57cec5SDimitry Andric       Function::Create(FunctionType::get(ReturnTy, {}, false),
4450b57cec5SDimitry Andric                        GlobalValue::ExternalLinkage, "__main", M.get());
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
4480b57cec5SDimitry Andric   Builder.SetInsertPoint(BB);
4490b57cec5SDimitry Andric   Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
4500b57cec5SDimitry Andric   Builder.CreateRet(ReturnVal);
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // Add this new module to the ExecutionEngine.
4530b57cec5SDimitry Andric   EE.addModule(std::move(M));
4540b57cec5SDimitry Andric }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric CodeGenOpt::Level getOptLevel() {
4570b57cec5SDimitry Andric   switch (OptLevel) {
4580b57cec5SDimitry Andric   default:
4590b57cec5SDimitry Andric     WithColor::error(errs(), "lli") << "invalid optimization level.\n";
4600b57cec5SDimitry Andric     exit(1);
4610b57cec5SDimitry Andric   case '0': return CodeGenOpt::None;
4620b57cec5SDimitry Andric   case '1': return CodeGenOpt::Less;
4630b57cec5SDimitry Andric   case ' ':
4640b57cec5SDimitry Andric   case '2': return CodeGenOpt::Default;
4650b57cec5SDimitry Andric   case '3': return CodeGenOpt::Aggressive;
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric   llvm_unreachable("Unrecognized opt level.");
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
470349cc55cSDimitry Andric [[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) {
4710b57cec5SDimitry Andric   Err.print(ProgName, errs());
4720b57cec5SDimitry Andric   exit(1);
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric 
4755ffd83dbSDimitry Andric Error loadDylibs();
476fe6060f1SDimitry Andric int runOrcJIT(const char *ProgName);
4770b57cec5SDimitry Andric void disallowOrcOptions();
478349cc55cSDimitry Andric Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote();
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4810b57cec5SDimitry Andric // main Driver function
4820b57cec5SDimitry Andric //
4830b57cec5SDimitry Andric int main(int argc, char **argv, char * const *envp) {
4840b57cec5SDimitry Andric   InitLLVM X(argc, argv);
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   if (argc > 1)
4870b57cec5SDimitry Andric     ExitOnErr.setBanner(std::string(argv[0]) + ": ");
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   // If we have a native target, initialize it to ensure it is linked in and
4900b57cec5SDimitry Andric   // usable by the JIT.
4910b57cec5SDimitry Andric   InitializeNativeTarget();
4920b57cec5SDimitry Andric   InitializeNativeTargetAsmPrinter();
4930b57cec5SDimitry Andric   InitializeNativeTargetAsmParser();
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   cl::ParseCommandLineOptions(argc, argv,
4960b57cec5SDimitry Andric                               "llvm interpreter & dynamic compiler\n");
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric   // If the user doesn't want core files, disable them.
4990b57cec5SDimitry Andric   if (DisableCoreFiles)
5000b57cec5SDimitry Andric     sys::Process::PreventCoreFiles();
5010b57cec5SDimitry Andric 
5025ffd83dbSDimitry Andric   ExitOnErr(loadDylibs());
5035ffd83dbSDimitry Andric 
504fe6060f1SDimitry Andric   if (UseJITKind == JITKind::MCJIT)
5050b57cec5SDimitry Andric     disallowOrcOptions();
506fe6060f1SDimitry Andric   else
507fe6060f1SDimitry Andric     return runOrcJIT(argv[0]);
5080b57cec5SDimitry Andric 
509fe6060f1SDimitry Andric   // Old lli implementation based on ExecutionEngine and MCJIT.
5100b57cec5SDimitry Andric   LLVMContext Context;
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   // Load the bitcode...
5130b57cec5SDimitry Andric   SMDiagnostic Err;
5140b57cec5SDimitry Andric   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
5150b57cec5SDimitry Andric   Module *Mod = Owner.get();
5160b57cec5SDimitry Andric   if (!Mod)
5170b57cec5SDimitry Andric     reportError(Err, argv[0]);
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   if (EnableCacheManager) {
5200b57cec5SDimitry Andric     std::string CacheName("file:");
5210b57cec5SDimitry Andric     CacheName.append(InputFile);
5220b57cec5SDimitry Andric     Mod->setModuleIdentifier(CacheName);
5230b57cec5SDimitry Andric   }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   // If not jitting lazily, load the whole bitcode file eagerly too.
5260b57cec5SDimitry Andric   if (NoLazyCompilation) {
5270b57cec5SDimitry Andric     // Use *argv instead of argv[0] to work around a wrong GCC warning.
5280b57cec5SDimitry Andric     ExitOnError ExitOnErr(std::string(*argv) +
5290b57cec5SDimitry Andric                           ": bitcode didn't read correctly: ");
5300b57cec5SDimitry Andric     ExitOnErr(Mod->materializeAll());
5310b57cec5SDimitry Andric   }
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric   std::string ErrorMsg;
5340b57cec5SDimitry Andric   EngineBuilder builder(std::move(Owner));
5355ffd83dbSDimitry Andric   builder.setMArch(codegen::getMArch());
5365ffd83dbSDimitry Andric   builder.setMCPU(codegen::getCPUStr());
5375ffd83dbSDimitry Andric   builder.setMAttrs(codegen::getFeatureList());
5385ffd83dbSDimitry Andric   if (auto RM = codegen::getExplicitRelocModel())
5395ffd83dbSDimitry Andric     builder.setRelocationModel(RM.getValue());
5405ffd83dbSDimitry Andric   if (auto CM = codegen::getExplicitCodeModel())
5415ffd83dbSDimitry Andric     builder.setCodeModel(CM.getValue());
5420b57cec5SDimitry Andric   builder.setErrorStr(&ErrorMsg);
5430b57cec5SDimitry Andric   builder.setEngineKind(ForceInterpreter
5440b57cec5SDimitry Andric                         ? EngineKind::Interpreter
5450b57cec5SDimitry Andric                         : EngineKind::JIT);
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric   // If we are supposed to override the target triple, do so now.
5480b57cec5SDimitry Andric   if (!TargetTriple.empty())
5490b57cec5SDimitry Andric     Mod->setTargetTriple(Triple::normalize(TargetTriple));
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric   // Enable MCJIT if desired.
5520b57cec5SDimitry Andric   RTDyldMemoryManager *RTDyldMM = nullptr;
5530b57cec5SDimitry Andric   if (!ForceInterpreter) {
5540b57cec5SDimitry Andric     if (RemoteMCJIT)
5550b57cec5SDimitry Andric       RTDyldMM = new ForwardingMemoryManager();
5560b57cec5SDimitry Andric     else
5570b57cec5SDimitry Andric       RTDyldMM = new SectionMemoryManager();
5580b57cec5SDimitry Andric 
5590b57cec5SDimitry Andric     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
5600b57cec5SDimitry Andric     // RTDyldMM: We still use it below, even though we don't own it.
5610b57cec5SDimitry Andric     builder.setMCJITMemoryManager(
5620b57cec5SDimitry Andric       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
5630b57cec5SDimitry Andric   } else if (RemoteMCJIT) {
5640b57cec5SDimitry Andric     WithColor::error(errs(), argv[0])
5650b57cec5SDimitry Andric         << "remote process execution does not work with the interpreter.\n";
5660b57cec5SDimitry Andric     exit(1);
5670b57cec5SDimitry Andric   }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   builder.setOptLevel(getOptLevel());
5700b57cec5SDimitry Andric 
571e8d8bef9SDimitry Andric   TargetOptions Options =
572e8d8bef9SDimitry Andric       codegen::InitTargetOptionsFromCodeGenFlags(Triple(TargetTriple));
5735ffd83dbSDimitry Andric   if (codegen::getFloatABIForCalls() != FloatABI::Default)
5745ffd83dbSDimitry Andric     Options.FloatABIType = codegen::getFloatABIForCalls();
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   builder.setTargetOptions(Options);
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   std::unique_ptr<ExecutionEngine> EE(builder.create());
5790b57cec5SDimitry Andric   if (!EE) {
5800b57cec5SDimitry Andric     if (!ErrorMsg.empty())
5810b57cec5SDimitry Andric       WithColor::error(errs(), argv[0])
5820b57cec5SDimitry Andric           << "error creating EE: " << ErrorMsg << "\n";
5830b57cec5SDimitry Andric     else
5840b57cec5SDimitry Andric       WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
5850b57cec5SDimitry Andric     exit(1);
5860b57cec5SDimitry Andric   }
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric   std::unique_ptr<LLIObjectCache> CacheManager;
5890b57cec5SDimitry Andric   if (EnableCacheManager) {
5900b57cec5SDimitry Andric     CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
5910b57cec5SDimitry Andric     EE->setObjectCache(CacheManager.get());
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   // Load any additional modules specified on the command line.
5950b57cec5SDimitry Andric   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
5960b57cec5SDimitry Andric     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
5970b57cec5SDimitry Andric     if (!XMod)
5980b57cec5SDimitry Andric       reportError(Err, argv[0]);
5990b57cec5SDimitry Andric     if (EnableCacheManager) {
6000b57cec5SDimitry Andric       std::string CacheName("file:");
6010b57cec5SDimitry Andric       CacheName.append(ExtraModules[i]);
6020b57cec5SDimitry Andric       XMod->setModuleIdentifier(CacheName);
6030b57cec5SDimitry Andric     }
6040b57cec5SDimitry Andric     EE->addModule(std::move(XMod));
6050b57cec5SDimitry Andric   }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
6080b57cec5SDimitry Andric     Expected<object::OwningBinary<object::ObjectFile>> Obj =
6090b57cec5SDimitry Andric         object::ObjectFile::createObjectFile(ExtraObjects[i]);
6100b57cec5SDimitry Andric     if (!Obj) {
6110b57cec5SDimitry Andric       // TODO: Actually report errors helpfully.
6120b57cec5SDimitry Andric       consumeError(Obj.takeError());
6130b57cec5SDimitry Andric       reportError(Err, argv[0]);
6140b57cec5SDimitry Andric     }
6150b57cec5SDimitry Andric     object::OwningBinary<object::ObjectFile> &O = Obj.get();
6160b57cec5SDimitry Andric     EE->addObjectFile(std::move(O));
6170b57cec5SDimitry Andric   }
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
6200b57cec5SDimitry Andric     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
6210b57cec5SDimitry Andric         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
6220b57cec5SDimitry Andric     if (!ArBufOrErr)
6230b57cec5SDimitry Andric       reportError(Err, argv[0]);
6240b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric     Expected<std::unique_ptr<object::Archive>> ArOrErr =
6270b57cec5SDimitry Andric         object::Archive::create(ArBuf->getMemBufferRef());
6280b57cec5SDimitry Andric     if (!ArOrErr) {
6290b57cec5SDimitry Andric       std::string Buf;
6300b57cec5SDimitry Andric       raw_string_ostream OS(Buf);
6310b57cec5SDimitry Andric       logAllUnhandledErrors(ArOrErr.takeError(), OS);
6320b57cec5SDimitry Andric       OS.flush();
6330b57cec5SDimitry Andric       errs() << Buf;
6340b57cec5SDimitry Andric       exit(1);
6350b57cec5SDimitry Andric     }
6360b57cec5SDimitry Andric     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric     EE->addArchive(std::move(OB));
6410b57cec5SDimitry Andric   }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   // If the target is Cygwin/MingW and we are generating remote code, we
6440b57cec5SDimitry Andric   // need an extra module to help out with linking.
6450b57cec5SDimitry Andric   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
6460b57cec5SDimitry Andric     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   // The following functions have no effect if their respective profiling
6500b57cec5SDimitry Andric   // support wasn't enabled in the build configuration.
6510b57cec5SDimitry Andric   EE->RegisterJITEventListener(
6520b57cec5SDimitry Andric                 JITEventListener::createOProfileJITEventListener());
6530b57cec5SDimitry Andric   EE->RegisterJITEventListener(
6540b57cec5SDimitry Andric                 JITEventListener::createIntelJITEventListener());
6550b57cec5SDimitry Andric   if (!RemoteMCJIT)
6560b57cec5SDimitry Andric     EE->RegisterJITEventListener(
6570b57cec5SDimitry Andric                 JITEventListener::createPerfJITEventListener());
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   if (!NoLazyCompilation && RemoteMCJIT) {
6600b57cec5SDimitry Andric     WithColor::warning(errs(), argv[0])
6610b57cec5SDimitry Andric         << "remote mcjit does not support lazy compilation\n";
6620b57cec5SDimitry Andric     NoLazyCompilation = true;
6630b57cec5SDimitry Andric   }
6640b57cec5SDimitry Andric   EE->DisableLazyCompilation(NoLazyCompilation);
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   // If the user specifically requested an argv[0] to pass into the program,
6670b57cec5SDimitry Andric   // do it now.
6680b57cec5SDimitry Andric   if (!FakeArgv0.empty()) {
6690b57cec5SDimitry Andric     InputFile = static_cast<std::string>(FakeArgv0);
6700b57cec5SDimitry Andric   } else {
6710b57cec5SDimitry Andric     // Otherwise, if there is a .bc suffix on the executable strip it off, it
6720b57cec5SDimitry Andric     // might confuse the program.
6730b57cec5SDimitry Andric     if (StringRef(InputFile).endswith(".bc"))
6740b57cec5SDimitry Andric       InputFile.erase(InputFile.length() - 3);
6750b57cec5SDimitry Andric   }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric   // Add the module's name to the start of the vector of arguments to main().
6780b57cec5SDimitry Andric   InputArgv.insert(InputArgv.begin(), InputFile);
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   // Call the main function from M as if its signature were:
6810b57cec5SDimitry Andric   //   int main (int argc, char **argv, const char **envp)
6820b57cec5SDimitry Andric   // using the contents of Args to determine argc & argv, and the contents of
6830b57cec5SDimitry Andric   // EnvVars to determine envp.
6840b57cec5SDimitry Andric   //
6850b57cec5SDimitry Andric   Function *EntryFn = Mod->getFunction(EntryFunc);
6860b57cec5SDimitry Andric   if (!EntryFn) {
6870b57cec5SDimitry Andric     WithColor::error(errs(), argv[0])
6880b57cec5SDimitry Andric         << '\'' << EntryFunc << "\' function not found in module.\n";
6890b57cec5SDimitry Andric     return -1;
6900b57cec5SDimitry Andric   }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   // Reset errno to zero on entry to main.
6930b57cec5SDimitry Andric   errno = 0;
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   int Result = -1;
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   // Sanity check use of remote-jit: LLI currently only supports use of the
6980b57cec5SDimitry Andric   // remote JIT on Unix platforms.
6990b57cec5SDimitry Andric   if (RemoteMCJIT) {
7000b57cec5SDimitry Andric #ifndef LLVM_ON_UNIX
7010b57cec5SDimitry Andric     WithColor::warning(errs(), argv[0])
7020b57cec5SDimitry Andric         << "host does not support external remote targets.\n";
7030b57cec5SDimitry Andric     WithColor::note() << "defaulting to local execution\n";
7040b57cec5SDimitry Andric     return -1;
7050b57cec5SDimitry Andric #else
7060b57cec5SDimitry Andric     if (ChildExecPath.empty()) {
7070b57cec5SDimitry Andric       WithColor::error(errs(), argv[0])
7080b57cec5SDimitry Andric           << "-remote-mcjit requires -mcjit-remote-process.\n";
7090b57cec5SDimitry Andric       exit(1);
7100b57cec5SDimitry Andric     } else if (!sys::fs::can_execute(ChildExecPath)) {
7110b57cec5SDimitry Andric       WithColor::error(errs(), argv[0])
7120b57cec5SDimitry Andric           << "unable to find usable child executable: '" << ChildExecPath
7130b57cec5SDimitry Andric           << "'\n";
7140b57cec5SDimitry Andric       return -1;
7150b57cec5SDimitry Andric     }
7160b57cec5SDimitry Andric #endif
7170b57cec5SDimitry Andric   }
7180b57cec5SDimitry Andric 
719349cc55cSDimitry Andric   std::unique_ptr<orc::ExecutorProcessControl> EPC =
720349cc55cSDimitry Andric       RemoteMCJIT ? ExitOnErr(launchRemote())
721349cc55cSDimitry Andric                   : ExitOnErr(orc::SelfExecutorProcessControl::Create());
722349cc55cSDimitry Andric 
7230b57cec5SDimitry Andric   if (!RemoteMCJIT) {
7240b57cec5SDimitry Andric     // If the program doesn't explicitly call exit, we will need the Exit
7250b57cec5SDimitry Andric     // function later on to make an explicit call, so get the function now.
7260b57cec5SDimitry Andric     FunctionCallee Exit = Mod->getOrInsertFunction(
7270b57cec5SDimitry Andric         "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric     // Run static constructors.
7300b57cec5SDimitry Andric     if (!ForceInterpreter) {
7310b57cec5SDimitry Andric       // Give MCJIT a chance to apply relocations and set page permissions.
7320b57cec5SDimitry Andric       EE->finalizeObject();
7330b57cec5SDimitry Andric     }
7340b57cec5SDimitry Andric     EE->runStaticConstructorsDestructors(false);
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric     // Trigger compilation separately so code regions that need to be
7370b57cec5SDimitry Andric     // invalidated will be known.
7380b57cec5SDimitry Andric     (void)EE->getPointerToFunction(EntryFn);
7390b57cec5SDimitry Andric     // Clear instruction cache before code will be executed.
7400b57cec5SDimitry Andric     if (RTDyldMM)
7410b57cec5SDimitry Andric       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric     // Run main.
7440b57cec5SDimitry Andric     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric     // Run static destructors.
7470b57cec5SDimitry Andric     EE->runStaticConstructorsDestructors(true);
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric     // If the program didn't call exit explicitly, we should call it now.
7500b57cec5SDimitry Andric     // This ensures that any atexit handlers get called correctly.
7510b57cec5SDimitry Andric     if (Function *ExitF =
7520b57cec5SDimitry Andric             dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
7530b57cec5SDimitry Andric       if (ExitF->getFunctionType() == Exit.getFunctionType()) {
7540b57cec5SDimitry Andric         std::vector<GenericValue> Args;
7550b57cec5SDimitry Andric         GenericValue ResultGV;
7560b57cec5SDimitry Andric         ResultGV.IntVal = APInt(32, Result);
7570b57cec5SDimitry Andric         Args.push_back(ResultGV);
7580b57cec5SDimitry Andric         EE->runFunction(ExitF, Args);
7590b57cec5SDimitry Andric         WithColor::error(errs(), argv[0])
7600b57cec5SDimitry Andric             << "exit(" << Result << ") returned!\n";
7610b57cec5SDimitry Andric         abort();
7620b57cec5SDimitry Andric       }
7630b57cec5SDimitry Andric     }
7640b57cec5SDimitry Andric     WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
7650b57cec5SDimitry Andric     abort();
7660b57cec5SDimitry Andric   } else {
7670b57cec5SDimitry Andric     // else == "if (RemoteMCJIT)"
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric     // Remote target MCJIT doesn't (yet) support static constructors. No reason
7700b57cec5SDimitry Andric     // it couldn't. This is a limitation of the LLI implementation, not the
7710b57cec5SDimitry Andric     // MCJIT itself. FIXME.
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric     // Create a remote memory manager.
774349cc55cSDimitry Andric     auto RemoteMM = ExitOnErr(
775349cc55cSDimitry Andric         orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols(
776349cc55cSDimitry Andric             *EPC));
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric     // Forward MCJIT's memory manager calls to the remote memory manager.
7790b57cec5SDimitry Andric     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
7800b57cec5SDimitry Andric       std::move(RemoteMM));
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric     // Forward MCJIT's symbol resolution calls to the remote.
7830b57cec5SDimitry Andric     static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
784349cc55cSDimitry Andric         ExitOnErr(RemoteResolver::Create(*EPC)));
7850b57cec5SDimitry Andric     // Grab the target address of the JIT'd main function on the remote and call
7860b57cec5SDimitry Andric     // it.
7870b57cec5SDimitry Andric     // FIXME: argv and envp handling.
788349cc55cSDimitry Andric     auto Entry =
789349cc55cSDimitry Andric         orc::ExecutorAddr(EE->getFunctionAddress(EntryFn->getName().str()));
7900b57cec5SDimitry Andric     EE->finalizeObject();
7910b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
792349cc55cSDimitry Andric                       << format("%llx", Entry.getValue()) << "\n");
793349cc55cSDimitry Andric     Result = ExitOnErr(EPC->runAsMain(Entry, {}));
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric     // Like static constructors, the remote target MCJIT support doesn't handle
7960b57cec5SDimitry Andric     // this yet. It could. FIXME.
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric     // Delete the EE - we need to tear it down *before* we terminate the session
7990b57cec5SDimitry Andric     // with the remote, otherwise it'll crash when it tries to release resources
8000b57cec5SDimitry Andric     // on a remote that has already been disconnected.
8010b57cec5SDimitry Andric     EE.reset();
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric     // Signal the remote target that we're done JITing.
804349cc55cSDimitry Andric     ExitOnErr(EPC->disconnect());
8050b57cec5SDimitry Andric   }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   return Result;
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric 
8108bcb0991SDimitry Andric static std::function<void(Module &)> createDebugDumper() {
8110b57cec5SDimitry Andric   switch (OrcDumpKind) {
8120b57cec5SDimitry Andric   case DumpKind::NoDump:
8138bcb0991SDimitry Andric     return [](Module &M) {};
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   case DumpKind::DumpFuncsToStdOut:
8168bcb0991SDimitry Andric     return [](Module &M) {
8170b57cec5SDimitry Andric       printf("[ ");
8180b57cec5SDimitry Andric 
8198bcb0991SDimitry Andric       for (const auto &F : M) {
8200b57cec5SDimitry Andric         if (F.isDeclaration())
8210b57cec5SDimitry Andric           continue;
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric         if (F.hasName()) {
8245ffd83dbSDimitry Andric           std::string Name(std::string(F.getName()));
8250b57cec5SDimitry Andric           printf("%s ", Name.c_str());
8260b57cec5SDimitry Andric         } else
8270b57cec5SDimitry Andric           printf("<anon> ");
8280b57cec5SDimitry Andric       }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric       printf("]\n");
8310b57cec5SDimitry Andric     };
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   case DumpKind::DumpModsToStdOut:
8348bcb0991SDimitry Andric     return [](Module &M) {
8358bcb0991SDimitry Andric       outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
8360b57cec5SDimitry Andric     };
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   case DumpKind::DumpModsToDisk:
8398bcb0991SDimitry Andric     return [](Module &M) {
8400b57cec5SDimitry Andric       std::error_code EC;
841fe6060f1SDimitry Andric       raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC,
842fe6060f1SDimitry Andric                          sys::fs::OF_TextWithCRLF);
8430b57cec5SDimitry Andric       if (EC) {
8448bcb0991SDimitry Andric         errs() << "Couldn't open " << M.getModuleIdentifier()
8450b57cec5SDimitry Andric                << " for dumping.\nError:" << EC.message() << "\n";
8460b57cec5SDimitry Andric         exit(1);
8470b57cec5SDimitry Andric       }
8488bcb0991SDimitry Andric       Out << M;
8490b57cec5SDimitry Andric     };
8500b57cec5SDimitry Andric   }
8510b57cec5SDimitry Andric   llvm_unreachable("Unknown DumpKind");
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric 
8545ffd83dbSDimitry Andric Error loadDylibs() {
8555ffd83dbSDimitry Andric   for (const auto &Dylib : Dylibs) {
8565ffd83dbSDimitry Andric     std::string ErrMsg;
8575ffd83dbSDimitry Andric     if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
8585ffd83dbSDimitry Andric       return make_error<StringError>(ErrMsg, inconvertibleErrorCode());
8595ffd83dbSDimitry Andric   }
8605ffd83dbSDimitry Andric 
8615ffd83dbSDimitry Andric   return Error::success();
8625ffd83dbSDimitry Andric }
8635ffd83dbSDimitry Andric 
8640b57cec5SDimitry Andric static void exitOnLazyCallThroughFailure() { exit(1); }
8650b57cec5SDimitry Andric 
8665ffd83dbSDimitry Andric Expected<orc::ThreadSafeModule>
8675ffd83dbSDimitry Andric loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) {
8685ffd83dbSDimitry Andric   SMDiagnostic Err;
8695ffd83dbSDimitry Andric   auto M = parseIRFile(Path, Err, *TSCtx.getContext());
8705ffd83dbSDimitry Andric   if (!M) {
8715ffd83dbSDimitry Andric     std::string ErrMsg;
8725ffd83dbSDimitry Andric     {
8735ffd83dbSDimitry Andric       raw_string_ostream ErrMsgStream(ErrMsg);
8745ffd83dbSDimitry Andric       Err.print("lli", ErrMsgStream);
8755ffd83dbSDimitry Andric     }
8765ffd83dbSDimitry Andric     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
8775ffd83dbSDimitry Andric   }
8785ffd83dbSDimitry Andric 
8795ffd83dbSDimitry Andric   if (EnableCacheManager)
8805ffd83dbSDimitry Andric     M->setModuleIdentifier("file:" + M->getModuleIdentifier());
8815ffd83dbSDimitry Andric 
8825ffd83dbSDimitry Andric   return orc::ThreadSafeModule(std::move(M), std::move(TSCtx));
8835ffd83dbSDimitry Andric }
8845ffd83dbSDimitry Andric 
885fe6060f1SDimitry Andric int runOrcJIT(const char *ProgName) {
8860b57cec5SDimitry Andric   // Start setting up the JIT environment.
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   // Parse the main module.
8898bcb0991SDimitry Andric   orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
8905ffd83dbSDimitry Andric   auto MainModule = ExitOnErr(loadModule(InputFile, TSCtx));
8910b57cec5SDimitry Andric 
8925ffd83dbSDimitry Andric   // Get TargetTriple and DataLayout from the main module if they're explicitly
8935ffd83dbSDimitry Andric   // set.
8945ffd83dbSDimitry Andric   Optional<Triple> TT;
8955ffd83dbSDimitry Andric   Optional<DataLayout> DL;
8965ffd83dbSDimitry Andric   MainModule.withModuleDo([&](Module &M) {
8975ffd83dbSDimitry Andric       if (!M.getTargetTriple().empty())
8985ffd83dbSDimitry Andric         TT = Triple(M.getTargetTriple());
8995ffd83dbSDimitry Andric       if (!M.getDataLayout().isDefault())
9005ffd83dbSDimitry Andric         DL = M.getDataLayout();
9015ffd83dbSDimitry Andric     });
9025ffd83dbSDimitry Andric 
9030b57cec5SDimitry Andric   orc::LLLazyJITBuilder Builder;
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric   Builder.setJITTargetMachineBuilder(
9065ffd83dbSDimitry Andric       TT ? orc::JITTargetMachineBuilder(*TT)
9075ffd83dbSDimitry Andric          : ExitOnErr(orc::JITTargetMachineBuilder::detectHost()));
9080b57cec5SDimitry Andric 
9095ffd83dbSDimitry Andric   TT = Builder.getJITTargetMachineBuilder()->getTargetTriple();
9105ffd83dbSDimitry Andric   if (DL)
9115ffd83dbSDimitry Andric     Builder.setDataLayout(DL);
9125ffd83dbSDimitry Andric 
9135ffd83dbSDimitry Andric   if (!codegen::getMArch().empty())
9145ffd83dbSDimitry Andric     Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(
9155ffd83dbSDimitry Andric         codegen::getMArch());
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   Builder.getJITTargetMachineBuilder()
9185ffd83dbSDimitry Andric       ->setCPU(codegen::getCPUStr())
9195ffd83dbSDimitry Andric       .addFeatures(codegen::getFeatureList())
9205ffd83dbSDimitry Andric       .setRelocationModel(codegen::getExplicitRelocModel())
9215ffd83dbSDimitry Andric       .setCodeModel(codegen::getExplicitCodeModel());
9220b57cec5SDimitry Andric 
923fe6060f1SDimitry Andric   // FIXME: Setting a dummy call-through manager in non-lazy mode prevents the
924fe6060f1SDimitry Andric   // JIT builder to instantiate a default (which would fail with an error for
925fe6060f1SDimitry Andric   // unsupported architectures).
926fe6060f1SDimitry Andric   if (UseJITKind != JITKind::OrcLazy) {
927fe6060f1SDimitry Andric     auto ES = std::make_unique<orc::ExecutionSession>(
928fe6060f1SDimitry Andric         ExitOnErr(orc::SelfExecutorProcessControl::Create()));
929fe6060f1SDimitry Andric     Builder.setLazyCallthroughManager(
930fe6060f1SDimitry Andric         std::make_unique<orc::LazyCallThroughManager>(*ES, 0, nullptr));
931fe6060f1SDimitry Andric     Builder.setExecutionSession(std::move(ES));
932fe6060f1SDimitry Andric   }
933fe6060f1SDimitry Andric 
9340b57cec5SDimitry Andric   Builder.setLazyCompileFailureAddr(
935*81ad6265SDimitry Andric       orc::ExecutorAddr::fromPtr(exitOnLazyCallThroughFailure));
9360b57cec5SDimitry Andric   Builder.setNumCompileThreads(LazyJITCompileThreads);
9370b57cec5SDimitry Andric 
9385ffd83dbSDimitry Andric   // If the object cache is enabled then set a custom compile function
9395ffd83dbSDimitry Andric   // creator to use the cache.
9405ffd83dbSDimitry Andric   std::unique_ptr<LLIObjectCache> CacheManager;
9415ffd83dbSDimitry Andric   if (EnableCacheManager) {
9425ffd83dbSDimitry Andric 
9435ffd83dbSDimitry Andric     CacheManager = std::make_unique<LLIObjectCache>(ObjectCacheDir);
9445ffd83dbSDimitry Andric 
9455ffd83dbSDimitry Andric     Builder.setCompileFunctionCreator(
9465ffd83dbSDimitry Andric       [&](orc::JITTargetMachineBuilder JTMB)
9475ffd83dbSDimitry Andric             -> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> {
9485ffd83dbSDimitry Andric         if (LazyJITCompileThreads > 0)
9495ffd83dbSDimitry Andric           return std::make_unique<orc::ConcurrentIRCompiler>(std::move(JTMB),
9505ffd83dbSDimitry Andric                                                         CacheManager.get());
9515ffd83dbSDimitry Andric 
9525ffd83dbSDimitry Andric         auto TM = JTMB.createTargetMachine();
9535ffd83dbSDimitry Andric         if (!TM)
9545ffd83dbSDimitry Andric           return TM.takeError();
9555ffd83dbSDimitry Andric 
9565ffd83dbSDimitry Andric         return std::make_unique<orc::TMOwningSimpleCompiler>(std::move(*TM),
9575ffd83dbSDimitry Andric                                                         CacheManager.get());
9585ffd83dbSDimitry Andric       });
9595ffd83dbSDimitry Andric   }
9605ffd83dbSDimitry Andric 
9615ffd83dbSDimitry Andric   // Set up LLJIT platform.
9625ffd83dbSDimitry Andric   LLJITPlatform P = Platform;
963*81ad6265SDimitry Andric   if (P == LLJITPlatform::DetectHost) {
964*81ad6265SDimitry Andric     if (JITLinker == JITLinkerKind::JITLink && !OrcRuntime.empty() &&
965*81ad6265SDimitry Andric         (TT->isOSBinFormatMachO() || TT->isOSBinFormatELF()))
966*81ad6265SDimitry Andric       P = LLJITPlatform::ORC;
967*81ad6265SDimitry Andric     else
9685ffd83dbSDimitry Andric       P = LLJITPlatform::GenericIR;
969*81ad6265SDimitry Andric   }
9705ffd83dbSDimitry Andric   switch (P) {
971*81ad6265SDimitry Andric   case LLJITPlatform::ORC:
972*81ad6265SDimitry Andric     Builder.setPlatformSetUp([](llvm::orc::LLJIT &J) -> llvm::Error {
973*81ad6265SDimitry Andric       J.setPlatformSupport(std::make_unique<ORCPlatformSupport>(J));
974*81ad6265SDimitry Andric       return Error::success();
975*81ad6265SDimitry Andric     });
976*81ad6265SDimitry Andric     break;
9775ffd83dbSDimitry Andric   case LLJITPlatform::GenericIR:
9785ffd83dbSDimitry Andric     // Nothing to do: LLJITBuilder will use this by default.
9795ffd83dbSDimitry Andric     break;
980fe6060f1SDimitry Andric   case LLJITPlatform::Inactive:
981fe6060f1SDimitry Andric     Builder.setPlatformSetUp(orc::setUpInactivePlatform);
9825ffd83dbSDimitry Andric     break;
9835ffd83dbSDimitry Andric   default:
9845ffd83dbSDimitry Andric     llvm_unreachable("Unrecognized platform value");
9855ffd83dbSDimitry Andric   }
9865ffd83dbSDimitry Andric 
987fe6060f1SDimitry Andric   std::unique_ptr<orc::ExecutorProcessControl> EPC = nullptr;
988fe6060f1SDimitry Andric   if (JITLinker == JITLinkerKind::JITLink) {
989fe6060f1SDimitry Andric     EPC = ExitOnErr(orc::SelfExecutorProcessControl::Create(
990fe6060f1SDimitry Andric         std::make_shared<orc::SymbolStringPool>()));
991fe6060f1SDimitry Andric 
992*81ad6265SDimitry Andric     Builder.setObjectLinkingLayerCreator([&EPC, &P](orc::ExecutionSession &ES,
993*81ad6265SDimitry Andric                                                     const Triple &TT) {
994fe6060f1SDimitry Andric       auto L = std::make_unique<orc::ObjectLinkingLayer>(ES, EPC->getMemMgr());
995*81ad6265SDimitry Andric       if (P != LLJITPlatform::ORC) {
996fe6060f1SDimitry Andric         L->addPlugin(std::make_unique<orc::EHFrameRegistrationPlugin>(
997fe6060f1SDimitry Andric             ES, ExitOnErr(orc::EPCEHFrameRegistrar::Create(ES))));
998fe6060f1SDimitry Andric         L->addPlugin(std::make_unique<orc::DebugObjectManagerPlugin>(
999fe6060f1SDimitry Andric             ES, ExitOnErr(orc::createJITLoaderGDBRegistrar(ES))));
1000*81ad6265SDimitry Andric       }
1001fe6060f1SDimitry Andric       return L;
1002fe6060f1SDimitry Andric     });
1003fe6060f1SDimitry Andric   }
1004fe6060f1SDimitry Andric 
10050b57cec5SDimitry Andric   auto J = ExitOnErr(Builder.create());
10060b57cec5SDimitry Andric 
1007fe6060f1SDimitry Andric   auto *ObjLayer = &J->getObjLinkingLayer();
1008fe6060f1SDimitry Andric   if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(ObjLayer))
1009fe6060f1SDimitry Andric     RTDyldObjLayer->registerJITEventListener(
10105ffd83dbSDimitry Andric         *JITEventListener::createGDBRegistrationListener());
10115ffd83dbSDimitry Andric 
10120b57cec5SDimitry Andric   if (PerModuleLazy)
10130b57cec5SDimitry Andric     J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   auto Dump = createDebugDumper();
10160b57cec5SDimitry Andric 
10175ffd83dbSDimitry Andric   J->getIRTransformLayer().setTransform(
10185ffd83dbSDimitry Andric       [&](orc::ThreadSafeModule TSM,
10190b57cec5SDimitry Andric           const orc::MaterializationResponsibility &R) {
10208bcb0991SDimitry Andric         TSM.withModuleDo([&](Module &M) {
10218bcb0991SDimitry Andric           if (verifyModule(M, &dbgs())) {
10228bcb0991SDimitry Andric             dbgs() << "Bad module: " << &M << "\n";
10230b57cec5SDimitry Andric             exit(1);
10240b57cec5SDimitry Andric           }
10258bcb0991SDimitry Andric           Dump(M);
10260b57cec5SDimitry Andric         });
10278bcb0991SDimitry Andric         return TSM;
10288bcb0991SDimitry Andric       });
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
103113138422SDimitry Andric 
103213138422SDimitry Andric   // Unless they've been explicitly disabled, make process symbols available to
103313138422SDimitry Andric   // JIT'd code.
103413138422SDimitry Andric   if (!NoProcessSymbols)
1035480093f4SDimitry Andric     J->getMainJITDylib().addGenerator(
1036480093f4SDimitry Andric         ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
1037480093f4SDimitry Andric             J->getDataLayout().getGlobalPrefix(),
1038480093f4SDimitry Andric             [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) {
1039480093f4SDimitry Andric               return Name != MainName;
1040480093f4SDimitry Andric             })));
1041480093f4SDimitry Andric 
1042fe6060f1SDimitry Andric   if (GenerateBuiltinFunctions.size() > 0)
1043fe6060f1SDimitry Andric     J->getMainJITDylib().addGenerator(
1044fe6060f1SDimitry Andric         std::make_unique<LLIBuiltinFunctionGenerator>(GenerateBuiltinFunctions,
1045fe6060f1SDimitry Andric                                                       Mangle));
1046fe6060f1SDimitry Andric 
1047*81ad6265SDimitry Andric   if (P == LLJITPlatform::ORC) {
1048*81ad6265SDimitry Andric     if (auto *OLL = llvm::dyn_cast<llvm::orc::ObjectLinkingLayer>(ObjLayer)) {
1049*81ad6265SDimitry Andric       auto &ES = J->getExecutionSession();
1050*81ad6265SDimitry Andric       if (TT->isOSBinFormatMachO()) {
1051*81ad6265SDimitry Andric         if (auto P = llvm::orc::MachOPlatform::Create(
1052*81ad6265SDimitry Andric                 ES, *OLL, J->getMainJITDylib(), OrcRuntime.c_str()))
1053*81ad6265SDimitry Andric           ES.setPlatform(std::move(*P));
1054*81ad6265SDimitry Andric         else
1055*81ad6265SDimitry Andric           ExitOnErr(P.takeError());
1056*81ad6265SDimitry Andric       } else if (TT->isOSBinFormatELF()) {
1057*81ad6265SDimitry Andric         if (auto P = llvm::orc::ELFNixPlatform::Create(
1058*81ad6265SDimitry Andric                 ES, *OLL, J->getMainJITDylib(), OrcRuntime.c_str()))
1059*81ad6265SDimitry Andric           ES.setPlatform(std::move(*P));
1060*81ad6265SDimitry Andric         else
1061*81ad6265SDimitry Andric           ExitOnErr(P.takeError());
1062*81ad6265SDimitry Andric       } else {
1063*81ad6265SDimitry Andric         errs() << "No ORC platform support\n";
1064*81ad6265SDimitry Andric         exit(1);
1065*81ad6265SDimitry Andric       }
1066*81ad6265SDimitry Andric     } else {
1067*81ad6265SDimitry Andric       errs() << "ORC platform requires JITLink\n";
1068*81ad6265SDimitry Andric       exit(1);
1069*81ad6265SDimitry Andric     }
1070*81ad6265SDimitry Andric   }
1071*81ad6265SDimitry Andric 
1072fe6060f1SDimitry Andric   // Regular modules are greedy: They materialize as a whole and trigger
1073fe6060f1SDimitry Andric   // materialization for all required symbols recursively. Lazy modules go
1074fe6060f1SDimitry Andric   // through partitioning and they replace outgoing calls with reexport stubs
1075fe6060f1SDimitry Andric   // that resolve on call-through.
1076fe6060f1SDimitry Andric   auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) {
1077fe6060f1SDimitry Andric     return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, std::move(M))
1078fe6060f1SDimitry Andric                                           : J->addIRModule(JD, std::move(M));
1079fe6060f1SDimitry Andric   };
1080fe6060f1SDimitry Andric 
10810b57cec5SDimitry Andric   // Add the main module.
1082fe6060f1SDimitry Andric   ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule)));
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric   // Create JITDylibs and add any extra modules.
10850b57cec5SDimitry Andric   {
10860b57cec5SDimitry Andric     // Create JITDylibs, keep a map from argument index to dylib. We will use
10870b57cec5SDimitry Andric     // -extra-module argument indexes to determine what dylib to use for each
10880b57cec5SDimitry Andric     // -extra-module.
10890b57cec5SDimitry Andric     std::map<unsigned, orc::JITDylib *> IdxToDylib;
10900b57cec5SDimitry Andric     IdxToDylib[0] = &J->getMainJITDylib();
10910b57cec5SDimitry Andric     for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
10920b57cec5SDimitry Andric          JDItr != JDEnd; ++JDItr) {
10930b57cec5SDimitry Andric       orc::JITDylib *JD = J->getJITDylibByName(*JDItr);
10945ffd83dbSDimitry Andric       if (!JD) {
10955ffd83dbSDimitry Andric         JD = &ExitOnErr(J->createJITDylib(*JDItr));
10965ffd83dbSDimitry Andric         J->getMainJITDylib().addToLinkOrder(*JD);
10975ffd83dbSDimitry Andric         JD->addToLinkOrder(J->getMainJITDylib());
10985ffd83dbSDimitry Andric       }
10990b57cec5SDimitry Andric       IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;
11000b57cec5SDimitry Andric     }
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric     for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
11030b57cec5SDimitry Andric          EMItr != EMEnd; ++EMItr) {
11045ffd83dbSDimitry Andric       auto M = ExitOnErr(loadModule(*EMItr, TSCtx));
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric       auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
11070b57cec5SDimitry Andric       assert(EMIdx != 0 && "ExtraModule should have index > 0");
11080b57cec5SDimitry Andric       auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
11090b57cec5SDimitry Andric       auto &JD = *JDItr->second;
1110fe6060f1SDimitry Andric       ExitOnErr(AddModule(JD, std::move(M)));
11110b57cec5SDimitry Andric     }
11128bcb0991SDimitry Andric 
11138bcb0991SDimitry Andric     for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
11148bcb0991SDimitry Andric          EAItr != EAEnd; ++EAItr) {
11158bcb0991SDimitry Andric       auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());
11168bcb0991SDimitry Andric       assert(EAIdx != 0 && "ExtraArchive should have index > 0");
11178bcb0991SDimitry Andric       auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));
11188bcb0991SDimitry Andric       auto &JD = *JDItr->second;
11198bcb0991SDimitry Andric       JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load(
11205ffd83dbSDimitry Andric           J->getObjLinkingLayer(), EAItr->c_str(), *TT)));
11218bcb0991SDimitry Andric     }
11220b57cec5SDimitry Andric   }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric   // Add the objects.
11250b57cec5SDimitry Andric   for (auto &ObjPath : ExtraObjects) {
11260b57cec5SDimitry Andric     auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
11270b57cec5SDimitry Andric     ExitOnErr(J->addObjectFile(std::move(Obj)));
11280b57cec5SDimitry Andric   }
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric   // Run any static constructors.
11315ffd83dbSDimitry Andric   ExitOnErr(J->initialize(J->getMainJITDylib()));
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric   // Run any -thread-entry points.
11340b57cec5SDimitry Andric   std::vector<std::thread> AltEntryThreads;
11350b57cec5SDimitry Andric   for (auto &ThreadEntryPoint : ThreadEntryPoints) {
11360b57cec5SDimitry Andric     auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
11370b57cec5SDimitry Andric     typedef void (*EntryPointPtr)();
1138*81ad6265SDimitry Andric     auto EntryPoint = EntryPointSym.toPtr<EntryPointPtr>();
11390b57cec5SDimitry Andric     AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
11400b57cec5SDimitry Andric   }
11410b57cec5SDimitry Andric 
1142fe6060f1SDimitry Andric   // Resolve and run the main function.
1143*81ad6265SDimitry Andric   auto MainAddr = ExitOnErr(J->lookup(EntryFunc));
1144fe6060f1SDimitry Andric   int Result;
11450b57cec5SDimitry Andric 
1146fe6060f1SDimitry Andric   if (EPC) {
1147fe6060f1SDimitry Andric     // ExecutorProcessControl-based execution with JITLink.
1148*81ad6265SDimitry Andric     Result = ExitOnErr(EPC->runAsMain(MainAddr, InputArgv));
1149fe6060f1SDimitry Andric   } else {
1150fe6060f1SDimitry Andric     // Manual in-process execution with RuntimeDyld.
1151fe6060f1SDimitry Andric     using MainFnTy = int(int, char *[]);
1152*81ad6265SDimitry Andric     auto MainFn = MainAddr.toPtr<MainFnTy *>();
1153fe6060f1SDimitry Andric     Result = orc::runAsMain(MainFn, InputArgv, StringRef(InputFile));
1154fe6060f1SDimitry Andric   }
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   // Wait for -entry-point threads.
11570b57cec5SDimitry Andric   for (auto &AltEntryThread : AltEntryThreads)
11580b57cec5SDimitry Andric     AltEntryThread.join();
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   // Run destructors.
11615ffd83dbSDimitry Andric   ExitOnErr(J->deinitialize(J->getMainJITDylib()));
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   return Result;
11640b57cec5SDimitry Andric }
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric void disallowOrcOptions() {
11670b57cec5SDimitry Andric   // Make sure nobody used an orc-lazy specific option accidentally.
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric   if (LazyJITCompileThreads != 0) {
11700b57cec5SDimitry Andric     errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
11710b57cec5SDimitry Andric     exit(1);
11720b57cec5SDimitry Andric   }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   if (!ThreadEntryPoints.empty()) {
11750b57cec5SDimitry Andric     errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
11760b57cec5SDimitry Andric     exit(1);
11770b57cec5SDimitry Andric   }
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric   if (PerModuleLazy) {
11800b57cec5SDimitry Andric     errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
11810b57cec5SDimitry Andric     exit(1);
11820b57cec5SDimitry Andric   }
11830b57cec5SDimitry Andric }
11840b57cec5SDimitry Andric 
1185349cc55cSDimitry Andric Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() {
11860b57cec5SDimitry Andric #ifndef LLVM_ON_UNIX
11870b57cec5SDimitry Andric   llvm_unreachable("launchRemote not supported on non-Unix platforms");
11880b57cec5SDimitry Andric #else
11890b57cec5SDimitry Andric   int PipeFD[2][2];
11900b57cec5SDimitry Andric   pid_t ChildPID;
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric   // Create two pipes.
11930b57cec5SDimitry Andric   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
11940b57cec5SDimitry Andric     perror("Error creating pipe: ");
11950b57cec5SDimitry Andric 
11960b57cec5SDimitry Andric   ChildPID = fork();
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   if (ChildPID == 0) {
11990b57cec5SDimitry Andric     // In the child...
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric     // Close the parent ends of the pipes
12020b57cec5SDimitry Andric     close(PipeFD[0][1]);
12030b57cec5SDimitry Andric     close(PipeFD[1][0]);
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric     // Execute the child process.
12070b57cec5SDimitry Andric     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
12080b57cec5SDimitry Andric     {
12090b57cec5SDimitry Andric       ChildPath.reset(new char[ChildExecPath.size() + 1]);
12100b57cec5SDimitry Andric       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
12110b57cec5SDimitry Andric       ChildPath[ChildExecPath.size()] = '\0';
12120b57cec5SDimitry Andric       std::string ChildInStr = utostr(PipeFD[0][0]);
12130b57cec5SDimitry Andric       ChildIn.reset(new char[ChildInStr.size() + 1]);
12140b57cec5SDimitry Andric       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
12150b57cec5SDimitry Andric       ChildIn[ChildInStr.size()] = '\0';
12160b57cec5SDimitry Andric       std::string ChildOutStr = utostr(PipeFD[1][1]);
12170b57cec5SDimitry Andric       ChildOut.reset(new char[ChildOutStr.size() + 1]);
12180b57cec5SDimitry Andric       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
12190b57cec5SDimitry Andric       ChildOut[ChildOutStr.size()] = '\0';
12200b57cec5SDimitry Andric     }
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
12230b57cec5SDimitry Andric     int rc = execv(ChildExecPath.c_str(), args);
12240b57cec5SDimitry Andric     if (rc != 0)
12250b57cec5SDimitry Andric       perror("Error executing child process: ");
12260b57cec5SDimitry Andric     llvm_unreachable("Error executing child process");
12270b57cec5SDimitry Andric   }
12280b57cec5SDimitry Andric   // else we're the parent...
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // Close the child ends of the pipes
12310b57cec5SDimitry Andric   close(PipeFD[0][0]);
12320b57cec5SDimitry Andric   close(PipeFD[1][1]);
12330b57cec5SDimitry Andric 
1234349cc55cSDimitry Andric   // Return a SimpleRemoteEPC instance connected to our end of the pipes.
1235349cc55cSDimitry Andric   return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>(
1236349cc55cSDimitry Andric       std::make_unique<llvm::orc::InPlaceTaskDispatcher>(),
1237349cc55cSDimitry Andric       llvm::orc::SimpleRemoteEPC::Setup(), PipeFD[1][0], PipeFD[0][1]);
12380b57cec5SDimitry Andric #endif
12390b57cec5SDimitry Andric }
1240