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