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