67e7cbd7686abfb5dc527098dedf853e8ad4b796
[oota-llvm.git] / tools / lli / lli.cpp
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 "OrcLazyJIT.h"
17 #include "RemoteJITUtils.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.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/OrcMCJITReplacement.h"
28 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
29 #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/TypeBuilder.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/Object/Archive.h"
36 #include "llvm/Object/ObjectFile.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/DynamicLibrary.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Memory.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/Program.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Transforms/Instrumentation.h"
55 #include <cerrno>
56
57 #ifdef __CYGWIN__
58 #include <cygwin/version.h>
59 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
60 #define DO_NOTHING_ATEXIT 1
61 #endif
62 #endif
63
64 using namespace llvm;
65
66 #define DEBUG_TYPE "lli"
67
68 namespace {
69
70   enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
71
72   cl::opt<std::string>
73   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
74
75   cl::list<std::string>
76   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
77
78   cl::opt<bool> ForceInterpreter("force-interpreter",
79                                  cl::desc("Force interpretation: disable JIT"),
80                                  cl::init(false));
81
82   cl::opt<JITKind> UseJITKind("jit-kind",
83                               cl::desc("Choose underlying JIT kind."),
84                               cl::init(JITKind::MCJIT),
85                               cl::values(
86                                 clEnumValN(JITKind::MCJIT, "mcjit",
87                                            "MCJIT"),
88                                 clEnumValN(JITKind::OrcMCJITReplacement,
89                                            "orc-mcjit",
90                                            "Orc-based MCJIT replacement"),
91                                 clEnumValN(JITKind::OrcLazy,
92                                            "orc-lazy",
93                                            "Orc-based lazy JIT."),
94                                 clEnumValEnd));
95
96   // The MCJIT supports building for a target address space separate from
97   // the JIT compilation process. Use a forked process and a copying
98   // memory manager with IPC to execute using this functionality.
99   cl::opt<bool> RemoteMCJIT("remote-mcjit",
100     cl::desc("Execute MCJIT'ed code in a separate process."),
101     cl::init(false));
102
103   // Manually specify the child process for remote execution. This overrides
104   // the simulated remote execution that allocates address space for child
105   // execution. The child process will be executed and will communicate with
106   // lli via stdin/stdout pipes.
107   cl::opt<std::string>
108   ChildExecPath("mcjit-remote-process",
109                 cl::desc("Specify the filename of the process to launch "
110                          "for remote MCJIT execution.  If none is specified,"
111                          "\n\tremote execution will be simulated in-process."),
112                 cl::value_desc("filename"), cl::init(""));
113
114   // Determine optimization level.
115   cl::opt<char>
116   OptLevel("O",
117            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
118                     "(default = '-O2')"),
119            cl::Prefix,
120            cl::ZeroOrMore,
121            cl::init(' '));
122
123   cl::opt<std::string>
124   TargetTriple("mtriple", cl::desc("Override target triple for module"));
125
126   cl::opt<std::string>
127   MArch("march",
128         cl::desc("Architecture to generate assembly for (see --version)"));
129
130   cl::opt<std::string>
131   MCPU("mcpu",
132        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
133        cl::value_desc("cpu-name"),
134        cl::init(""));
135
136   cl::list<std::string>
137   MAttrs("mattr",
138          cl::CommaSeparated,
139          cl::desc("Target specific attributes (-mattr=help for details)"),
140          cl::value_desc("a1,+a2,-a3,..."));
141
142   cl::opt<std::string>
143   EntryFunc("entry-function",
144             cl::desc("Specify the entry function (default = 'main') "
145                      "of the executable"),
146             cl::value_desc("function"),
147             cl::init("main"));
148
149   cl::list<std::string>
150   ExtraModules("extra-module",
151          cl::desc("Extra modules to be loaded"),
152          cl::value_desc("input bitcode"));
153
154   cl::list<std::string>
155   ExtraObjects("extra-object",
156          cl::desc("Extra object files to be loaded"),
157          cl::value_desc("input object"));
158
159   cl::list<std::string>
160   ExtraArchives("extra-archive",
161          cl::desc("Extra archive files to be loaded"),
162          cl::value_desc("input archive"));
163
164   cl::opt<bool>
165   EnableCacheManager("enable-cache-manager",
166         cl::desc("Use cache manager to save/load mdoules"),
167         cl::init(false));
168
169   cl::opt<std::string>
170   ObjectCacheDir("object-cache-dir",
171                   cl::desc("Directory to store cached object files "
172                            "(must be user writable)"),
173                   cl::init(""));
174
175   cl::opt<std::string>
176   FakeArgv0("fake-argv0",
177             cl::desc("Override the 'argv[0]' value passed into the executing"
178                      " program"), cl::value_desc("executable"));
179
180   cl::opt<bool>
181   DisableCoreFiles("disable-core-files", cl::Hidden,
182                    cl::desc("Disable emission of core files if possible"));
183
184   cl::opt<bool>
185   NoLazyCompilation("disable-lazy-compilation",
186                   cl::desc("Disable JIT lazy compilation"),
187                   cl::init(false));
188
189   cl::opt<Reloc::Model>
190   RelocModel("relocation-model",
191              cl::desc("Choose relocation model"),
192              cl::init(Reloc::Default),
193              cl::values(
194             clEnumValN(Reloc::Default, "default",
195                        "Target default relocation model"),
196             clEnumValN(Reloc::Static, "static",
197                        "Non-relocatable code"),
198             clEnumValN(Reloc::PIC_, "pic",
199                        "Fully relocatable, position independent code"),
200             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
201                        "Relocatable external references, non-relocatable code"),
202             clEnumValEnd));
203
204   cl::opt<llvm::CodeModel::Model>
205   CMModel("code-model",
206           cl::desc("Choose code model"),
207           cl::init(CodeModel::JITDefault),
208           cl::values(clEnumValN(CodeModel::JITDefault, "default",
209                                 "Target default JIT code model"),
210                      clEnumValN(CodeModel::Small, "small",
211                                 "Small code model"),
212                      clEnumValN(CodeModel::Kernel, "kernel",
213                                 "Kernel code model"),
214                      clEnumValN(CodeModel::Medium, "medium",
215                                 "Medium code model"),
216                      clEnumValN(CodeModel::Large, "large",
217                                 "Large code model"),
218                      clEnumValEnd));
219
220   cl::opt<bool>
221   GenerateSoftFloatCalls("soft-float",
222     cl::desc("Generate software floating point library calls"),
223     cl::init(false));
224
225   cl::opt<llvm::FloatABI::ABIType>
226   FloatABIForCalls("float-abi",
227                    cl::desc("Choose float ABI type"),
228                    cl::init(FloatABI::Default),
229                    cl::values(
230                      clEnumValN(FloatABI::Default, "default",
231                                 "Target default float ABI type"),
232                      clEnumValN(FloatABI::Soft, "soft",
233                                 "Soft float ABI (implied by -soft-float)"),
234                      clEnumValN(FloatABI::Hard, "hard",
235                                 "Hard float ABI (uses FP registers)"),
236                      clEnumValEnd));
237 }
238
239 //===----------------------------------------------------------------------===//
240 // Object cache
241 //
242 // This object cache implementation writes cached objects to disk to the
243 // directory specified by CacheDir, using a filename provided in the module
244 // descriptor. The cache tries to load a saved object using that path if the
245 // file exists. CacheDir defaults to "", in which case objects are cached
246 // alongside their originating bitcodes.
247 //
248 class LLIObjectCache : public ObjectCache {
249 public:
250   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
251     // Add trailing '/' to cache dir if necessary.
252     if (!this->CacheDir.empty() &&
253         this->CacheDir[this->CacheDir.size() - 1] != '/')
254       this->CacheDir += '/';
255   }
256   ~LLIObjectCache() override {}
257
258   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
259     const std::string ModuleID = M->getModuleIdentifier();
260     std::string CacheName;
261     if (!getCacheFilename(ModuleID, CacheName))
262       return;
263     if (!CacheDir.empty()) { // Create user-defined cache dir.
264       SmallString<128> dir(sys::path::parent_path(CacheName));
265       sys::fs::create_directories(Twine(dir));
266     }
267     std::error_code EC;
268     raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
269     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
270     outfile.close();
271   }
272
273   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
274     const std::string ModuleID = M->getModuleIdentifier();
275     std::string CacheName;
276     if (!getCacheFilename(ModuleID, CacheName))
277       return nullptr;
278     // Load the object from the cache filename
279     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
280         MemoryBuffer::getFile(CacheName.c_str(), -1, false);
281     // If the file isn't there, that's OK.
282     if (!IRObjectBuffer)
283       return nullptr;
284     // MCJIT will want to write into this buffer, and we don't want that
285     // because the file has probably just been mmapped.  Instead we make
286     // a copy.  The filed-based buffer will be released when it goes
287     // out of scope.
288     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
289   }
290
291 private:
292   std::string CacheDir;
293
294   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
295     std::string Prefix("file:");
296     size_t PrefixLength = Prefix.length();
297     if (ModID.substr(0, PrefixLength) != Prefix)
298       return false;
299         std::string CacheSubdir = ModID.substr(PrefixLength);
300 #if defined(_WIN32)
301         // Transform "X:\foo" => "/X\foo" for convenience.
302         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
303           CacheSubdir[1] = CacheSubdir[0];
304           CacheSubdir[0] = '/';
305         }
306 #endif
307     CacheName = CacheDir + CacheSubdir;
308     size_t pos = CacheName.rfind('.');
309     CacheName.replace(pos, CacheName.length() - pos, ".o");
310     return true;
311   }
312 };
313
314 static ExecutionEngine *EE = nullptr;
315 static LLIObjectCache *CacheManager = nullptr;
316
317 static void do_shutdown() {
318   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
319 #ifndef DO_NOTHING_ATEXIT
320   delete EE;
321   if (CacheManager)
322     delete CacheManager;
323   llvm_shutdown();
324 #endif
325 }
326
327 // On Mingw and Cygwin, an external symbol named '__main' is called from the
328 // generated 'main' function to allow static intialization.  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,
333                                   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 = make_unique<Module>("CygMingHelper", Context);
340   M->setTargetTriple(TargetTripleStr);
341
342   // Create an empty function named "__main".
343   Function *Result;
344   if (TargetTriple.isArch64Bit()) {
345     Result = Function::Create(
346       TypeBuilder<int64_t(void), false>::get(Context),
347       GlobalValue::ExternalLinkage, "__main", M.get());
348   } else {
349     Result = Function::Create(
350       TypeBuilder<int32_t(void), false>::get(Context),
351       GlobalValue::ExternalLinkage, "__main", M.get());
352   }
353   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
354   Builder.SetInsertPoint(BB);
355   Value *ReturnVal;
356   if (TargetTriple.isArch64Bit())
357     ReturnVal = ConstantInt::get(Context, APInt(64, 0));
358   else
359     ReturnVal = ConstantInt::get(Context, APInt(32, 0));
360   Builder.CreateRet(ReturnVal);
361
362   // Add this new module to the ExecutionEngine.
363   EE->addModule(std::move(M));
364 }
365
366 CodeGenOpt::Level getOptLevel() {
367   switch (OptLevel) {
368   default:
369     errs() << "lli: Invalid optimization level.\n";
370     exit(1);
371   case '0': return CodeGenOpt::None;
372   case '1': return CodeGenOpt::Less;
373   case ' ':
374   case '2': return CodeGenOpt::Default;
375   case '3': return CodeGenOpt::Aggressive;
376   }
377   llvm_unreachable("Unrecognized opt level.");
378 }
379
380 //===----------------------------------------------------------------------===//
381 // main Driver function
382 //
383 int main(int argc, char **argv, char * const *envp) {
384   sys::PrintStackTraceOnErrorSignal();
385   PrettyStackTraceProgram X(argc, argv);
386
387   LLVMContext &Context = getGlobalContext();
388   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
389
390   // If we have a native target, initialize it to ensure it is linked in and
391   // usable by the JIT.
392   InitializeNativeTarget();
393   InitializeNativeTargetAsmPrinter();
394   InitializeNativeTargetAsmParser();
395
396   cl::ParseCommandLineOptions(argc, argv,
397                               "llvm interpreter & dynamic compiler\n");
398
399   // If the user doesn't want core files, disable them.
400   if (DisableCoreFiles)
401     sys::Process::PreventCoreFiles();
402
403   // Load the bitcode...
404   SMDiagnostic Err;
405   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
406   Module *Mod = Owner.get();
407   if (!Mod) {
408     Err.print(argv[0], errs());
409     return 1;
410   }
411
412   if (UseJITKind == JITKind::OrcLazy)
413     return runOrcLazyJIT(std::move(Owner), argc, argv);
414
415   if (EnableCacheManager) {
416     std::string CacheName("file:");
417     CacheName.append(InputFile);
418     Mod->setModuleIdentifier(CacheName);
419   }
420
421   // If not jitting lazily, load the whole bitcode file eagerly too.
422   if (NoLazyCompilation) {
423     if (std::error_code EC = Mod->materializeAll()) {
424       errs() << argv[0] << ": bitcode didn't read correctly.\n";
425       errs() << "Reason: " << EC.message() << "\n";
426       exit(1);
427     }
428   }
429
430   std::string ErrorMsg;
431   EngineBuilder builder(std::move(Owner));
432   builder.setMArch(MArch);
433   builder.setMCPU(MCPU);
434   builder.setMAttrs(MAttrs);
435   builder.setRelocationModel(RelocModel);
436   builder.setCodeModel(CMModel);
437   builder.setErrorStr(&ErrorMsg);
438   builder.setEngineKind(ForceInterpreter
439                         ? EngineKind::Interpreter
440                         : EngineKind::JIT);
441   builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
442
443   // If we are supposed to override the target triple, do so now.
444   if (!TargetTriple.empty())
445     Mod->setTargetTriple(Triple::normalize(TargetTriple));
446
447   // Enable MCJIT if desired.
448   RTDyldMemoryManager *RTDyldMM = nullptr;
449   if (!ForceInterpreter) {
450     if (RemoteMCJIT)
451       RTDyldMM = new ForwardingMemoryManager();
452     else
453       RTDyldMM = new SectionMemoryManager();
454
455     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
456     // RTDyldMM: We still use it below, even though we don't own it.
457     builder.setMCJITMemoryManager(
458       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
459   } else if (RemoteMCJIT) {
460     errs() << "error: Remote process execution does not work with the "
461               "interpreter.\n";
462     exit(1);
463   }
464
465   builder.setOptLevel(getOptLevel());
466
467   TargetOptions Options;
468   if (FloatABIForCalls != FloatABI::Default)
469     Options.FloatABIType = FloatABIForCalls;
470
471   builder.setTargetOptions(Options);
472
473   EE = builder.create();
474   if (!EE) {
475     if (!ErrorMsg.empty())
476       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
477     else
478       errs() << argv[0] << ": unknown error creating EE!\n";
479     exit(1);
480   }
481
482   if (EnableCacheManager) {
483     CacheManager = new LLIObjectCache(ObjectCacheDir);
484     EE->setObjectCache(CacheManager);
485   }
486
487   // Load any additional modules specified on the command line.
488   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
489     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
490     if (!XMod) {
491       Err.print(argv[0], errs());
492       return 1;
493     }
494     if (EnableCacheManager) {
495       std::string CacheName("file:");
496       CacheName.append(ExtraModules[i]);
497       XMod->setModuleIdentifier(CacheName);
498     }
499     EE->addModule(std::move(XMod));
500   }
501
502   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
503     ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
504         object::ObjectFile::createObjectFile(ExtraObjects[i]);
505     if (!Obj) {
506       Err.print(argv[0], errs());
507       return 1;
508     }
509     object::OwningBinary<object::ObjectFile> &O = Obj.get();
510     EE->addObjectFile(std::move(O));
511   }
512
513   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
514     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
515         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
516     if (!ArBufOrErr) {
517       Err.print(argv[0], errs());
518       return 1;
519     }
520     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
521
522     ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
523         object::Archive::create(ArBuf->getMemBufferRef());
524     if (std::error_code EC = ArOrErr.getError()) {
525       errs() << EC.message();
526       return 1;
527     }
528     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
529
530     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
531
532     EE->addArchive(std::move(OB));
533   }
534
535   // If the target is Cygwin/MingW and we are generating remote code, we
536   // need an extra module to help out with linking.
537   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
538     addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
539   }
540
541   // The following functions have no effect if their respective profiling
542   // support wasn't enabled in the build configuration.
543   EE->RegisterJITEventListener(
544                 JITEventListener::createOProfileJITEventListener());
545   EE->RegisterJITEventListener(
546                 JITEventListener::createIntelJITEventListener());
547
548   if (!NoLazyCompilation && RemoteMCJIT) {
549     errs() << "warning: remote mcjit does not support lazy compilation\n";
550     NoLazyCompilation = true;
551   }
552   EE->DisableLazyCompilation(NoLazyCompilation);
553
554   // If the user specifically requested an argv[0] to pass into the program,
555   // do it now.
556   if (!FakeArgv0.empty()) {
557     InputFile = static_cast<std::string>(FakeArgv0);
558   } else {
559     // Otherwise, if there is a .bc suffix on the executable strip it off, it
560     // might confuse the program.
561     if (StringRef(InputFile).endswith(".bc"))
562       InputFile.erase(InputFile.length() - 3);
563   }
564
565   // Add the module's name to the start of the vector of arguments to main().
566   InputArgv.insert(InputArgv.begin(), InputFile);
567
568   // Call the main function from M as if its signature were:
569   //   int main (int argc, char **argv, const char **envp)
570   // using the contents of Args to determine argc & argv, and the contents of
571   // EnvVars to determine envp.
572   //
573   Function *EntryFn = Mod->getFunction(EntryFunc);
574   if (!EntryFn) {
575     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
576     return -1;
577   }
578
579   // Reset errno to zero on entry to main.
580   errno = 0;
581
582   int Result;
583
584   // Sanity check use of remote-jit: LLI currently only supports use of the
585   // remote JIT on Unix platforms.
586   if (RemoteMCJIT) {
587 #ifndef LLVM_ON_UNIX
588     errs() << "Warning: host does not support external remote targets.\n"
589            << "  Defaulting to local execution execution\n";
590     return -1;
591 #else
592     if (ChildExecPath.empty()) {
593       errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
594       exit(1);
595     } else if (!sys::fs::can_execute(ChildExecPath)) {
596       errs() << "Unable to find usable child executable: '" << ChildExecPath
597              << "'\n";
598       return -1;
599     }
600 #endif
601   }
602
603   if (!RemoteMCJIT) {
604     // If the program doesn't explicitly call exit, we will need the Exit
605     // function later on to make an explicit call, so get the function now.
606     Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
607                                                       Type::getInt32Ty(Context),
608                                                       nullptr);
609
610     // Run static constructors.
611     if (!ForceInterpreter) {
612       // Give MCJIT a chance to apply relocations and set page permissions.
613       EE->finalizeObject();
614     }
615     EE->runStaticConstructorsDestructors(false);
616
617     // Trigger compilation separately so code regions that need to be
618     // invalidated will be known.
619     (void)EE->getPointerToFunction(EntryFn);
620     // Clear instruction cache before code will be executed.
621     if (RTDyldMM)
622       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
623
624     // Run main.
625     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
626
627     // Run static destructors.
628     EE->runStaticConstructorsDestructors(true);
629
630     // If the program didn't call exit explicitly, we should call it now.
631     // This ensures that any atexit handlers get called correctly.
632     if (Function *ExitF = dyn_cast<Function>(Exit)) {
633       std::vector<GenericValue> Args;
634       GenericValue ResultGV;
635       ResultGV.IntVal = APInt(32, Result);
636       Args.push_back(ResultGV);
637       EE->runFunction(ExitF, Args);
638       errs() << "ERROR: exit(" << Result << ") returned!\n";
639       abort();
640     } else {
641       errs() << "ERROR: exit defined with wrong prototype!\n";
642       abort();
643     }
644   } else {
645     // else == "if (RemoteMCJIT)"
646
647     // Remote target MCJIT doesn't (yet) support static constructors. No reason
648     // it couldn't. This is a limitation of the LLI implemantation, not the
649     // MCJIT itself. FIXME.
650
651     // Lanch the remote process and get a channel to it.
652     std::unique_ptr<FDRPCChannel> C = launchRemote();
653     if (!C) {
654       errs() << "Failed to launch remote JIT.\n";
655       exit(1);
656     }
657
658     // Create a remote target client running over the channel.
659     typedef orc::remote::OrcRemoteTargetClient<orc::remote::RPCChannel> MyRemote;
660     ErrorOr<MyRemote> R = MyRemote::Create(*C);
661     if (!R) {
662       errs() << "Could not create remote: " << R.getError().message() << "\n";
663       exit(1);
664     }
665
666     // Create a remote memory manager.
667     std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM;
668     if (auto EC = R->createRemoteMemoryManager(RemoteMM)) {
669       errs() << "Could not create remote memory manager: " << EC.message() << "\n";
670       exit(1);
671     }
672
673     // Forward MCJIT's memory manager calls to the remote memory manager.
674     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
675       std::move(RemoteMM));
676
677     // Forward MCJIT's symbol resolution calls to the remote.
678     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setResolver(
679       orc::createLambdaResolver(
680         [&](const std::string &Name) {
681           orc::TargetAddress Addr = 0;
682           if (auto EC = R->getSymbolAddress(Addr, Name)) {
683             errs() << "Failure during symbol lookup: " << EC.message() << "\n";
684             exit(1);
685           }
686           return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
687         },
688         [](const std::string &Name) { return nullptr; }
689       ));
690
691     // Grab the target address of the JIT'd main function on the remote and call
692     // it.
693     // FIXME: argv and envp handling.
694     orc::TargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
695     EE->finalizeObject();
696     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
697                  << format("%llx", Entry) << "\n");
698     if (auto EC = R->callIntVoid(Result, Entry))
699       errs() << "ERROR: " << EC.message() << "\n";
700
701     // Like static constructors, the remote target MCJIT support doesn't handle
702     // this yet. It could. FIXME.
703
704     // Delete the EE - we need to tear it down *before* we terminate the session
705     // with the remote, otherwise it'll crash when it tries to release resources
706     // on a remote that has already been disconnected.
707     delete EE;
708     EE = nullptr;
709
710     // Signal the remote target that we're done JITing.
711     R->terminateSession();
712   }
713
714   return Result;
715 }
716
717 std::unique_ptr<FDRPCChannel> launchRemote() {
718 #ifndef LLVM_ON_UNIX
719   llvm_unreachable("launchRemote not supported on non-Unix platforms");
720 #else
721   int PipeFD[2][2];
722   pid_t ChildPID;
723
724   // Create two pipes.
725   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
726     perror("Error creating pipe: ");
727
728   ChildPID = fork();
729
730   if (ChildPID == 0) {
731     // In the child...
732
733     // Close the parent ends of the pipes
734     close(PipeFD[0][1]);
735     close(PipeFD[1][0]);
736
737
738     // Execute the child process.
739     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
740     {
741       ChildPath.reset(new char[ChildExecPath.size() + 1]);
742       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
743       ChildPath[ChildExecPath.size()] = '\0';
744       std::string ChildInStr = std::to_string(PipeFD[0][0]);
745       ChildIn.reset(new char[ChildInStr.size() + 1]);
746       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
747       ChildIn[ChildInStr.size()] = '\0';
748       std::string ChildOutStr = std::to_string(PipeFD[1][1]);
749       ChildOut.reset(new char[ChildOutStr.size() + 1]);
750       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
751       ChildOut[ChildOutStr.size()] = '\0';
752     }
753
754     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
755     int rc = execv(ChildExecPath.c_str(), args);
756     if (rc != 0)
757       perror("Error executing child process: ");
758     llvm_unreachable("Error executing child process");
759   }
760   // else we're the parent...
761
762   // Close the child ends of the pipes
763   close(PipeFD[0][0]);
764   close(PipeFD[1][1]);
765
766   // Return an RPC channel connected to our end of the pipes.
767   return llvm::make_unique<FDRPCChannel>(PipeFD[1][0], PipeFD[0][1]);
768 #endif
769 }