xref: /freebsd/contrib/llvm-project/llvm/tools/lli/lli.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
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 
150b57cec5SDimitry Andric #include "RemoteJITUtils.h"
160b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
170b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
180b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/CommandFlags.inc"
200b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllCodegenComponents.h"
210b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
220b57cec5SDimitry Andric #include "llvm/ExecutionEngine/GenericValue.h"
230b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Interpreter.h"
240b57cec5SDimitry Andric #include "llvm/ExecutionEngine/JITEventListener.h"
250b57cec5SDimitry Andric #include "llvm/ExecutionEngine/MCJIT.h"
260b57cec5SDimitry Andric #include "llvm/ExecutionEngine/ObjectCache.h"
270b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
280b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
290b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/LLJIT.h"
300b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
310b57cec5SDimitry Andric #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
320b57cec5SDimitry Andric #include "llvm/ExecutionEngine/SectionMemoryManager.h"
330b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
340b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
350b57cec5SDimitry Andric #include "llvm/IR/Module.h"
360b57cec5SDimitry Andric #include "llvm/IR/Type.h"
370b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
380b57cec5SDimitry Andric #include "llvm/IRReader/IRReader.h"
390b57cec5SDimitry Andric #include "llvm/Object/Archive.h"
400b57cec5SDimitry Andric #include "llvm/Object/ObjectFile.h"
410b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
420b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
430b57cec5SDimitry Andric #include "llvm/Support/DynamicLibrary.h"
440b57cec5SDimitry Andric #include "llvm/Support/Format.h"
450b57cec5SDimitry Andric #include "llvm/Support/InitLLVM.h"
460b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
470b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
480b57cec5SDimitry Andric #include "llvm/Support/Memory.h"
490b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
500b57cec5SDimitry Andric #include "llvm/Support/Path.h"
510b57cec5SDimitry Andric #include "llvm/Support/PluginLoader.h"
520b57cec5SDimitry Andric #include "llvm/Support/Process.h"
530b57cec5SDimitry Andric #include "llvm/Support/Program.h"
540b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
550b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
560b57cec5SDimitry Andric #include "llvm/Support/WithColor.h"
570b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
580b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
590b57cec5SDimitry Andric #include <cerrno>
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric #ifdef __CYGWIN__
620b57cec5SDimitry Andric #include <cygwin/version.h>
630b57cec5SDimitry Andric #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
640b57cec5SDimitry Andric #define DO_NOTHING_ATEXIT 1
650b57cec5SDimitry Andric #endif
660b57cec5SDimitry Andric #endif
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric using namespace llvm;
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric #define DEBUG_TYPE "lli"
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric namespace {
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric   enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric   cl::opt<std::string>
770b57cec5SDimitry Andric   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric   cl::list<std::string>
800b57cec5SDimitry Andric   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   cl::opt<bool> ForceInterpreter("force-interpreter",
830b57cec5SDimitry Andric                                  cl::desc("Force interpretation: disable JIT"),
840b57cec5SDimitry Andric                                  cl::init(false));
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric   cl::opt<JITKind> UseJITKind(
870b57cec5SDimitry Andric       "jit-kind", cl::desc("Choose underlying JIT kind."),
880b57cec5SDimitry Andric       cl::init(JITKind::MCJIT),
890b57cec5SDimitry Andric       cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
900b57cec5SDimitry Andric                  clEnumValN(JITKind::OrcMCJITReplacement, "orc-mcjit",
910b57cec5SDimitry Andric                             "Orc-based MCJIT replacement "
920b57cec5SDimitry Andric                             "(deprecated)"),
930b57cec5SDimitry Andric                  clEnumValN(JITKind::OrcLazy, "orc-lazy",
940b57cec5SDimitry Andric                             "Orc-based lazy JIT.")));
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric   cl::opt<unsigned>
970b57cec5SDimitry Andric   LazyJITCompileThreads("compile-threads",
980b57cec5SDimitry Andric                         cl::desc("Choose the number of compile threads "
990b57cec5SDimitry Andric                                  "(jit-kind=orc-lazy only)"),
1000b57cec5SDimitry Andric                         cl::init(0));
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   cl::list<std::string>
1030b57cec5SDimitry Andric   ThreadEntryPoints("thread-entry",
1040b57cec5SDimitry Andric                     cl::desc("calls the given entry-point on a new thread "
1050b57cec5SDimitry Andric                              "(jit-kind=orc-lazy only)"));
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   cl::opt<bool> PerModuleLazy(
1080b57cec5SDimitry Andric       "per-module-lazy",
1090b57cec5SDimitry Andric       cl::desc("Performs lazy compilation on whole module boundaries "
1100b57cec5SDimitry Andric                "rather than individual functions"),
1110b57cec5SDimitry Andric       cl::init(false));
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   cl::list<std::string>
1140b57cec5SDimitry Andric       JITDylibs("jd",
1150b57cec5SDimitry Andric                 cl::desc("Specifies the JITDylib to be used for any subsequent "
1160b57cec5SDimitry Andric                          "-extra-module arguments."));
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   // The MCJIT supports building for a target address space separate from
1190b57cec5SDimitry Andric   // the JIT compilation process. Use a forked process and a copying
1200b57cec5SDimitry Andric   // memory manager with IPC to execute using this functionality.
1210b57cec5SDimitry Andric   cl::opt<bool> RemoteMCJIT("remote-mcjit",
1220b57cec5SDimitry Andric     cl::desc("Execute MCJIT'ed code in a separate process."),
1230b57cec5SDimitry Andric     cl::init(false));
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // Manually specify the child process for remote execution. This overrides
1260b57cec5SDimitry Andric   // the simulated remote execution that allocates address space for child
1270b57cec5SDimitry Andric   // execution. The child process will be executed and will communicate with
1280b57cec5SDimitry Andric   // lli via stdin/stdout pipes.
1290b57cec5SDimitry Andric   cl::opt<std::string>
1300b57cec5SDimitry Andric   ChildExecPath("mcjit-remote-process",
1310b57cec5SDimitry Andric                 cl::desc("Specify the filename of the process to launch "
1320b57cec5SDimitry Andric                          "for remote MCJIT execution.  If none is specified,"
1330b57cec5SDimitry Andric                          "\n\tremote execution will be simulated in-process."),
1340b57cec5SDimitry Andric                 cl::value_desc("filename"), cl::init(""));
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   // Determine optimization level.
1370b57cec5SDimitry Andric   cl::opt<char>
1380b57cec5SDimitry Andric   OptLevel("O",
1390b57cec5SDimitry Andric            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
1400b57cec5SDimitry Andric                     "(default = '-O2')"),
1410b57cec5SDimitry Andric            cl::Prefix,
1420b57cec5SDimitry Andric            cl::ZeroOrMore,
1430b57cec5SDimitry Andric            cl::init(' '));
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   cl::opt<std::string>
1460b57cec5SDimitry Andric   TargetTriple("mtriple", cl::desc("Override target triple for module"));
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   cl::opt<std::string>
1490b57cec5SDimitry Andric   EntryFunc("entry-function",
1500b57cec5SDimitry Andric             cl::desc("Specify the entry function (default = 'main') "
1510b57cec5SDimitry Andric                      "of the executable"),
1520b57cec5SDimitry Andric             cl::value_desc("function"),
1530b57cec5SDimitry Andric             cl::init("main"));
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   cl::list<std::string>
1560b57cec5SDimitry Andric   ExtraModules("extra-module",
1570b57cec5SDimitry Andric          cl::desc("Extra modules to be loaded"),
1580b57cec5SDimitry Andric          cl::value_desc("input bitcode"));
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   cl::list<std::string>
1610b57cec5SDimitry Andric   ExtraObjects("extra-object",
1620b57cec5SDimitry Andric          cl::desc("Extra object files to be loaded"),
1630b57cec5SDimitry Andric          cl::value_desc("input object"));
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   cl::list<std::string>
1660b57cec5SDimitry Andric   ExtraArchives("extra-archive",
1670b57cec5SDimitry Andric          cl::desc("Extra archive files to be loaded"),
1680b57cec5SDimitry Andric          cl::value_desc("input archive"));
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   cl::opt<bool>
1710b57cec5SDimitry Andric   EnableCacheManager("enable-cache-manager",
1720b57cec5SDimitry Andric         cl::desc("Use cache manager to save/load modules"),
1730b57cec5SDimitry Andric         cl::init(false));
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   cl::opt<std::string>
1760b57cec5SDimitry Andric   ObjectCacheDir("object-cache-dir",
1770b57cec5SDimitry Andric                   cl::desc("Directory to store cached object files "
1780b57cec5SDimitry Andric                            "(must be user writable)"),
1790b57cec5SDimitry Andric                   cl::init(""));
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   cl::opt<std::string>
1820b57cec5SDimitry Andric   FakeArgv0("fake-argv0",
1830b57cec5SDimitry Andric             cl::desc("Override the 'argv[0]' value passed into the executing"
1840b57cec5SDimitry Andric                      " program"), cl::value_desc("executable"));
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   cl::opt<bool>
1870b57cec5SDimitry Andric   DisableCoreFiles("disable-core-files", cl::Hidden,
1880b57cec5SDimitry Andric                    cl::desc("Disable emission of core files if possible"));
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   cl::opt<bool>
1910b57cec5SDimitry Andric   NoLazyCompilation("disable-lazy-compilation",
1920b57cec5SDimitry Andric                   cl::desc("Disable JIT lazy compilation"),
1930b57cec5SDimitry Andric                   cl::init(false));
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   cl::opt<bool>
1960b57cec5SDimitry Andric   GenerateSoftFloatCalls("soft-float",
1970b57cec5SDimitry Andric     cl::desc("Generate software floating point library calls"),
1980b57cec5SDimitry Andric     cl::init(false));
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   enum class DumpKind {
2010b57cec5SDimitry Andric     NoDump,
2020b57cec5SDimitry Andric     DumpFuncsToStdOut,
2030b57cec5SDimitry Andric     DumpModsToStdOut,
2040b57cec5SDimitry Andric     DumpModsToDisk
2050b57cec5SDimitry Andric   };
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   cl::opt<DumpKind> OrcDumpKind(
2080b57cec5SDimitry Andric       "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
2090b57cec5SDimitry Andric       cl::init(DumpKind::NoDump),
2100b57cec5SDimitry Andric       cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
2110b57cec5SDimitry Andric                             "Don't dump anything."),
2120b57cec5SDimitry Andric                  clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
2130b57cec5SDimitry Andric                             "Dump function names to stdout."),
2140b57cec5SDimitry Andric                  clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
2150b57cec5SDimitry Andric                             "Dump modules to stdout."),
2160b57cec5SDimitry Andric                  clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
2170b57cec5SDimitry Andric                             "Dump modules to the current "
2180b57cec5SDimitry Andric                             "working directory. (WARNING: "
2190b57cec5SDimitry Andric                             "will overwrite existing files).")),
2200b57cec5SDimitry Andric       cl::Hidden);
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   ExitOnError ExitOnErr;
2230b57cec5SDimitry Andric }
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2260b57cec5SDimitry Andric // Object cache
2270b57cec5SDimitry Andric //
2280b57cec5SDimitry Andric // This object cache implementation writes cached objects to disk to the
2290b57cec5SDimitry Andric // directory specified by CacheDir, using a filename provided in the module
2300b57cec5SDimitry Andric // descriptor. The cache tries to load a saved object using that path if the
2310b57cec5SDimitry Andric // file exists. CacheDir defaults to "", in which case objects are cached
2320b57cec5SDimitry Andric // alongside their originating bitcodes.
2330b57cec5SDimitry Andric //
2340b57cec5SDimitry Andric class LLIObjectCache : public ObjectCache {
2350b57cec5SDimitry Andric public:
2360b57cec5SDimitry Andric   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
2370b57cec5SDimitry Andric     // Add trailing '/' to cache dir if necessary.
2380b57cec5SDimitry Andric     if (!this->CacheDir.empty() &&
2390b57cec5SDimitry Andric         this->CacheDir[this->CacheDir.size() - 1] != '/')
2400b57cec5SDimitry Andric       this->CacheDir += '/';
2410b57cec5SDimitry Andric   }
2420b57cec5SDimitry Andric   ~LLIObjectCache() override {}
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
2450b57cec5SDimitry Andric     const std::string &ModuleID = M->getModuleIdentifier();
2460b57cec5SDimitry Andric     std::string CacheName;
2470b57cec5SDimitry Andric     if (!getCacheFilename(ModuleID, CacheName))
2480b57cec5SDimitry Andric       return;
2490b57cec5SDimitry Andric     if (!CacheDir.empty()) { // Create user-defined cache dir.
2500b57cec5SDimitry Andric       SmallString<128> dir(sys::path::parent_path(CacheName));
2510b57cec5SDimitry Andric       sys::fs::create_directories(Twine(dir));
2520b57cec5SDimitry Andric     }
2530b57cec5SDimitry Andric     std::error_code EC;
254*8bcb0991SDimitry Andric     raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
2550b57cec5SDimitry Andric     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
2560b57cec5SDimitry Andric     outfile.close();
2570b57cec5SDimitry Andric   }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
2600b57cec5SDimitry Andric     const std::string &ModuleID = M->getModuleIdentifier();
2610b57cec5SDimitry Andric     std::string CacheName;
2620b57cec5SDimitry Andric     if (!getCacheFilename(ModuleID, CacheName))
2630b57cec5SDimitry Andric       return nullptr;
2640b57cec5SDimitry Andric     // Load the object from the cache filename
2650b57cec5SDimitry Andric     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
2660b57cec5SDimitry Andric         MemoryBuffer::getFile(CacheName, -1, false);
2670b57cec5SDimitry Andric     // If the file isn't there, that's OK.
2680b57cec5SDimitry Andric     if (!IRObjectBuffer)
2690b57cec5SDimitry Andric       return nullptr;
2700b57cec5SDimitry Andric     // MCJIT will want to write into this buffer, and we don't want that
2710b57cec5SDimitry Andric     // because the file has probably just been mmapped.  Instead we make
2720b57cec5SDimitry Andric     // a copy.  The filed-based buffer will be released when it goes
2730b57cec5SDimitry Andric     // out of scope.
2740b57cec5SDimitry Andric     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
2750b57cec5SDimitry Andric   }
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric private:
2780b57cec5SDimitry Andric   std::string CacheDir;
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
2810b57cec5SDimitry Andric     std::string Prefix("file:");
2820b57cec5SDimitry Andric     size_t PrefixLength = Prefix.length();
2830b57cec5SDimitry Andric     if (ModID.substr(0, PrefixLength) != Prefix)
2840b57cec5SDimitry Andric       return false;
2850b57cec5SDimitry Andric         std::string CacheSubdir = ModID.substr(PrefixLength);
2860b57cec5SDimitry Andric #if defined(_WIN32)
2870b57cec5SDimitry Andric         // Transform "X:\foo" => "/X\foo" for convenience.
2880b57cec5SDimitry Andric         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
2890b57cec5SDimitry Andric           CacheSubdir[1] = CacheSubdir[0];
2900b57cec5SDimitry Andric           CacheSubdir[0] = '/';
2910b57cec5SDimitry Andric         }
2920b57cec5SDimitry Andric #endif
2930b57cec5SDimitry Andric     CacheName = CacheDir + CacheSubdir;
2940b57cec5SDimitry Andric     size_t pos = CacheName.rfind('.');
2950b57cec5SDimitry Andric     CacheName.replace(pos, CacheName.length() - pos, ".o");
2960b57cec5SDimitry Andric     return true;
2970b57cec5SDimitry Andric   }
2980b57cec5SDimitry Andric };
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric // On Mingw and Cygwin, an external symbol named '__main' is called from the
3010b57cec5SDimitry Andric // generated 'main' function to allow static initialization.  To avoid linking
3020b57cec5SDimitry Andric // problems with remote targets (because lli's remote target support does not
3030b57cec5SDimitry Andric // currently handle external linking) we add a secondary module which defines
3040b57cec5SDimitry Andric // an empty '__main' function.
3050b57cec5SDimitry Andric static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
3060b57cec5SDimitry Andric                                   StringRef TargetTripleStr) {
3070b57cec5SDimitry Andric   IRBuilder<> Builder(Context);
3080b57cec5SDimitry Andric   Triple TargetTriple(TargetTripleStr);
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   // Create a new module.
311*8bcb0991SDimitry Andric   std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
3120b57cec5SDimitry Andric   M->setTargetTriple(TargetTripleStr);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // Create an empty function named "__main".
3150b57cec5SDimitry Andric   Type *ReturnTy;
3160b57cec5SDimitry Andric   if (TargetTriple.isArch64Bit())
3170b57cec5SDimitry Andric     ReturnTy = Type::getInt64Ty(Context);
3180b57cec5SDimitry Andric   else
3190b57cec5SDimitry Andric     ReturnTy = Type::getInt32Ty(Context);
3200b57cec5SDimitry Andric   Function *Result =
3210b57cec5SDimitry Andric       Function::Create(FunctionType::get(ReturnTy, {}, false),
3220b57cec5SDimitry Andric                        GlobalValue::ExternalLinkage, "__main", M.get());
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
3250b57cec5SDimitry Andric   Builder.SetInsertPoint(BB);
3260b57cec5SDimitry Andric   Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
3270b57cec5SDimitry Andric   Builder.CreateRet(ReturnVal);
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   // Add this new module to the ExecutionEngine.
3300b57cec5SDimitry Andric   EE.addModule(std::move(M));
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric CodeGenOpt::Level getOptLevel() {
3340b57cec5SDimitry Andric   switch (OptLevel) {
3350b57cec5SDimitry Andric   default:
3360b57cec5SDimitry Andric     WithColor::error(errs(), "lli") << "invalid optimization level.\n";
3370b57cec5SDimitry Andric     exit(1);
3380b57cec5SDimitry Andric   case '0': return CodeGenOpt::None;
3390b57cec5SDimitry Andric   case '1': return CodeGenOpt::Less;
3400b57cec5SDimitry Andric   case ' ':
3410b57cec5SDimitry Andric   case '2': return CodeGenOpt::Default;
3420b57cec5SDimitry Andric   case '3': return CodeGenOpt::Aggressive;
3430b57cec5SDimitry Andric   }
3440b57cec5SDimitry Andric   llvm_unreachable("Unrecognized opt level.");
3450b57cec5SDimitry Andric }
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric LLVM_ATTRIBUTE_NORETURN
3480b57cec5SDimitry Andric static void reportError(SMDiagnostic Err, const char *ProgName) {
3490b57cec5SDimitry Andric   Err.print(ProgName, errs());
3500b57cec5SDimitry Andric   exit(1);
3510b57cec5SDimitry Andric }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric int runOrcLazyJIT(const char *ProgName);
3540b57cec5SDimitry Andric void disallowOrcOptions();
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3570b57cec5SDimitry Andric // main Driver function
3580b57cec5SDimitry Andric //
3590b57cec5SDimitry Andric int main(int argc, char **argv, char * const *envp) {
3600b57cec5SDimitry Andric   InitLLVM X(argc, argv);
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   if (argc > 1)
3630b57cec5SDimitry Andric     ExitOnErr.setBanner(std::string(argv[0]) + ": ");
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   // If we have a native target, initialize it to ensure it is linked in and
3660b57cec5SDimitry Andric   // usable by the JIT.
3670b57cec5SDimitry Andric   InitializeNativeTarget();
3680b57cec5SDimitry Andric   InitializeNativeTargetAsmPrinter();
3690b57cec5SDimitry Andric   InitializeNativeTargetAsmParser();
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   cl::ParseCommandLineOptions(argc, argv,
3720b57cec5SDimitry Andric                               "llvm interpreter & dynamic compiler\n");
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   // If the user doesn't want core files, disable them.
3750b57cec5SDimitry Andric   if (DisableCoreFiles)
3760b57cec5SDimitry Andric     sys::Process::PreventCoreFiles();
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   if (UseJITKind == JITKind::OrcLazy)
3790b57cec5SDimitry Andric     return runOrcLazyJIT(argv[0]);
3800b57cec5SDimitry Andric   else
3810b57cec5SDimitry Andric     disallowOrcOptions();
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   LLVMContext Context;
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   // Load the bitcode...
3860b57cec5SDimitry Andric   SMDiagnostic Err;
3870b57cec5SDimitry Andric   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
3880b57cec5SDimitry Andric   Module *Mod = Owner.get();
3890b57cec5SDimitry Andric   if (!Mod)
3900b57cec5SDimitry Andric     reportError(Err, argv[0]);
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   if (EnableCacheManager) {
3930b57cec5SDimitry Andric     std::string CacheName("file:");
3940b57cec5SDimitry Andric     CacheName.append(InputFile);
3950b57cec5SDimitry Andric     Mod->setModuleIdentifier(CacheName);
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   // If not jitting lazily, load the whole bitcode file eagerly too.
3990b57cec5SDimitry Andric   if (NoLazyCompilation) {
4000b57cec5SDimitry Andric     // Use *argv instead of argv[0] to work around a wrong GCC warning.
4010b57cec5SDimitry Andric     ExitOnError ExitOnErr(std::string(*argv) +
4020b57cec5SDimitry Andric                           ": bitcode didn't read correctly: ");
4030b57cec5SDimitry Andric     ExitOnErr(Mod->materializeAll());
4040b57cec5SDimitry Andric   }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   std::string ErrorMsg;
4070b57cec5SDimitry Andric   EngineBuilder builder(std::move(Owner));
4080b57cec5SDimitry Andric   builder.setMArch(MArch);
4090b57cec5SDimitry Andric   builder.setMCPU(getCPUStr());
4100b57cec5SDimitry Andric   builder.setMAttrs(getFeatureList());
4110b57cec5SDimitry Andric   if (RelocModel.getNumOccurrences())
4120b57cec5SDimitry Andric     builder.setRelocationModel(RelocModel);
4130b57cec5SDimitry Andric   if (CMModel.getNumOccurrences())
4140b57cec5SDimitry Andric     builder.setCodeModel(CMModel);
4150b57cec5SDimitry Andric   builder.setErrorStr(&ErrorMsg);
4160b57cec5SDimitry Andric   builder.setEngineKind(ForceInterpreter
4170b57cec5SDimitry Andric                         ? EngineKind::Interpreter
4180b57cec5SDimitry Andric                         : EngineKind::JIT);
4190b57cec5SDimitry Andric   builder.setUseOrcMCJITReplacement(AcknowledgeORCv1Deprecation,
4200b57cec5SDimitry Andric                                     UseJITKind == JITKind::OrcMCJITReplacement);
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   // If we are supposed to override the target triple, do so now.
4230b57cec5SDimitry Andric   if (!TargetTriple.empty())
4240b57cec5SDimitry Andric     Mod->setTargetTriple(Triple::normalize(TargetTriple));
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   // Enable MCJIT if desired.
4270b57cec5SDimitry Andric   RTDyldMemoryManager *RTDyldMM = nullptr;
4280b57cec5SDimitry Andric   if (!ForceInterpreter) {
4290b57cec5SDimitry Andric     if (RemoteMCJIT)
4300b57cec5SDimitry Andric       RTDyldMM = new ForwardingMemoryManager();
4310b57cec5SDimitry Andric     else
4320b57cec5SDimitry Andric       RTDyldMM = new SectionMemoryManager();
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
4350b57cec5SDimitry Andric     // RTDyldMM: We still use it below, even though we don't own it.
4360b57cec5SDimitry Andric     builder.setMCJITMemoryManager(
4370b57cec5SDimitry Andric       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
4380b57cec5SDimitry Andric   } else if (RemoteMCJIT) {
4390b57cec5SDimitry Andric     WithColor::error(errs(), argv[0])
4400b57cec5SDimitry Andric         << "remote process execution does not work with the interpreter.\n";
4410b57cec5SDimitry Andric     exit(1);
4420b57cec5SDimitry Andric   }
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   builder.setOptLevel(getOptLevel());
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
4470b57cec5SDimitry Andric   if (FloatABIForCalls != FloatABI::Default)
4480b57cec5SDimitry Andric     Options.FloatABIType = FloatABIForCalls;
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   builder.setTargetOptions(Options);
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   std::unique_ptr<ExecutionEngine> EE(builder.create());
4530b57cec5SDimitry Andric   if (!EE) {
4540b57cec5SDimitry Andric     if (!ErrorMsg.empty())
4550b57cec5SDimitry Andric       WithColor::error(errs(), argv[0])
4560b57cec5SDimitry Andric           << "error creating EE: " << ErrorMsg << "\n";
4570b57cec5SDimitry Andric     else
4580b57cec5SDimitry Andric       WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
4590b57cec5SDimitry Andric     exit(1);
4600b57cec5SDimitry Andric   }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   std::unique_ptr<LLIObjectCache> CacheManager;
4630b57cec5SDimitry Andric   if (EnableCacheManager) {
4640b57cec5SDimitry Andric     CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
4650b57cec5SDimitry Andric     EE->setObjectCache(CacheManager.get());
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   // Load any additional modules specified on the command line.
4690b57cec5SDimitry Andric   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
4700b57cec5SDimitry Andric     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
4710b57cec5SDimitry Andric     if (!XMod)
4720b57cec5SDimitry Andric       reportError(Err, argv[0]);
4730b57cec5SDimitry Andric     if (EnableCacheManager) {
4740b57cec5SDimitry Andric       std::string CacheName("file:");
4750b57cec5SDimitry Andric       CacheName.append(ExtraModules[i]);
4760b57cec5SDimitry Andric       XMod->setModuleIdentifier(CacheName);
4770b57cec5SDimitry Andric     }
4780b57cec5SDimitry Andric     EE->addModule(std::move(XMod));
4790b57cec5SDimitry Andric   }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
4820b57cec5SDimitry Andric     Expected<object::OwningBinary<object::ObjectFile>> Obj =
4830b57cec5SDimitry Andric         object::ObjectFile::createObjectFile(ExtraObjects[i]);
4840b57cec5SDimitry Andric     if (!Obj) {
4850b57cec5SDimitry Andric       // TODO: Actually report errors helpfully.
4860b57cec5SDimitry Andric       consumeError(Obj.takeError());
4870b57cec5SDimitry Andric       reportError(Err, argv[0]);
4880b57cec5SDimitry Andric     }
4890b57cec5SDimitry Andric     object::OwningBinary<object::ObjectFile> &O = Obj.get();
4900b57cec5SDimitry Andric     EE->addObjectFile(std::move(O));
4910b57cec5SDimitry Andric   }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
4940b57cec5SDimitry Andric     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
4950b57cec5SDimitry Andric         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
4960b57cec5SDimitry Andric     if (!ArBufOrErr)
4970b57cec5SDimitry Andric       reportError(Err, argv[0]);
4980b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric     Expected<std::unique_ptr<object::Archive>> ArOrErr =
5010b57cec5SDimitry Andric         object::Archive::create(ArBuf->getMemBufferRef());
5020b57cec5SDimitry Andric     if (!ArOrErr) {
5030b57cec5SDimitry Andric       std::string Buf;
5040b57cec5SDimitry Andric       raw_string_ostream OS(Buf);
5050b57cec5SDimitry Andric       logAllUnhandledErrors(ArOrErr.takeError(), OS);
5060b57cec5SDimitry Andric       OS.flush();
5070b57cec5SDimitry Andric       errs() << Buf;
5080b57cec5SDimitry Andric       exit(1);
5090b57cec5SDimitry Andric     }
5100b57cec5SDimitry Andric     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric     EE->addArchive(std::move(OB));
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   // If the target is Cygwin/MingW and we are generating remote code, we
5180b57cec5SDimitry Andric   // need an extra module to help out with linking.
5190b57cec5SDimitry Andric   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
5200b57cec5SDimitry Andric     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
5210b57cec5SDimitry Andric   }
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   // The following functions have no effect if their respective profiling
5240b57cec5SDimitry Andric   // support wasn't enabled in the build configuration.
5250b57cec5SDimitry Andric   EE->RegisterJITEventListener(
5260b57cec5SDimitry Andric                 JITEventListener::createOProfileJITEventListener());
5270b57cec5SDimitry Andric   EE->RegisterJITEventListener(
5280b57cec5SDimitry Andric                 JITEventListener::createIntelJITEventListener());
5290b57cec5SDimitry Andric   if (!RemoteMCJIT)
5300b57cec5SDimitry Andric     EE->RegisterJITEventListener(
5310b57cec5SDimitry Andric                 JITEventListener::createPerfJITEventListener());
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric   if (!NoLazyCompilation && RemoteMCJIT) {
5340b57cec5SDimitry Andric     WithColor::warning(errs(), argv[0])
5350b57cec5SDimitry Andric         << "remote mcjit does not support lazy compilation\n";
5360b57cec5SDimitry Andric     NoLazyCompilation = true;
5370b57cec5SDimitry Andric   }
5380b57cec5SDimitry Andric   EE->DisableLazyCompilation(NoLazyCompilation);
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   // If the user specifically requested an argv[0] to pass into the program,
5410b57cec5SDimitry Andric   // do it now.
5420b57cec5SDimitry Andric   if (!FakeArgv0.empty()) {
5430b57cec5SDimitry Andric     InputFile = static_cast<std::string>(FakeArgv0);
5440b57cec5SDimitry Andric   } else {
5450b57cec5SDimitry Andric     // Otherwise, if there is a .bc suffix on the executable strip it off, it
5460b57cec5SDimitry Andric     // might confuse the program.
5470b57cec5SDimitry Andric     if (StringRef(InputFile).endswith(".bc"))
5480b57cec5SDimitry Andric       InputFile.erase(InputFile.length() - 3);
5490b57cec5SDimitry Andric   }
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric   // Add the module's name to the start of the vector of arguments to main().
5520b57cec5SDimitry Andric   InputArgv.insert(InputArgv.begin(), InputFile);
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric   // Call the main function from M as if its signature were:
5550b57cec5SDimitry Andric   //   int main (int argc, char **argv, const char **envp)
5560b57cec5SDimitry Andric   // using the contents of Args to determine argc & argv, and the contents of
5570b57cec5SDimitry Andric   // EnvVars to determine envp.
5580b57cec5SDimitry Andric   //
5590b57cec5SDimitry Andric   Function *EntryFn = Mod->getFunction(EntryFunc);
5600b57cec5SDimitry Andric   if (!EntryFn) {
5610b57cec5SDimitry Andric     WithColor::error(errs(), argv[0])
5620b57cec5SDimitry Andric         << '\'' << EntryFunc << "\' function not found in module.\n";
5630b57cec5SDimitry Andric     return -1;
5640b57cec5SDimitry Andric   }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   // Reset errno to zero on entry to main.
5670b57cec5SDimitry Andric   errno = 0;
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   int Result = -1;
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   // Sanity check use of remote-jit: LLI currently only supports use of the
5720b57cec5SDimitry Andric   // remote JIT on Unix platforms.
5730b57cec5SDimitry Andric   if (RemoteMCJIT) {
5740b57cec5SDimitry Andric #ifndef LLVM_ON_UNIX
5750b57cec5SDimitry Andric     WithColor::warning(errs(), argv[0])
5760b57cec5SDimitry Andric         << "host does not support external remote targets.\n";
5770b57cec5SDimitry Andric     WithColor::note() << "defaulting to local execution\n";
5780b57cec5SDimitry Andric     return -1;
5790b57cec5SDimitry Andric #else
5800b57cec5SDimitry Andric     if (ChildExecPath.empty()) {
5810b57cec5SDimitry Andric       WithColor::error(errs(), argv[0])
5820b57cec5SDimitry Andric           << "-remote-mcjit requires -mcjit-remote-process.\n";
5830b57cec5SDimitry Andric       exit(1);
5840b57cec5SDimitry Andric     } else if (!sys::fs::can_execute(ChildExecPath)) {
5850b57cec5SDimitry Andric       WithColor::error(errs(), argv[0])
5860b57cec5SDimitry Andric           << "unable to find usable child executable: '" << ChildExecPath
5870b57cec5SDimitry Andric           << "'\n";
5880b57cec5SDimitry Andric       return -1;
5890b57cec5SDimitry Andric     }
5900b57cec5SDimitry Andric #endif
5910b57cec5SDimitry Andric   }
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   if (!RemoteMCJIT) {
5940b57cec5SDimitry Andric     // If the program doesn't explicitly call exit, we will need the Exit
5950b57cec5SDimitry Andric     // function later on to make an explicit call, so get the function now.
5960b57cec5SDimitry Andric     FunctionCallee Exit = Mod->getOrInsertFunction(
5970b57cec5SDimitry Andric         "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric     // Run static constructors.
6000b57cec5SDimitry Andric     if (!ForceInterpreter) {
6010b57cec5SDimitry Andric       // Give MCJIT a chance to apply relocations and set page permissions.
6020b57cec5SDimitry Andric       EE->finalizeObject();
6030b57cec5SDimitry Andric     }
6040b57cec5SDimitry Andric     EE->runStaticConstructorsDestructors(false);
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric     // Trigger compilation separately so code regions that need to be
6070b57cec5SDimitry Andric     // invalidated will be known.
6080b57cec5SDimitry Andric     (void)EE->getPointerToFunction(EntryFn);
6090b57cec5SDimitry Andric     // Clear instruction cache before code will be executed.
6100b57cec5SDimitry Andric     if (RTDyldMM)
6110b57cec5SDimitry Andric       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric     // Run main.
6140b57cec5SDimitry Andric     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     // Run static destructors.
6170b57cec5SDimitry Andric     EE->runStaticConstructorsDestructors(true);
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric     // If the program didn't call exit explicitly, we should call it now.
6200b57cec5SDimitry Andric     // This ensures that any atexit handlers get called correctly.
6210b57cec5SDimitry Andric     if (Function *ExitF =
6220b57cec5SDimitry Andric             dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
6230b57cec5SDimitry Andric       if (ExitF->getFunctionType() == Exit.getFunctionType()) {
6240b57cec5SDimitry Andric         std::vector<GenericValue> Args;
6250b57cec5SDimitry Andric         GenericValue ResultGV;
6260b57cec5SDimitry Andric         ResultGV.IntVal = APInt(32, Result);
6270b57cec5SDimitry Andric         Args.push_back(ResultGV);
6280b57cec5SDimitry Andric         EE->runFunction(ExitF, Args);
6290b57cec5SDimitry Andric         WithColor::error(errs(), argv[0])
6300b57cec5SDimitry Andric             << "exit(" << Result << ") returned!\n";
6310b57cec5SDimitry Andric         abort();
6320b57cec5SDimitry Andric       }
6330b57cec5SDimitry Andric     }
6340b57cec5SDimitry Andric     WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
6350b57cec5SDimitry Andric     abort();
6360b57cec5SDimitry Andric   } else {
6370b57cec5SDimitry Andric     // else == "if (RemoteMCJIT)"
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric     // Remote target MCJIT doesn't (yet) support static constructors. No reason
6400b57cec5SDimitry Andric     // it couldn't. This is a limitation of the LLI implementation, not the
6410b57cec5SDimitry Andric     // MCJIT itself. FIXME.
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric     // Lanch the remote process and get a channel to it.
6440b57cec5SDimitry Andric     std::unique_ptr<FDRawChannel> C = launchRemote();
6450b57cec5SDimitry Andric     if (!C) {
6460b57cec5SDimitry Andric       WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
6470b57cec5SDimitry Andric       exit(1);
6480b57cec5SDimitry Andric     }
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric     // Create a remote target client running over the channel.
6510b57cec5SDimitry Andric     llvm::orc::ExecutionSession ES;
6520b57cec5SDimitry Andric     ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
6530b57cec5SDimitry Andric     typedef orc::remote::OrcRemoteTargetClient MyRemote;
6540b57cec5SDimitry Andric     auto R = ExitOnErr(MyRemote::Create(*C, ES));
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric     // Create a remote memory manager.
6570b57cec5SDimitry Andric     auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric     // Forward MCJIT's memory manager calls to the remote memory manager.
6600b57cec5SDimitry Andric     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
6610b57cec5SDimitry Andric       std::move(RemoteMM));
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric     // Forward MCJIT's symbol resolution calls to the remote.
6640b57cec5SDimitry Andric     static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
6650b57cec5SDimitry Andric         orc::createLambdaResolver(
6660b57cec5SDimitry Andric             AcknowledgeORCv1Deprecation,
6670b57cec5SDimitry Andric             [](const std::string &Name) { return nullptr; },
6680b57cec5SDimitry Andric             [&](const std::string &Name) {
6690b57cec5SDimitry Andric               if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
6700b57cec5SDimitry Andric                 return JITSymbol(Addr, JITSymbolFlags::Exported);
6710b57cec5SDimitry Andric               return JITSymbol(nullptr);
6720b57cec5SDimitry Andric             }));
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     // Grab the target address of the JIT'd main function on the remote and call
6750b57cec5SDimitry Andric     // it.
6760b57cec5SDimitry Andric     // FIXME: argv and envp handling.
6770b57cec5SDimitry Andric     JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
6780b57cec5SDimitry Andric     EE->finalizeObject();
6790b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
6800b57cec5SDimitry Andric                       << format("%llx", Entry) << "\n");
6810b57cec5SDimitry Andric     Result = ExitOnErr(R->callIntVoid(Entry));
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric     // Like static constructors, the remote target MCJIT support doesn't handle
6840b57cec5SDimitry Andric     // this yet. It could. FIXME.
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric     // Delete the EE - we need to tear it down *before* we terminate the session
6870b57cec5SDimitry Andric     // with the remote, otherwise it'll crash when it tries to release resources
6880b57cec5SDimitry Andric     // on a remote that has already been disconnected.
6890b57cec5SDimitry Andric     EE.reset();
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric     // Signal the remote target that we're done JITing.
6920b57cec5SDimitry Andric     ExitOnErr(R->terminateSession());
6930b57cec5SDimitry Andric   }
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   return Result;
6960b57cec5SDimitry Andric }
6970b57cec5SDimitry Andric 
698*8bcb0991SDimitry Andric static std::function<void(Module &)> createDebugDumper() {
6990b57cec5SDimitry Andric   switch (OrcDumpKind) {
7000b57cec5SDimitry Andric   case DumpKind::NoDump:
701*8bcb0991SDimitry Andric     return [](Module &M) {};
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   case DumpKind::DumpFuncsToStdOut:
704*8bcb0991SDimitry Andric     return [](Module &M) {
7050b57cec5SDimitry Andric       printf("[ ");
7060b57cec5SDimitry Andric 
707*8bcb0991SDimitry Andric       for (const auto &F : M) {
7080b57cec5SDimitry Andric         if (F.isDeclaration())
7090b57cec5SDimitry Andric           continue;
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric         if (F.hasName()) {
7120b57cec5SDimitry Andric           std::string Name(F.getName());
7130b57cec5SDimitry Andric           printf("%s ", Name.c_str());
7140b57cec5SDimitry Andric         } else
7150b57cec5SDimitry Andric           printf("<anon> ");
7160b57cec5SDimitry Andric       }
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric       printf("]\n");
7190b57cec5SDimitry Andric     };
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   case DumpKind::DumpModsToStdOut:
722*8bcb0991SDimitry Andric     return [](Module &M) {
723*8bcb0991SDimitry Andric       outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
7240b57cec5SDimitry Andric     };
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   case DumpKind::DumpModsToDisk:
727*8bcb0991SDimitry Andric     return [](Module &M) {
7280b57cec5SDimitry Andric       std::error_code EC;
729*8bcb0991SDimitry Andric       raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC, sys::fs::OF_Text);
7300b57cec5SDimitry Andric       if (EC) {
731*8bcb0991SDimitry Andric         errs() << "Couldn't open " << M.getModuleIdentifier()
7320b57cec5SDimitry Andric                << " for dumping.\nError:" << EC.message() << "\n";
7330b57cec5SDimitry Andric         exit(1);
7340b57cec5SDimitry Andric       }
735*8bcb0991SDimitry Andric       Out << M;
7360b57cec5SDimitry Andric     };
7370b57cec5SDimitry Andric   }
7380b57cec5SDimitry Andric   llvm_unreachable("Unknown DumpKind");
7390b57cec5SDimitry Andric }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric static void exitOnLazyCallThroughFailure() { exit(1); }
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric int runOrcLazyJIT(const char *ProgName) {
7440b57cec5SDimitry Andric   // Start setting up the JIT environment.
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   // Parse the main module.
747*8bcb0991SDimitry Andric   orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
7480b57cec5SDimitry Andric   SMDiagnostic Err;
749*8bcb0991SDimitry Andric   auto MainModule = parseIRFile(InputFile, Err, *TSCtx.getContext());
7500b57cec5SDimitry Andric   if (!MainModule)
7510b57cec5SDimitry Andric     reportError(Err, ProgName);
7520b57cec5SDimitry Andric 
753*8bcb0991SDimitry Andric   const auto &TT = MainModule->getTargetTriple();
7540b57cec5SDimitry Andric   orc::LLLazyJITBuilder Builder;
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   Builder.setJITTargetMachineBuilder(
7570b57cec5SDimitry Andric       TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
7580b57cec5SDimitry Andric                  : orc::JITTargetMachineBuilder(Triple(TT)));
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   if (!MArch.empty())
7610b57cec5SDimitry Andric     Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(MArch);
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   Builder.getJITTargetMachineBuilder()
7640b57cec5SDimitry Andric       ->setCPU(getCPUStr())
7650b57cec5SDimitry Andric       .addFeatures(getFeatureList())
7660b57cec5SDimitry Andric       .setRelocationModel(RelocModel.getNumOccurrences()
7670b57cec5SDimitry Andric                               ? Optional<Reloc::Model>(RelocModel)
7680b57cec5SDimitry Andric                               : None)
7690b57cec5SDimitry Andric       .setCodeModel(CMModel.getNumOccurrences()
7700b57cec5SDimitry Andric                         ? Optional<CodeModel::Model>(CMModel)
7710b57cec5SDimitry Andric                         : None);
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric   Builder.setLazyCompileFailureAddr(
7740b57cec5SDimitry Andric       pointerToJITTargetAddress(exitOnLazyCallThroughFailure));
7750b57cec5SDimitry Andric   Builder.setNumCompileThreads(LazyJITCompileThreads);
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   auto J = ExitOnErr(Builder.create());
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   if (PerModuleLazy)
7800b57cec5SDimitry Andric     J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   auto Dump = createDebugDumper();
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   J->setLazyCompileTransform([&](orc::ThreadSafeModule TSM,
7850b57cec5SDimitry Andric                                  const orc::MaterializationResponsibility &R) {
786*8bcb0991SDimitry Andric     TSM.withModuleDo([&](Module &M) {
787*8bcb0991SDimitry Andric       if (verifyModule(M, &dbgs())) {
788*8bcb0991SDimitry Andric         dbgs() << "Bad module: " << &M << "\n";
7890b57cec5SDimitry Andric         exit(1);
7900b57cec5SDimitry Andric       }
791*8bcb0991SDimitry Andric       Dump(M);
7920b57cec5SDimitry Andric     });
793*8bcb0991SDimitry Andric     return TSM;
794*8bcb0991SDimitry Andric   });
795*8bcb0991SDimitry Andric   J->getMainJITDylib().addGenerator(
7960b57cec5SDimitry Andric       ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
7970b57cec5SDimitry Andric           J->getDataLayout().getGlobalPrefix())));
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric   orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
8000b57cec5SDimitry Andric   orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
8010b57cec5SDimitry Andric   ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   // Add the main module.
804*8bcb0991SDimitry Andric   ExitOnErr(
805*8bcb0991SDimitry Andric       J->addLazyIRModule(orc::ThreadSafeModule(std::move(MainModule), TSCtx)));
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   // Create JITDylibs and add any extra modules.
8080b57cec5SDimitry Andric   {
8090b57cec5SDimitry Andric     // Create JITDylibs, keep a map from argument index to dylib. We will use
8100b57cec5SDimitry Andric     // -extra-module argument indexes to determine what dylib to use for each
8110b57cec5SDimitry Andric     // -extra-module.
8120b57cec5SDimitry Andric     std::map<unsigned, orc::JITDylib *> IdxToDylib;
8130b57cec5SDimitry Andric     IdxToDylib[0] = &J->getMainJITDylib();
8140b57cec5SDimitry Andric     for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
8150b57cec5SDimitry Andric          JDItr != JDEnd; ++JDItr) {
8160b57cec5SDimitry Andric       orc::JITDylib *JD = J->getJITDylibByName(*JDItr);
8170b57cec5SDimitry Andric       if (!JD)
8180b57cec5SDimitry Andric         JD = &J->createJITDylib(*JDItr);
8190b57cec5SDimitry Andric       IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;
8200b57cec5SDimitry Andric     }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric     for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
8230b57cec5SDimitry Andric          EMItr != EMEnd; ++EMItr) {
8240b57cec5SDimitry Andric       auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
8250b57cec5SDimitry Andric       if (!M)
8260b57cec5SDimitry Andric         reportError(Err, ProgName);
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric       auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
8290b57cec5SDimitry Andric       assert(EMIdx != 0 && "ExtraModule should have index > 0");
8300b57cec5SDimitry Andric       auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
8310b57cec5SDimitry Andric       auto &JD = *JDItr->second;
8320b57cec5SDimitry Andric       ExitOnErr(
8330b57cec5SDimitry Andric           J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
8340b57cec5SDimitry Andric     }
835*8bcb0991SDimitry Andric 
836*8bcb0991SDimitry Andric     for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
837*8bcb0991SDimitry Andric          EAItr != EAEnd; ++EAItr) {
838*8bcb0991SDimitry Andric       auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());
839*8bcb0991SDimitry Andric       assert(EAIdx != 0 && "ExtraArchive should have index > 0");
840*8bcb0991SDimitry Andric       auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));
841*8bcb0991SDimitry Andric       auto &JD = *JDItr->second;
842*8bcb0991SDimitry Andric       JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load(
843*8bcb0991SDimitry Andric           J->getObjLinkingLayer(), EAItr->c_str())));
844*8bcb0991SDimitry Andric     }
8450b57cec5SDimitry Andric   }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   // Add the objects.
8480b57cec5SDimitry Andric   for (auto &ObjPath : ExtraObjects) {
8490b57cec5SDimitry Andric     auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
8500b57cec5SDimitry Andric     ExitOnErr(J->addObjectFile(std::move(Obj)));
8510b57cec5SDimitry Andric   }
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   // Generate a argument string.
8540b57cec5SDimitry Andric   std::vector<std::string> Args;
8550b57cec5SDimitry Andric   Args.push_back(InputFile);
8560b57cec5SDimitry Andric   for (auto &Arg : InputArgv)
8570b57cec5SDimitry Andric     Args.push_back(Arg);
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   // Run any static constructors.
8600b57cec5SDimitry Andric   ExitOnErr(J->runConstructors());
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   // Run any -thread-entry points.
8630b57cec5SDimitry Andric   std::vector<std::thread> AltEntryThreads;
8640b57cec5SDimitry Andric   for (auto &ThreadEntryPoint : ThreadEntryPoints) {
8650b57cec5SDimitry Andric     auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
8660b57cec5SDimitry Andric     typedef void (*EntryPointPtr)();
8670b57cec5SDimitry Andric     auto EntryPoint =
8680b57cec5SDimitry Andric       reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
8690b57cec5SDimitry Andric     AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
8700b57cec5SDimitry Andric   }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric   // Run main.
8730b57cec5SDimitry Andric   auto MainSym = ExitOnErr(J->lookup("main"));
8740b57cec5SDimitry Andric   typedef int (*MainFnPtr)(int, const char *[]);
8750b57cec5SDimitry Andric   std::vector<const char *> ArgV;
8760b57cec5SDimitry Andric   for (auto &Arg : Args)
8770b57cec5SDimitry Andric     ArgV.push_back(Arg.c_str());
8780b57cec5SDimitry Andric   ArgV.push_back(nullptr);
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric   int ArgC = ArgV.size() - 1;
8810b57cec5SDimitry Andric   auto Main =
8820b57cec5SDimitry Andric       reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
8830b57cec5SDimitry Andric   auto Result = Main(ArgC, (const char **)ArgV.data());
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric   // Wait for -entry-point threads.
8860b57cec5SDimitry Andric   for (auto &AltEntryThread : AltEntryThreads)
8870b57cec5SDimitry Andric     AltEntryThread.join();
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   // Run destructors.
8900b57cec5SDimitry Andric   ExitOnErr(J->runDestructors());
8910b57cec5SDimitry Andric   CXXRuntimeOverrides.runDestructors();
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   return Result;
8940b57cec5SDimitry Andric }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric void disallowOrcOptions() {
8970b57cec5SDimitry Andric   // Make sure nobody used an orc-lazy specific option accidentally.
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   if (LazyJITCompileThreads != 0) {
9000b57cec5SDimitry Andric     errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
9010b57cec5SDimitry Andric     exit(1);
9020b57cec5SDimitry Andric   }
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   if (!ThreadEntryPoints.empty()) {
9050b57cec5SDimitry Andric     errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
9060b57cec5SDimitry Andric     exit(1);
9070b57cec5SDimitry Andric   }
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric   if (PerModuleLazy) {
9100b57cec5SDimitry Andric     errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
9110b57cec5SDimitry Andric     exit(1);
9120b57cec5SDimitry Andric   }
9130b57cec5SDimitry Andric }
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric std::unique_ptr<FDRawChannel> launchRemote() {
9160b57cec5SDimitry Andric #ifndef LLVM_ON_UNIX
9170b57cec5SDimitry Andric   llvm_unreachable("launchRemote not supported on non-Unix platforms");
9180b57cec5SDimitry Andric #else
9190b57cec5SDimitry Andric   int PipeFD[2][2];
9200b57cec5SDimitry Andric   pid_t ChildPID;
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   // Create two pipes.
9230b57cec5SDimitry Andric   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
9240b57cec5SDimitry Andric     perror("Error creating pipe: ");
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   ChildPID = fork();
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   if (ChildPID == 0) {
9290b57cec5SDimitry Andric     // In the child...
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric     // Close the parent ends of the pipes
9320b57cec5SDimitry Andric     close(PipeFD[0][1]);
9330b57cec5SDimitry Andric     close(PipeFD[1][0]);
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric     // Execute the child process.
9370b57cec5SDimitry Andric     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
9380b57cec5SDimitry Andric     {
9390b57cec5SDimitry Andric       ChildPath.reset(new char[ChildExecPath.size() + 1]);
9400b57cec5SDimitry Andric       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
9410b57cec5SDimitry Andric       ChildPath[ChildExecPath.size()] = '\0';
9420b57cec5SDimitry Andric       std::string ChildInStr = utostr(PipeFD[0][0]);
9430b57cec5SDimitry Andric       ChildIn.reset(new char[ChildInStr.size() + 1]);
9440b57cec5SDimitry Andric       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
9450b57cec5SDimitry Andric       ChildIn[ChildInStr.size()] = '\0';
9460b57cec5SDimitry Andric       std::string ChildOutStr = utostr(PipeFD[1][1]);
9470b57cec5SDimitry Andric       ChildOut.reset(new char[ChildOutStr.size() + 1]);
9480b57cec5SDimitry Andric       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
9490b57cec5SDimitry Andric       ChildOut[ChildOutStr.size()] = '\0';
9500b57cec5SDimitry Andric     }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
9530b57cec5SDimitry Andric     int rc = execv(ChildExecPath.c_str(), args);
9540b57cec5SDimitry Andric     if (rc != 0)
9550b57cec5SDimitry Andric       perror("Error executing child process: ");
9560b57cec5SDimitry Andric     llvm_unreachable("Error executing child process");
9570b57cec5SDimitry Andric   }
9580b57cec5SDimitry Andric   // else we're the parent...
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   // Close the child ends of the pipes
9610b57cec5SDimitry Andric   close(PipeFD[0][0]);
9620b57cec5SDimitry Andric   close(PipeFD[1][1]);
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   // Return an RPC channel connected to our end of the pipes.
965*8bcb0991SDimitry Andric   return std::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
9660b57cec5SDimitry Andric #endif
9670b57cec5SDimitry Andric }
968