xref: /llvm-project-15.0.7/llvm/tools/lli/lli.cpp (revision 3ddd210a)
1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility provides a simple wrapper around the LLVM Execution Engines,
11 // which allow the direct execution of LLVM programs through a Just-In-Time
12 // compiler, or through an interpreter if no JIT is available for this platform.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "RemoteJITUtils.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Bitcode/BitcodeReader.h"
20 #include "llvm/CodeGen/CommandFlags.inc"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/ExecutionEngine/Interpreter.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/ExecutionEngine/MCJIT.h"
27 #include "llvm/ExecutionEngine/ObjectCache.h"
28 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
29 #include "llvm/ExecutionEngine/Orc/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/TypeBuilder.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("jit-kind",
87                               cl::desc("Choose underlying JIT kind."),
88                               cl::init(JITKind::MCJIT),
89                               cl::values(
90                                 clEnumValN(JITKind::MCJIT, "mcjit",
91                                            "MCJIT"),
92                                 clEnumValN(JITKind::OrcMCJITReplacement,
93                                            "orc-mcjit",
94                                            "Orc-based MCJIT replacement"),
95                                 clEnumValN(JITKind::OrcLazy,
96                                            "orc-lazy",
97                                            "Orc-based lazy JIT.")));
98 
99   // The MCJIT supports building for a target address space separate from
100   // the JIT compilation process. Use a forked process and a copying
101   // memory manager with IPC to execute using this functionality.
102   cl::opt<bool> RemoteMCJIT("remote-mcjit",
103     cl::desc("Execute MCJIT'ed code in a separate process."),
104     cl::init(false));
105 
106   // Manually specify the child process for remote execution. This overrides
107   // the simulated remote execution that allocates address space for child
108   // execution. The child process will be executed and will communicate with
109   // lli via stdin/stdout pipes.
110   cl::opt<std::string>
111   ChildExecPath("mcjit-remote-process",
112                 cl::desc("Specify the filename of the process to launch "
113                          "for remote MCJIT execution.  If none is specified,"
114                          "\n\tremote execution will be simulated in-process."),
115                 cl::value_desc("filename"), cl::init(""));
116 
117   // Determine optimization level.
118   cl::opt<char>
119   OptLevel("O",
120            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
121                     "(default = '-O2')"),
122            cl::Prefix,
123            cl::ZeroOrMore,
124            cl::init(' '));
125 
126   cl::opt<std::string>
127   TargetTriple("mtriple", cl::desc("Override target triple for module"));
128 
129   cl::opt<std::string>
130   EntryFunc("entry-function",
131             cl::desc("Specify the entry function (default = 'main') "
132                      "of the executable"),
133             cl::value_desc("function"),
134             cl::init("main"));
135 
136   cl::list<std::string>
137   ExtraModules("extra-module",
138          cl::desc("Extra modules to be loaded"),
139          cl::value_desc("input bitcode"));
140 
141   cl::list<std::string>
142   ExtraObjects("extra-object",
143          cl::desc("Extra object files to be loaded"),
144          cl::value_desc("input object"));
145 
146   cl::list<std::string>
147   ExtraArchives("extra-archive",
148          cl::desc("Extra archive files to be loaded"),
149          cl::value_desc("input archive"));
150 
151   cl::opt<bool>
152   EnableCacheManager("enable-cache-manager",
153         cl::desc("Use cache manager to save/load mdoules"),
154         cl::init(false));
155 
156   cl::opt<std::string>
157   ObjectCacheDir("object-cache-dir",
158                   cl::desc("Directory to store cached object files "
159                            "(must be user writable)"),
160                   cl::init(""));
161 
162   cl::opt<std::string>
163   FakeArgv0("fake-argv0",
164             cl::desc("Override the 'argv[0]' value passed into the executing"
165                      " program"), cl::value_desc("executable"));
166 
167   cl::opt<bool>
168   DisableCoreFiles("disable-core-files", cl::Hidden,
169                    cl::desc("Disable emission of core files if possible"));
170 
171   cl::opt<bool>
172   NoLazyCompilation("disable-lazy-compilation",
173                   cl::desc("Disable JIT lazy compilation"),
174                   cl::init(false));
175 
176   cl::opt<bool>
177   GenerateSoftFloatCalls("soft-float",
178     cl::desc("Generate software floating point library calls"),
179     cl::init(false));
180 
181   enum class DumpKind {
182     NoDump,
183     DumpFuncsToStdOut,
184     DumpModsToStdOut,
185     DumpModsToDisk
186   };
187 
188   cl::opt<DumpKind> OrcDumpKind(
189       "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."),
190       cl::init(DumpKind::NoDump),
191       cl::values(clEnumValN(DumpKind::NoDump, "no-dump",
192                             "Don't dump anything."),
193                  clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout",
194                             "Dump function names to stdout."),
195                  clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout",
196                             "Dump modules to stdout."),
197                  clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk",
198                             "Dump modules to the current "
199                             "working directory. (WARNING: "
200                             "will overwrite existing files).")),
201       cl::Hidden);
202 
203   ExitOnError ExitOnErr;
204 }
205 
206 //===----------------------------------------------------------------------===//
207 // Object cache
208 //
209 // This object cache implementation writes cached objects to disk to the
210 // directory specified by CacheDir, using a filename provided in the module
211 // descriptor. The cache tries to load a saved object using that path if the
212 // file exists. CacheDir defaults to "", in which case objects are cached
213 // alongside their originating bitcodes.
214 //
215 class LLIObjectCache : public ObjectCache {
216 public:
217   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
218     // Add trailing '/' to cache dir if necessary.
219     if (!this->CacheDir.empty() &&
220         this->CacheDir[this->CacheDir.size() - 1] != '/')
221       this->CacheDir += '/';
222   }
223   ~LLIObjectCache() override {}
224 
225   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
226     const std::string &ModuleID = M->getModuleIdentifier();
227     std::string CacheName;
228     if (!getCacheFilename(ModuleID, CacheName))
229       return;
230     if (!CacheDir.empty()) { // Create user-defined cache dir.
231       SmallString<128> dir(sys::path::parent_path(CacheName));
232       sys::fs::create_directories(Twine(dir));
233     }
234     std::error_code EC;
235     raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
236     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
237     outfile.close();
238   }
239 
240   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
241     const std::string &ModuleID = M->getModuleIdentifier();
242     std::string CacheName;
243     if (!getCacheFilename(ModuleID, CacheName))
244       return nullptr;
245     // Load the object from the cache filename
246     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
247         MemoryBuffer::getFile(CacheName, -1, false);
248     // If the file isn't there, that's OK.
249     if (!IRObjectBuffer)
250       return nullptr;
251     // MCJIT will want to write into this buffer, and we don't want that
252     // because the file has probably just been mmapped.  Instead we make
253     // a copy.  The filed-based buffer will be released when it goes
254     // out of scope.
255     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
256   }
257 
258 private:
259   std::string CacheDir;
260 
261   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
262     std::string Prefix("file:");
263     size_t PrefixLength = Prefix.length();
264     if (ModID.substr(0, PrefixLength) != Prefix)
265       return false;
266         std::string CacheSubdir = ModID.substr(PrefixLength);
267 #if defined(_WIN32)
268         // Transform "X:\foo" => "/X\foo" for convenience.
269         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
270           CacheSubdir[1] = CacheSubdir[0];
271           CacheSubdir[0] = '/';
272         }
273 #endif
274     CacheName = CacheDir + CacheSubdir;
275     size_t pos = CacheName.rfind('.');
276     CacheName.replace(pos, CacheName.length() - pos, ".o");
277     return true;
278   }
279 };
280 
281 // On Mingw and Cygwin, an external symbol named '__main' is called from the
282 // generated 'main' function to allow static initialization.  To avoid linking
283 // problems with remote targets (because lli's remote target support does not
284 // currently handle external linking) we add a secondary module which defines
285 // an empty '__main' function.
286 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
287                                   StringRef TargetTripleStr) {
288   IRBuilder<> Builder(Context);
289   Triple TargetTriple(TargetTripleStr);
290 
291   // Create a new module.
292   std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
293   M->setTargetTriple(TargetTripleStr);
294 
295   // Create an empty function named "__main".
296   Function *Result;
297   if (TargetTriple.isArch64Bit()) {
298     Result = Function::Create(
299       TypeBuilder<int64_t(void), false>::get(Context),
300       GlobalValue::ExternalLinkage, "__main", M.get());
301   } else {
302     Result = Function::Create(
303       TypeBuilder<int32_t(void), false>::get(Context),
304       GlobalValue::ExternalLinkage, "__main", M.get());
305   }
306   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
307   Builder.SetInsertPoint(BB);
308   Value *ReturnVal;
309   if (TargetTriple.isArch64Bit())
310     ReturnVal = ConstantInt::get(Context, APInt(64, 0));
311   else
312     ReturnVal = ConstantInt::get(Context, APInt(32, 0));
313   Builder.CreateRet(ReturnVal);
314 
315   // Add this new module to the ExecutionEngine.
316   EE.addModule(std::move(M));
317 }
318 
319 CodeGenOpt::Level getOptLevel() {
320   switch (OptLevel) {
321   default:
322     WithColor::error(errs(), "lli") << "invalid optimization level.\n";
323     exit(1);
324   case '0': return CodeGenOpt::None;
325   case '1': return CodeGenOpt::Less;
326   case ' ':
327   case '2': return CodeGenOpt::Default;
328   case '3': return CodeGenOpt::Aggressive;
329   }
330   llvm_unreachable("Unrecognized opt level.");
331 }
332 
333 LLVM_ATTRIBUTE_NORETURN
334 static void reportError(SMDiagnostic Err, const char *ProgName) {
335   Err.print(ProgName, errs());
336   exit(1);
337 }
338 
339 int runOrcLazyJIT(LLVMContext &Ctx, std::vector<std::unique_ptr<Module>> Ms,
340                   const std::vector<std::string> &Args);
341 
342 //===----------------------------------------------------------------------===//
343 // main Driver function
344 //
345 int main(int argc, char **argv, char * const *envp) {
346   InitLLVM X(argc, argv);
347 
348   if (argc > 1)
349     ExitOnErr.setBanner(std::string(argv[0]) + ": ");
350 
351   // If we have a native target, initialize it to ensure it is linked in and
352   // usable by the JIT.
353   InitializeNativeTarget();
354   InitializeNativeTargetAsmPrinter();
355   InitializeNativeTargetAsmParser();
356 
357   cl::ParseCommandLineOptions(argc, argv,
358                               "llvm interpreter & dynamic compiler\n");
359 
360   // If the user doesn't want core files, disable them.
361   if (DisableCoreFiles)
362     sys::Process::PreventCoreFiles();
363 
364   LLVMContext Context;
365 
366   // Load the bitcode...
367   SMDiagnostic Err;
368   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
369   Module *Mod = Owner.get();
370   if (!Mod)
371     reportError(Err, argv[0]);
372 
373   if (UseJITKind == JITKind::OrcLazy) {
374     std::vector<std::unique_ptr<Module>> Ms;
375     Ms.push_back(std::move(Owner));
376     for (auto &ExtraMod : ExtraModules) {
377       Ms.push_back(parseIRFile(ExtraMod, Err, Context));
378       if (!Ms.back())
379         reportError(Err, argv[0]);
380     }
381     std::vector<std::string> Args;
382     Args.push_back(InputFile);
383     for (auto &Arg : InputArgv)
384       Args.push_back(Arg);
385     return runOrcLazyJIT(Context, std::move(Ms), Args);
386   }
387 
388   if (EnableCacheManager) {
389     std::string CacheName("file:");
390     CacheName.append(InputFile);
391     Mod->setModuleIdentifier(CacheName);
392   }
393 
394   // If not jitting lazily, load the whole bitcode file eagerly too.
395   if (NoLazyCompilation) {
396     // Use *argv instead of argv[0] to work around a wrong GCC warning.
397     ExitOnError ExitOnErr(std::string(*argv) +
398                           ": bitcode didn't read correctly: ");
399     ExitOnErr(Mod->materializeAll());
400   }
401 
402   std::string ErrorMsg;
403   EngineBuilder builder(std::move(Owner));
404   builder.setMArch(MArch);
405   builder.setMCPU(getCPUStr());
406   builder.setMAttrs(getFeatureList());
407   if (RelocModel.getNumOccurrences())
408     builder.setRelocationModel(RelocModel);
409   if (CMModel.getNumOccurrences())
410     builder.setCodeModel(CMModel);
411   builder.setErrorStr(&ErrorMsg);
412   builder.setEngineKind(ForceInterpreter
413                         ? EngineKind::Interpreter
414                         : EngineKind::JIT);
415   builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
416 
417   // If we are supposed to override the target triple, do so now.
418   if (!TargetTriple.empty())
419     Mod->setTargetTriple(Triple::normalize(TargetTriple));
420 
421   // Enable MCJIT if desired.
422   RTDyldMemoryManager *RTDyldMM = nullptr;
423   if (!ForceInterpreter) {
424     if (RemoteMCJIT)
425       RTDyldMM = new ForwardingMemoryManager();
426     else
427       RTDyldMM = new SectionMemoryManager();
428 
429     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
430     // RTDyldMM: We still use it below, even though we don't own it.
431     builder.setMCJITMemoryManager(
432       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
433   } else if (RemoteMCJIT) {
434     WithColor::error(errs(), argv[0])
435         << "remote process execution does not work with the interpreter.\n";
436     exit(1);
437   }
438 
439   builder.setOptLevel(getOptLevel());
440 
441   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
442   if (FloatABIForCalls != FloatABI::Default)
443     Options.FloatABIType = FloatABIForCalls;
444 
445   builder.setTargetOptions(Options);
446 
447   std::unique_ptr<ExecutionEngine> EE(builder.create());
448   if (!EE) {
449     if (!ErrorMsg.empty())
450       WithColor::error(errs(), argv[0])
451           << "error creating EE: " << ErrorMsg << "\n";
452     else
453       WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n";
454     exit(1);
455   }
456 
457   std::unique_ptr<LLIObjectCache> CacheManager;
458   if (EnableCacheManager) {
459     CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
460     EE->setObjectCache(CacheManager.get());
461   }
462 
463   // Load any additional modules specified on the command line.
464   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
465     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
466     if (!XMod)
467       reportError(Err, argv[0]);
468     if (EnableCacheManager) {
469       std::string CacheName("file:");
470       CacheName.append(ExtraModules[i]);
471       XMod->setModuleIdentifier(CacheName);
472     }
473     EE->addModule(std::move(XMod));
474   }
475 
476   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
477     Expected<object::OwningBinary<object::ObjectFile>> Obj =
478         object::ObjectFile::createObjectFile(ExtraObjects[i]);
479     if (!Obj) {
480       // TODO: Actually report errors helpfully.
481       consumeError(Obj.takeError());
482       reportError(Err, argv[0]);
483     }
484     object::OwningBinary<object::ObjectFile> &O = Obj.get();
485     EE->addObjectFile(std::move(O));
486   }
487 
488   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
489     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
490         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
491     if (!ArBufOrErr)
492       reportError(Err, argv[0]);
493     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
494 
495     Expected<std::unique_ptr<object::Archive>> ArOrErr =
496         object::Archive::create(ArBuf->getMemBufferRef());
497     if (!ArOrErr) {
498       std::string Buf;
499       raw_string_ostream OS(Buf);
500       logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
501       OS.flush();
502       errs() << Buf;
503       exit(1);
504     }
505     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
506 
507     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
508 
509     EE->addArchive(std::move(OB));
510   }
511 
512   // If the target is Cygwin/MingW and we are generating remote code, we
513   // need an extra module to help out with linking.
514   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
515     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
516   }
517 
518   // The following functions have no effect if their respective profiling
519   // support wasn't enabled in the build configuration.
520   EE->RegisterJITEventListener(
521                 JITEventListener::createOProfileJITEventListener());
522   EE->RegisterJITEventListener(
523                 JITEventListener::createIntelJITEventListener());
524 
525   if (!NoLazyCompilation && RemoteMCJIT) {
526     WithColor::warning(errs(), argv[0])
527         << "remote mcjit does not support lazy compilation\n";
528     NoLazyCompilation = true;
529   }
530   EE->DisableLazyCompilation(NoLazyCompilation);
531 
532   // If the user specifically requested an argv[0] to pass into the program,
533   // do it now.
534   if (!FakeArgv0.empty()) {
535     InputFile = static_cast<std::string>(FakeArgv0);
536   } else {
537     // Otherwise, if there is a .bc suffix on the executable strip it off, it
538     // might confuse the program.
539     if (StringRef(InputFile).endswith(".bc"))
540       InputFile.erase(InputFile.length() - 3);
541   }
542 
543   // Add the module's name to the start of the vector of arguments to main().
544   InputArgv.insert(InputArgv.begin(), InputFile);
545 
546   // Call the main function from M as if its signature were:
547   //   int main (int argc, char **argv, const char **envp)
548   // using the contents of Args to determine argc & argv, and the contents of
549   // EnvVars to determine envp.
550   //
551   Function *EntryFn = Mod->getFunction(EntryFunc);
552   if (!EntryFn) {
553     WithColor::error(errs(), argv[0])
554         << '\'' << EntryFunc << "\' function not found in module.\n";
555     return -1;
556   }
557 
558   // Reset errno to zero on entry to main.
559   errno = 0;
560 
561   int Result = -1;
562 
563   // Sanity check use of remote-jit: LLI currently only supports use of the
564   // remote JIT on Unix platforms.
565   if (RemoteMCJIT) {
566 #ifndef LLVM_ON_UNIX
567     WithColor::warning(errs(), argv[0])
568         << "host does not support external remote targets.\n";
569     WithColor::note() << "defaulting to local execution\n";
570     return -1;
571 #else
572     if (ChildExecPath.empty()) {
573       WithColor::error(errs(), argv[0])
574           << "-remote-mcjit requires -mcjit-remote-process.\n";
575       exit(1);
576     } else if (!sys::fs::can_execute(ChildExecPath)) {
577       WithColor::error(errs(), argv[0])
578           << "unable to find usable child executable: '" << ChildExecPath
579           << "'\n";
580       return -1;
581     }
582 #endif
583   }
584 
585   if (!RemoteMCJIT) {
586     // If the program doesn't explicitly call exit, we will need the Exit
587     // function later on to make an explicit call, so get the function now.
588     Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
589                                                       Type::getInt32Ty(Context));
590 
591     // Run static constructors.
592     if (!ForceInterpreter) {
593       // Give MCJIT a chance to apply relocations and set page permissions.
594       EE->finalizeObject();
595     }
596     EE->runStaticConstructorsDestructors(false);
597 
598     // Trigger compilation separately so code regions that need to be
599     // invalidated will be known.
600     (void)EE->getPointerToFunction(EntryFn);
601     // Clear instruction cache before code will be executed.
602     if (RTDyldMM)
603       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
604 
605     // Run main.
606     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
607 
608     // Run static destructors.
609     EE->runStaticConstructorsDestructors(true);
610 
611     // If the program didn't call exit explicitly, we should call it now.
612     // This ensures that any atexit handlers get called correctly.
613     if (Function *ExitF = dyn_cast<Function>(Exit)) {
614       std::vector<GenericValue> Args;
615       GenericValue ResultGV;
616       ResultGV.IntVal = APInt(32, Result);
617       Args.push_back(ResultGV);
618       EE->runFunction(ExitF, Args);
619       WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n";
620       abort();
621     } else {
622       WithColor::error(errs(), argv[0])
623           << "exit defined with wrong prototype!\n";
624       abort();
625     }
626   } else {
627     // else == "if (RemoteMCJIT)"
628 
629     // Remote target MCJIT doesn't (yet) support static constructors. No reason
630     // it couldn't. This is a limitation of the LLI implementation, not the
631     // MCJIT itself. FIXME.
632 
633     // Lanch the remote process and get a channel to it.
634     std::unique_ptr<FDRawChannel> C = launchRemote();
635     if (!C) {
636       WithColor::error(errs(), argv[0]) << "failed to launch remote JIT.\n";
637       exit(1);
638     }
639 
640     // Create a remote target client running over the channel.
641     llvm::orc::ExecutionSession ES;
642     ES.setErrorReporter([&](Error Err) { ExitOnErr(std::move(Err)); });
643     typedef orc::remote::OrcRemoteTargetClient MyRemote;
644     auto R = ExitOnErr(MyRemote::Create(*C, ES));
645 
646     // Create a remote memory manager.
647     auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
648 
649     // Forward MCJIT's memory manager calls to the remote memory manager.
650     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
651       std::move(RemoteMM));
652 
653     // Forward MCJIT's symbol resolution calls to the remote.
654     static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
655         orc::createLambdaResolver(
656             [](const std::string &Name) { return nullptr; },
657             [&](const std::string &Name) {
658               if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
659                 return JITSymbol(Addr, JITSymbolFlags::Exported);
660               return JITSymbol(nullptr);
661             }));
662 
663     // Grab the target address of the JIT'd main function on the remote and call
664     // it.
665     // FIXME: argv and envp handling.
666     JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
667     EE->finalizeObject();
668     LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
669                       << format("%llx", Entry) << "\n");
670     Result = ExitOnErr(R->callIntVoid(Entry));
671 
672     // Like static constructors, the remote target MCJIT support doesn't handle
673     // this yet. It could. FIXME.
674 
675     // Delete the EE - we need to tear it down *before* we terminate the session
676     // with the remote, otherwise it'll crash when it tries to release resources
677     // on a remote that has already been disconnected.
678     EE.reset();
679 
680     // Signal the remote target that we're done JITing.
681     ExitOnErr(R->terminateSession());
682   }
683 
684   return Result;
685 }
686 
687 static orc::IRTransformLayer2::TransformFunction createDebugDumper() {
688   switch (OrcDumpKind) {
689   case DumpKind::NoDump:
690     return [](std::unique_ptr<Module> M) { return M; };
691 
692   case DumpKind::DumpFuncsToStdOut:
693     return [](std::unique_ptr<Module> M) {
694       printf("[ ");
695 
696       for (const auto &F : *M) {
697         if (F.isDeclaration())
698           continue;
699 
700         if (F.hasName()) {
701           std::string Name(F.getName());
702           printf("%s ", Name.c_str());
703         } else
704           printf("<anon> ");
705       }
706 
707       printf("]\n");
708       return M;
709     };
710 
711   case DumpKind::DumpModsToStdOut:
712     return [](std::unique_ptr<Module> M) {
713       outs() << "----- Module Start -----\n"
714              << *M << "----- Module End -----\n";
715 
716       return M;
717     };
718 
719   case DumpKind::DumpModsToDisk:
720     return [](std::unique_ptr<Module> M) {
721       std::error_code EC;
722       raw_fd_ostream Out(M->getModuleIdentifier() + ".ll", EC, sys::fs::F_Text);
723       if (EC) {
724         errs() << "Couldn't open " << M->getModuleIdentifier()
725                << " for dumping.\nError:" << EC.message() << "\n";
726         exit(1);
727       }
728       Out << *M;
729       return M;
730     };
731   }
732   llvm_unreachable("Unknown DumpKind");
733 }
734 
735 int runOrcLazyJIT(LLVMContext &Ctx, std::vector<std::unique_ptr<Module>> Ms,
736                   const std::vector<std::string> &Args) {
737   // Bail out early if no modules loaded.
738   if (Ms.empty())
739     return 0;
740 
741   // Add lli's symbols into the JIT's search space.
742   std::string ErrMsg;
743   sys::DynamicLibrary LibLLI =
744       sys::DynamicLibrary::getPermanentLibrary(nullptr, &ErrMsg);
745   if (!LibLLI.isValid()) {
746     errs() << "Error loading lli symbols: " << ErrMsg << ".\n";
747     return 1;
748   }
749 
750   const auto &TT = Ms.front()->getTargetTriple();
751   orc::JITTargetMachineBuilder TMD =
752       TT.empty() ? ExitOnErr(orc::JITTargetMachineBuilder::detectHost())
753                  : orc::JITTargetMachineBuilder(Triple(TT));
754 
755   TMD.setArch(MArch)
756       .setCPU(getCPUStr())
757       .addFeatures(getFeatureList())
758       .setRelocationModel(RelocModel.getNumOccurrences()
759                               ? Optional<Reloc::Model>(RelocModel)
760                               : None)
761       .setCodeModel(CMModel.getNumOccurrences()
762                         ? Optional<CodeModel::Model>(CMModel)
763                         : None);
764   auto TM = ExitOnErr(TMD.createTargetMachine());
765   auto DL = TM->createDataLayout();
766   auto ES = llvm::make_unique<orc::ExecutionSession>();
767   auto J =
768       ExitOnErr(orc::LLLazyJIT::Create(std::move(ES), std::move(TM), DL, Ctx));
769 
770   J->setLazyCompileTransform(createDebugDumper());
771   J->getMainVSO().setFallbackDefinitionGenerator(
772       orc::DynamicLibraryFallbackGenerator(
773           std::move(LibLLI), DL, [](orc::SymbolStringPtr) { return true; }));
774 
775   orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
776   orc::LocalCXXRuntimeOverrides2 CXXRuntimeOverrides;
777   ExitOnErr(CXXRuntimeOverrides.enable(J->getMainVSO(), Mangle));
778 
779   for (auto &M : Ms)
780     ExitOnErr(J->addLazyIRModule(std::move(M)));
781 
782   ExitOnErr(J->runConstructors());
783 
784   auto MainSym = ExitOnErr(J->lookup("main"));
785   typedef int (*MainFnPtr)(int, const char *[]);
786   std::vector<const char *> ArgV;
787   for (auto &Arg : Args)
788     ArgV.push_back(Arg.c_str());
789   auto Main =
790       reinterpret_cast<MainFnPtr>(static_cast<uintptr_t>(MainSym.getAddress()));
791   auto Result = Main(ArgV.size(), (const char **)ArgV.data());
792 
793   ExitOnErr(J->runDestructors());
794 
795   CXXRuntimeOverrides.runDestructors();
796 
797   return Result;
798 }
799 
800 std::unique_ptr<FDRawChannel> launchRemote() {
801 #ifndef LLVM_ON_UNIX
802   llvm_unreachable("launchRemote not supported on non-Unix platforms");
803 #else
804   int PipeFD[2][2];
805   pid_t ChildPID;
806 
807   // Create two pipes.
808   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
809     perror("Error creating pipe: ");
810 
811   ChildPID = fork();
812 
813   if (ChildPID == 0) {
814     // In the child...
815 
816     // Close the parent ends of the pipes
817     close(PipeFD[0][1]);
818     close(PipeFD[1][0]);
819 
820 
821     // Execute the child process.
822     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
823     {
824       ChildPath.reset(new char[ChildExecPath.size() + 1]);
825       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
826       ChildPath[ChildExecPath.size()] = '\0';
827       std::string ChildInStr = utostr(PipeFD[0][0]);
828       ChildIn.reset(new char[ChildInStr.size() + 1]);
829       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
830       ChildIn[ChildInStr.size()] = '\0';
831       std::string ChildOutStr = utostr(PipeFD[1][1]);
832       ChildOut.reset(new char[ChildOutStr.size() + 1]);
833       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
834       ChildOut[ChildOutStr.size()] = '\0';
835     }
836 
837     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
838     int rc = execv(ChildExecPath.c_str(), args);
839     if (rc != 0)
840       perror("Error executing child process: ");
841     llvm_unreachable("Error executing child process");
842   }
843   // else we're the parent...
844 
845   // Close the child ends of the pipes
846   close(PipeFD[0][0]);
847   close(PipeFD[1][1]);
848 
849   // Return an RPC channel connected to our end of the pipes.
850   return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
851 #endif
852 }
853