xref: /llvm-project-15.0.7/llvm/tools/lli/lli.cpp (revision cdc514e4)
1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility provides a simple wrapper around the LLVM Execution Engines,
10 // which allow the direct execution of LLVM programs through a Just-In-Time
11 // compiler, or through an interpreter if no JIT is available for this platform.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "RemoteJITUtils.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/BitcodeReader.h"
19 #include "llvm/CodeGen/CommandFlags.inc"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/ExecutionEngine/Interpreter.h"
24 #include "llvm/ExecutionEngine/JITEventListener.h"
25 #include "llvm/ExecutionEngine/MCJIT.h"
26 #include "llvm/ExecutionEngine/ObjectCache.h"
27 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
28 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
29 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
30 #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
31 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
32 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/IRReader/IRReader.h"
39 #include "llvm/Object/Archive.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/DynamicLibrary.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/ManagedStatic.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/Memory.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Path.h"
51 #include "llvm/Support/PluginLoader.h"
52 #include "llvm/Support/Process.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/SourceMgr.h"
55 #include "llvm/Support/TargetSelect.h"
56 #include "llvm/Support/WithColor.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Instrumentation.h"
59 #include <cerrno>
60 
61 #ifdef __CYGWIN__
62 #include <cygwin/version.h>
63 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
64 #define DO_NOTHING_ATEXIT 1
65 #endif
66 #endif
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "lli"
71 
72 namespace {
73 
74   enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
75 
76   cl::opt<std::string>
77   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
78 
79   cl::list<std::string>
80   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
81 
82   cl::opt<bool> ForceInterpreter("force-interpreter",
83                                  cl::desc("Force interpretation: disable JIT"),
84                                  cl::init(false));
85 
86   cl::opt<JITKind> UseJITKind(
87       "jit-kind", cl::desc("Choose underlying JIT kind."),
88       cl::init(JITKind::MCJIT),
89       cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"),
90                  clEnumValN(JITKind::OrcMCJITReplacement, "orc-mcjit",
91                             "Orc-based MCJIT replacement "
92                             "(deprecated)"),
93                  clEnumValN(JITKind::OrcLazy, "orc-lazy",
94                             "Orc-based lazy JIT.")));
95 
96   cl::opt<unsigned>
97   LazyJITCompileThreads("compile-threads",
98                         cl::desc("Choose the number of compile threads "
99                                  "(jit-kind=orc-lazy only)"),
100                         cl::init(0));
101 
102   cl::list<std::string>
103   ThreadEntryPoints("thread-entry",
104                     cl::desc("calls the given entry-point on a new thread "
105                              "(jit-kind=orc-lazy only)"));
106 
107   cl::opt<bool> PerModuleLazy(
108       "per-module-lazy",
109       cl::desc("Performs lazy compilation on whole module boundaries "
110                "rather than individual functions"),
111       cl::init(false));
112 
113   cl::list<std::string>
114       JITDylibs("jd",
115                 cl::desc("Specifies the JITDylib to be used for any subsequent "
116                          "-extra-module arguments."));
117 
118   cl::list<std::string>
119     Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"),
120            cl::ZeroOrMore);
121 
122   // The MCJIT supports building for a target address space separate from
123   // the JIT compilation process. Use a forked process and a copying
124   // memory manager with IPC to execute using this functionality.
125   cl::opt<bool> RemoteMCJIT("remote-mcjit",
126     cl::desc("Execute MCJIT'ed code in a separate process."),
127     cl::init(false));
128 
129   // Manually specify the child process for remote execution. This overrides
130   // the simulated remote execution that allocates address space for child
131   // execution. The child process will be executed and will communicate with
132   // lli via stdin/stdout pipes.
133   cl::opt<std::string>
134   ChildExecPath("mcjit-remote-process",
135                 cl::desc("Specify the filename of the process to launch "
136                          "for remote MCJIT execution.  If none is specified,"
137                          "\n\tremote execution will be simulated in-process."),
138                 cl::value_desc("filename"), cl::init(""));
139 
140   // Determine optimization level.
141   cl::opt<char>
142   OptLevel("O",
143            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
144                     "(default = '-O2')"),
145            cl::Prefix,
146            cl::ZeroOrMore,
147            cl::init(' '));
148 
149   cl::opt<std::string>
150   TargetTriple("mtriple", cl::desc("Override target triple for module"));
151 
152   cl::opt<std::string>
153   EntryFunc("entry-function",
154             cl::desc("Specify the entry function (default = 'main') "
155                      "of the executable"),
156             cl::value_desc("function"),
157             cl::init("main"));
158 
159   cl::list<std::string>
160   ExtraModules("extra-module",
161          cl::desc("Extra modules to be loaded"),
162          cl::value_desc("input bitcode"));
163 
164   cl::list<std::string>
165   ExtraObjects("extra-object",
166          cl::desc("Extra object files to be loaded"),
167          cl::value_desc("input object"));
168 
169   cl::list<std::string>
170   ExtraArchives("extra-archive",
171          cl::desc("Extra archive files to be loaded"),
172          cl::value_desc("input archive"));
173 
174   cl::opt<bool>
175   EnableCacheManager("enable-cache-manager",
176         cl::desc("Use cache manager to save/load modules"),
177         cl::init(false));
178 
179   cl::opt<std::string>
180   ObjectCacheDir("object-cache-dir",
181                   cl::desc("Directory to store cached object files "
182                            "(must be user writable)"),
183                   cl::init(""));
184 
185   cl::opt<std::string>
186   FakeArgv0("fake-argv0",
187             cl::desc("Override the 'argv[0]' value passed into the executing"
188                      " program"), cl::value_desc("executable"));
189 
190   cl::opt<bool>
191   DisableCoreFiles("disable-core-files", cl::Hidden,
192                    cl::desc("Disable emission of core files if possible"));
193 
194   cl::opt<bool>
195   NoLazyCompilation("disable-lazy-compilation",
196                   cl::desc("Disable JIT lazy compilation"),
197                   cl::init(false));
198 
199   cl::opt<bool>
200   GenerateSoftFloatCalls("soft-float",
201     cl::desc("Generate software floating point library calls"),
202     cl::init(false));
203 
204   cl::opt<bool> NoProcessSymbols(
205       "no-process-syms",
206       cl::desc("Do not resolve lli process symbols in JIT'd code"),
207       cl::init(false));
208 
209   enum class DumpKind {
210     NoDump,
211     DumpFuncsToStdOut,
212     DumpModsToStdOut,
213     DumpModsToDisk
214   };
215 
216   cl::opt<DumpKind> OrcDumpKind(
217       "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
218       cl::init(DumpKind::NoDump),
219       cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
220                             "Don't dump anything."),
221                  clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
222                             "Dump function names to stdout."),
223                  clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
224                             "Dump modules to stdout."),
225                  clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
226                             "Dump modules to the current "
227                             "working directory. (WARNING: "
228                             "will overwrite existing files).")),
229       cl::Hidden);
230 
231   ExitOnError ExitOnErr;
232 }
233 
234 //===----------------------------------------------------------------------===//
235 // Object cache
236 //
237 // This object cache implementation writes cached objects to disk to the
238 // directory specified by CacheDir, using a filename provided in the module
239 // descriptor. The cache tries to load a saved object using that path if the
240 // file exists. CacheDir defaults to "", in which case objects are cached
241 // alongside their originating bitcodes.
242 //
243 class LLIObjectCache : public ObjectCache {
244 public:
245   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
246     // Add trailing '/' to cache dir if necessary.
247     if (!this->CacheDir.empty() &&
248         this->CacheDir[this->CacheDir.size() - 1] != '/')
249       this->CacheDir += '/';
250   }
251   ~LLIObjectCache() override {}
252 
253   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
254     const std::string &ModuleID = M->getModuleIdentifier();
255     std::string CacheName;
256     if (!getCacheFilename(ModuleID, CacheName))
257       return;
258     if (!CacheDir.empty()) { // Create user-defined cache dir.
259       SmallString<128> dir(sys::path::parent_path(CacheName));
260       sys::fs::create_directories(Twine(dir));
261     }
262     std::error_code EC;
263     raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None);
264     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
265     outfile.close();
266   }
267 
268   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
269     const std::string &ModuleID = M->getModuleIdentifier();
270     std::string CacheName;
271     if (!getCacheFilename(ModuleID, CacheName))
272       return nullptr;
273     // Load the object from the cache filename
274     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
275         MemoryBuffer::getFile(CacheName, -1, false);
276     // If the file isn't there, that's OK.
277     if (!IRObjectBuffer)
278       return nullptr;
279     // MCJIT will want to write into this buffer, and we don't want that
280     // because the file has probably just been mmapped.  Instead we make
281     // a copy.  The filed-based buffer will be released when it goes
282     // out of scope.
283     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
284   }
285 
286 private:
287   std::string CacheDir;
288 
289   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
290     std::string Prefix("file:");
291     size_t PrefixLength = Prefix.length();
292     if (ModID.substr(0, PrefixLength) != Prefix)
293       return false;
294         std::string CacheSubdir = ModID.substr(PrefixLength);
295 #if defined(_WIN32)
296         // Transform "X:\foo" => "/X\foo" for convenience.
297         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
298           CacheSubdir[1] = CacheSubdir[0];
299           CacheSubdir[0] = '/';
300         }
301 #endif
302     CacheName = CacheDir + CacheSubdir;
303     size_t pos = CacheName.rfind('.');
304     CacheName.replace(pos, CacheName.length() - pos, ".o");
305     return true;
306   }
307 };
308 
309 // On Mingw and Cygwin, an external symbol named '__main' is called from the
310 // generated 'main' function to allow static initialization.  To avoid linking
311 // problems with remote targets (because lli's remote target support does not
312 // currently handle external linking) we add a secondary module which defines
313 // an empty '__main' function.
314 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
315                                   StringRef TargetTripleStr) {
316   IRBuilder<> Builder(Context);
317   Triple TargetTriple(TargetTripleStr);
318 
319   // Create a new module.
320   std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
321   M->setTargetTriple(TargetTripleStr);
322 
323   // Create an empty function named "__main".
324   Type *ReturnTy;
325   if (TargetTriple.isArch64Bit())
326     ReturnTy = Type::getInt64Ty(Context);
327   else
328     ReturnTy = Type::getInt32Ty(Context);
329   Function *Result =
330       Function::Create(FunctionType::get(ReturnTy, {}, false),
331                        GlobalValue::ExternalLinkage, "__main", M.get());
332 
333   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
334   Builder.SetInsertPoint(BB);
335   Value *ReturnVal = ConstantInt::get(ReturnTy, 0);
336   Builder.CreateRet(ReturnVal);
337 
338   // Add this new module to the ExecutionEngine.
339   EE.addModule(std::move(M));
340 }
341 
342 CodeGenOpt::Level getOptLevel() {
343   switch (OptLevel) {
344   default:
345     WithColor::error(errs(), "lli") << "invalid optimization level.\n";
346     exit(1);
347   case '0': return CodeGenOpt::None;
348   case '1': return CodeGenOpt::Less;
349   case ' ':
350   case '2': return CodeGenOpt::Default;
351   case '3': return CodeGenOpt::Aggressive;
352   }
353   llvm_unreachable("Unrecognized opt level.");
354 }
355 
356 LLVM_ATTRIBUTE_NORETURN
357 static void reportError(SMDiagnostic Err, const char *ProgName) {
358   Err.print(ProgName, errs());
359   exit(1);
360 }
361 
362 Error loadDylibs();
363 int runOrcLazyJIT(const char *ProgName);
364 void disallowOrcOptions();
365 
366 //===----------------------------------------------------------------------===//
367 // main Driver function
368 //
369 int main(int argc, char **argv, char * const *envp) {
370   InitLLVM X(argc, argv);
371 
372   if (argc > 1)
373     ExitOnErr.setBanner(std::string(argv[0]) + ": ");
374 
375   // If we have a native target, initialize it to ensure it is linked in and
376   // usable by the JIT.
377   InitializeNativeTarget();
378   InitializeNativeTargetAsmPrinter();
379   InitializeNativeTargetAsmParser();
380 
381   cl::ParseCommandLineOptions(argc, argv,
382                               "llvm interpreter & dynamic compiler\n");
383 
384   // If the user doesn't want core files, disable them.
385   if (DisableCoreFiles)
386     sys::Process::PreventCoreFiles();
387 
388   ExitOnErr(loadDylibs());
389 
390   if (UseJITKind == JITKind::OrcLazy)
391     return runOrcLazyJIT(argv[0]);
392   else
393     disallowOrcOptions();
394 
395   LLVMContext Context;
396 
397   // Load the bitcode...
398   SMDiagnostic Err;
399   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
400   Module *Mod = Owner.get();
401   if (!Mod)
402     reportError(Err, argv[0]);
403 
404   if (EnableCacheManager) {
405     std::string CacheName("file:");
406     CacheName.append(InputFile);
407     Mod->setModuleIdentifier(CacheName);
408   }
409 
410   // If not jitting lazily, load the whole bitcode file eagerly too.
411   if (NoLazyCompilation) {
412     // Use *argv instead of argv[0] to work around a wrong GCC warning.
413     ExitOnError ExitOnErr(std::string(*argv) +
414                           ": bitcode didn't read correctly: ");
415     ExitOnErr(Mod->materializeAll());
416   }
417 
418   std::string ErrorMsg;
419   EngineBuilder builder(std::move(Owner));
420   builder.setMArch(MArch);
421   builder.setMCPU(getCPUStr());
422   builder.setMAttrs(getFeatureList());
423   if (RelocModel.getNumOccurrences())
424     builder.setRelocationModel(RelocModel);
425   if (CMModel.getNumOccurrences())
426     builder.setCodeModel(CMModel);
427   builder.setErrorStr(&ErrorMsg);
428   builder.setEngineKind(ForceInterpreter
429                         ? EngineKind::Interpreter
430                         : EngineKind::JIT);
431   builder.setUseOrcMCJITReplacement(AcknowledgeORCv1Deprecation,
432                                     UseJITKind == JITKind::OrcMCJITReplacement);
433 
434   // If we are supposed to override the target triple, do so now.
435   if (!TargetTriple.empty())
436     Mod->setTargetTriple(Triple::normalize(TargetTriple));
437 
438   // Enable MCJIT if desired.
439   RTDyldMemoryManager *RTDyldMM = nullptr;
440   if (!ForceInterpreter) {
441     if (RemoteMCJIT)
442       RTDyldMM = new ForwardingMemoryManager();
443     else
444       RTDyldMM = new SectionMemoryManager();
445 
446     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
447     // RTDyldMM: We still use it below, even though we don't own it.
448     builder.setMCJITMemoryManager(
449       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
450   } else if (RemoteMCJIT) {
451     WithColor::error(errs(), argv[0])
452         << "remote process execution does not work with the interpreter.\n";
453     exit(1);
454   }
455 
456   builder.setOptLevel(getOptLevel());
457 
458   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
459   if (FloatABIForCalls != FloatABI::Default)
460     Options.FloatABIType = FloatABIForCalls;
461 
462   builder.setTargetOptions(Options);
463 
464   std::unique_ptr<ExecutionEngine> EE(builder.create());
465   if (!EE) {
466     if (!ErrorMsg.empty())
467       WithColor::error(errs(), argv[0])
468           << "error creating EE: " << ErrorMsg << "\n";
469     else
470       WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
471     exit(1);
472   }
473 
474   std::unique_ptr<LLIObjectCache> CacheManager;
475   if (EnableCacheManager) {
476     CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
477     EE->setObjectCache(CacheManager.get());
478   }
479 
480   // Load any additional modules specified on the command line.
481   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
482     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
483     if (!XMod)
484       reportError(Err, argv[0]);
485     if (EnableCacheManager) {
486       std::string CacheName("file:");
487       CacheName.append(ExtraModules[i]);
488       XMod->setModuleIdentifier(CacheName);
489     }
490     EE->addModule(std::move(XMod));
491   }
492 
493   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
494     Expected<object::OwningBinary<object::ObjectFile>> Obj =
495         object::ObjectFile::createObjectFile(ExtraObjects[i]);
496     if (!Obj) {
497       // TODO: Actually report errors helpfully.
498       consumeError(Obj.takeError());
499       reportError(Err, argv[0]);
500     }
501     object::OwningBinary<object::ObjectFile> &O = Obj.get();
502     EE->addObjectFile(std::move(O));
503   }
504 
505   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
506     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
507         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
508     if (!ArBufOrErr)
509       reportError(Err, argv[0]);
510     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
511 
512     Expected<std::unique_ptr<object::Archive>> ArOrErr =
513         object::Archive::create(ArBuf->getMemBufferRef());
514     if (!ArOrErr) {
515       std::string Buf;
516       raw_string_ostream OS(Buf);
517       logAllUnhandledErrors(ArOrErr.takeError(), OS);
518       OS.flush();
519       errs() << Buf;
520       exit(1);
521     }
522     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
523 
524     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
525 
526     EE->addArchive(std::move(OB));
527   }
528 
529   // If the target is Cygwin/MingW and we are generating remote code, we
530   // need an extra module to help out with linking.
531   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
532     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
533   }
534 
535   // The following functions have no effect if their respective profiling
536   // support wasn't enabled in the build configuration.
537   EE->RegisterJITEventListener(
538                 JITEventListener::createOProfileJITEventListener());
539   EE->RegisterJITEventListener(
540                 JITEventListener::createIntelJITEventListener());
541   if (!RemoteMCJIT)
542     EE->RegisterJITEventListener(
543                 JITEventListener::createPerfJITEventListener());
544 
545   if (!NoLazyCompilation && RemoteMCJIT) {
546     WithColor::warning(errs(), argv[0])
547         << "remote mcjit does not support lazy compilation\n";
548     NoLazyCompilation = true;
549   }
550   EE->DisableLazyCompilation(NoLazyCompilation);
551 
552   // If the user specifically requested an argv[0] to pass into the program,
553   // do it now.
554   if (!FakeArgv0.empty()) {
555     InputFile = static_cast<std::string>(FakeArgv0);
556   } else {
557     // Otherwise, if there is a .bc suffix on the executable strip it off, it
558     // might confuse the program.
559     if (StringRef(InputFile).endswith(".bc"))
560       InputFile.erase(InputFile.length() - 3);
561   }
562 
563   // Add the module's name to the start of the vector of arguments to main().
564   InputArgv.insert(InputArgv.begin(), InputFile);
565 
566   // Call the main function from M as if its signature were:
567   //   int main (int argc, char **argv, const char **envp)
568   // using the contents of Args to determine argc & argv, and the contents of
569   // EnvVars to determine envp.
570   //
571   Function *EntryFn = Mod->getFunction(EntryFunc);
572   if (!EntryFn) {
573     WithColor::error(errs(), argv[0])
574         << '\'' << EntryFunc << "\' function not found in module.\n";
575     return -1;
576   }
577 
578   // Reset errno to zero on entry to main.
579   errno = 0;
580 
581   int Result = -1;
582 
583   // Sanity check use of remote-jit: LLI currently only supports use of the
584   // remote JIT on Unix platforms.
585   if (RemoteMCJIT) {
586 #ifndef LLVM_ON_UNIX
587     WithColor::warning(errs(), argv[0])
588         << "host does not support external remote targets.\n";
589     WithColor::note() << "defaulting to local execution\n";
590     return -1;
591 #else
592     if (ChildExecPath.empty()) {
593       WithColor::error(errs(), argv[0])
594           << "-remote-mcjit requires -mcjit-remote-process.\n";
595       exit(1);
596     } else if (!sys::fs::can_execute(ChildExecPath)) {
597       WithColor::error(errs(), argv[0])
598           << "unable to find usable child executable: '" << ChildExecPath
599           << "'\n";
600       return -1;
601     }
602 #endif
603   }
604 
605   if (!RemoteMCJIT) {
606     // If the program doesn't explicitly call exit, we will need the Exit
607     // function later on to make an explicit call, so get the function now.
608     FunctionCallee Exit = Mod->getOrInsertFunction(
609         "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context));
610 
611     // Run static constructors.
612     if (!ForceInterpreter) {
613       // Give MCJIT a chance to apply relocations and set page permissions.
614       EE->finalizeObject();
615     }
616     EE->runStaticConstructorsDestructors(false);
617 
618     // Trigger compilation separately so code regions that need to be
619     // invalidated will be known.
620     (void)EE->getPointerToFunction(EntryFn);
621     // Clear instruction cache before code will be executed.
622     if (RTDyldMM)
623       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
624 
625     // Run main.
626     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
627 
628     // Run static destructors.
629     EE->runStaticConstructorsDestructors(true);
630 
631     // If the program didn't call exit explicitly, we should call it now.
632     // This ensures that any atexit handlers get called correctly.
633     if (Function *ExitF =
634             dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) {
635       if (ExitF->getFunctionType() == Exit.getFunctionType()) {
636         std::vector<GenericValue> Args;
637         GenericValue ResultGV;
638         ResultGV.IntVal = APInt(32, Result);
639         Args.push_back(ResultGV);
640         EE->runFunction(ExitF, Args);
641         WithColor::error(errs(), argv[0])
642             << "exit(" << Result << ") returned!\n";
643         abort();
644       }
645     }
646     WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n";
647     abort();
648   } else {
649     // else == "if (RemoteMCJIT)"
650 
651     // Remote target MCJIT doesn't (yet) support static constructors. No reason
652     // it couldn't. This is a limitation of the LLI implementation, not the
653     // MCJIT itself. FIXME.
654 
655     // Lanch the remote process and get a channel to it.
656     std::unique_ptr<FDRawChannel> C = launchRemote();
657     if (!C) {
658       WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
659       exit(1);
660     }
661 
662     // Create a remote target client running over the channel.
663     llvm::orc::ExecutionSession ES;
664     ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
665     typedef orc::remote::OrcRemoteTargetClient MyRemote;
666     auto R = ExitOnErr(MyRemote::Create(*C, ES));
667 
668     // Create a remote memory manager.
669     auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
670 
671     // Forward MCJIT's memory manager calls to the remote memory manager.
672     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
673       std::move(RemoteMM));
674 
675     // Forward MCJIT's symbol resolution calls to the remote.
676     static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
677         orc::createLambdaResolver(
678             AcknowledgeORCv1Deprecation,
679             [](const std::string &Name) { return nullptr; },
680             [&](const std::string &Name) {
681               if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
682                 return JITSymbol(Addr, JITSymbolFlags::Exported);
683               return JITSymbol(nullptr);
684             }));
685 
686     // Grab the target address of the JIT'd main function on the remote and call
687     // it.
688     // FIXME: argv and envp handling.
689     JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
690     EE->finalizeObject();
691     LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
692                       << format("%llx", Entry) << "\n");
693     Result = ExitOnErr(R->callIntVoid(Entry));
694 
695     // Like static constructors, the remote target MCJIT support doesn't handle
696     // this yet. It could. FIXME.
697 
698     // Delete the EE - we need to tear it down *before* we terminate the session
699     // with the remote, otherwise it'll crash when it tries to release resources
700     // on a remote that has already been disconnected.
701     EE.reset();
702 
703     // Signal the remote target that we're done JITing.
704     ExitOnErr(R->terminateSession());
705   }
706 
707   return Result;
708 }
709 
710 static std::function<void(Module &)> createDebugDumper() {
711   switch (OrcDumpKind) {
712   case DumpKind::NoDump:
713     return [](Module &M) {};
714 
715   case DumpKind::DumpFuncsToStdOut:
716     return [](Module &M) {
717       printf("[ ");
718 
719       for (const auto &F : M) {
720         if (F.isDeclaration())
721           continue;
722 
723         if (F.hasName()) {
724           std::string Name(std::string(F.getName()));
725           printf("%s ", Name.c_str());
726         } else
727           printf("<anon> ");
728       }
729 
730       printf("]\n");
731     };
732 
733   case DumpKind::DumpModsToStdOut:
734     return [](Module &M) {
735       outs() << "----- Module Start -----\n" << M << "----- Module End -----\n";
736     };
737 
738   case DumpKind::DumpModsToDisk:
739     return [](Module &M) {
740       std::error_code EC;
741       raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC, sys::fs::OF_Text);
742       if (EC) {
743         errs() << "Couldn't open " << M.getModuleIdentifier()
744                << " for dumping.\nError:" << EC.message() << "\n";
745         exit(1);
746       }
747       Out << M;
748     };
749   }
750   llvm_unreachable("Unknown DumpKind");
751 }
752 
753 Error loadDylibs() {
754   for (const auto &Dylib : Dylibs) {
755     std::string ErrMsg;
756     if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
757       return make_error<StringError>(ErrMsg, inconvertibleErrorCode());
758   }
759 
760   return Error::success();
761 }
762 
763 static void exitOnLazyCallThroughFailure() { exit(1); }
764 
765 int runOrcLazyJIT(const char *ProgName) {
766   // Start setting up the JIT environment.
767 
768   // Parse the main module.
769   orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
770   SMDiagnostic Err;
771   auto MainModule = parseIRFile(InputFile, Err, *TSCtx.getContext());
772   if (!MainModule)
773     reportError(Err, ProgName);
774 
775   const auto &TT = MainModule->getTargetTriple();
776   orc::LLLazyJITBuilder Builder;
777 
778   Builder.setJITTargetMachineBuilder(
779       TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
780                  : orc::JITTargetMachineBuilder(Triple(TT)));
781 
782   if (!MArch.empty())
783     Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName(MArch);
784 
785   Builder.getJITTargetMachineBuilder()
786       ->setCPU(getCPUStr())
787       .addFeatures(getFeatureList())
788       .setRelocationModel(RelocModel.getNumOccurrences()
789                               ? Optional<Reloc::Model>(RelocModel)
790                               : None)
791       .setCodeModel(CMModel.getNumOccurrences()
792                         ? Optional<CodeModel::Model>(CMModel)
793                         : None);
794 
795   Builder.setLazyCompileFailureAddr(
796       pointerToJITTargetAddress(exitOnLazyCallThroughFailure));
797   Builder.setNumCompileThreads(LazyJITCompileThreads);
798 
799   auto J = ExitOnErr(Builder.create());
800 
801   if (PerModuleLazy)
802     J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
803 
804   auto Dump = createDebugDumper();
805 
806   J->getIRTransformLayer().setTransform(
807       [&](orc::ThreadSafeModule TSM,
808           const orc::MaterializationResponsibility &R) {
809         TSM.withModuleDo([&](Module &M) {
810           if (verifyModule(M, &dbgs())) {
811             dbgs() << "Bad module: " << &M << "\n";
812             exit(1);
813           }
814           Dump(M);
815         });
816         return TSM;
817       });
818 
819   orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
820 
821   // Unless they've been explicitly disabled, make process symbols available to
822   // JIT'd code.
823   if (!NoProcessSymbols)
824     J->getMainJITDylib().addGenerator(
825         ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(
826             J->getDataLayout().getGlobalPrefix(),
827             [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) {
828               return Name != MainName;
829             })));
830 
831   orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
832   ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
833 
834   // Add the main module.
835   ExitOnErr(
836       J->addLazyIRModule(orc::ThreadSafeModule(std::move(MainModule), TSCtx)));
837 
838   // Create JITDylibs and add any extra modules.
839   {
840     // Create JITDylibs, keep a map from argument index to dylib. We will use
841     // -extra-module argument indexes to determine what dylib to use for each
842     // -extra-module.
843     std::map<unsigned, orc::JITDylib *> IdxToDylib;
844     IdxToDylib[0] = &J->getMainJITDylib();
845     for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
846          JDItr != JDEnd; ++JDItr) {
847       orc::JITDylib *JD = J->getJITDylibByName(*JDItr);
848       if (!JD)
849         JD = &J->createJITDylib(*JDItr);
850       IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD;
851     }
852 
853     for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end();
854          EMItr != EMEnd; ++EMItr) {
855       auto M = parseIRFile(*EMItr, Err, *TSCtx.getContext());
856       if (!M)
857         reportError(Err, ProgName);
858 
859       auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin());
860       assert(EMIdx != 0 && "ExtraModule should have index > 0");
861       auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx));
862       auto &JD = *JDItr->second;
863       ExitOnErr(
864           J->addLazyIRModule(JD, orc::ThreadSafeModule(std::move(M), TSCtx)));
865     }
866 
867     for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end();
868          EAItr != EAEnd; ++EAItr) {
869       auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin());
870       assert(EAIdx != 0 && "ExtraArchive should have index > 0");
871       auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx));
872       auto &JD = *JDItr->second;
873       JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load(
874           J->getObjLinkingLayer(), EAItr->c_str())));
875     }
876   }
877 
878   // Add the objects.
879   for (auto &ObjPath : ExtraObjects) {
880     auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath)));
881     ExitOnErr(J->addObjectFile(std::move(Obj)));
882   }
883 
884   // Run any static constructors.
885   ExitOnErr(J->runConstructors());
886 
887   // Run any -thread-entry points.
888   std::vector<std::thread> AltEntryThreads;
889   for (auto &ThreadEntryPoint : ThreadEntryPoints) {
890     auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint));
891     typedef void (*EntryPointPtr)();
892     auto EntryPoint =
893       reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress()));
894     AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); }));
895   }
896 
897   // Run main.
898   auto MainSym = ExitOnErr(J->lookup("main"));
899 
900   typedef int (*MainFnPtr)(int, char *[]);
901   auto Result = orc::runAsMain(
902       jitTargetAddressToFunction<MainFnPtr>(MainSym.getAddress()), InputArgv,
903       StringRef(InputFile));
904 
905   // Wait for -entry-point threads.
906   for (auto &AltEntryThread : AltEntryThreads)
907     AltEntryThread.join();
908 
909   // Run destructors.
910   ExitOnErr(J->runDestructors());
911   CXXRuntimeOverrides.runDestructors();
912 
913   return Result;
914 }
915 
916 void disallowOrcOptions() {
917   // Make sure nobody used an orc-lazy specific option accidentally.
918 
919   if (LazyJITCompileThreads != 0) {
920     errs() << "-compile-threads requires -jit-kind=orc-lazy\n";
921     exit(1);
922   }
923 
924   if (!ThreadEntryPoints.empty()) {
925     errs() << "-thread-entry requires -jit-kind=orc-lazy\n";
926     exit(1);
927   }
928 
929   if (PerModuleLazy) {
930     errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n";
931     exit(1);
932   }
933 }
934 
935 std::unique_ptr<FDRawChannel> launchRemote() {
936 #ifndef LLVM_ON_UNIX
937   llvm_unreachable("launchRemote not supported on non-Unix platforms");
938 #else
939   int PipeFD[2][2];
940   pid_t ChildPID;
941 
942   // Create two pipes.
943   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
944     perror("Error creating pipe: ");
945 
946   ChildPID = fork();
947 
948   if (ChildPID == 0) {
949     // In the child...
950 
951     // Close the parent ends of the pipes
952     close(PipeFD[0][1]);
953     close(PipeFD[1][0]);
954 
955 
956     // Execute the child process.
957     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
958     {
959       ChildPath.reset(new char[ChildExecPath.size() + 1]);
960       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
961       ChildPath[ChildExecPath.size()] = '\0';
962       std::string ChildInStr = utostr(PipeFD[0][0]);
963       ChildIn.reset(new char[ChildInStr.size() + 1]);
964       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
965       ChildIn[ChildInStr.size()] = '\0';
966       std::string ChildOutStr = utostr(PipeFD[1][1]);
967       ChildOut.reset(new char[ChildOutStr.size() + 1]);
968       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
969       ChildOut[ChildOutStr.size()] = '\0';
970     }
971 
972     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
973     int rc = execv(ChildExecPath.c_str(), args);
974     if (rc != 0)
975       perror("Error executing child process: ");
976     llvm_unreachable("Error executing child process");
977   }
978   // else we're the parent...
979 
980   // Close the child ends of the pipes
981   close(PipeFD[0][0]);
982   close(PipeFD[1][1]);
983 
984   // Return an RPC channel connected to our end of the pipes.
985   return std::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
986 #endif
987 }
988