]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lli/lli.cpp
Merge ^/head r313896 through r314128.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/StringExtras.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Bitcode/BitcodeReader.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/ExecutionEngine/Interpreter.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/ExecutionEngine/MCJIT.h"
27 #include "llvm/ExecutionEngine/ObjectCache.h"
28 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
29 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
30 #include "llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/TypeBuilder.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/DynamicLibrary.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Memory.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/PluginLoader.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/Process.h"
50 #include "llvm/Support/Program.h"
51 #include "llvm/Support/Signals.h"
52 #include "llvm/Support/SourceMgr.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Instrumentation.h"
56 #include <cerrno>
57
58 #ifdef __CYGWIN__
59 #include <cygwin/version.h>
60 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
61 #define DO_NOTHING_ATEXIT 1
62 #endif
63 #endif
64
65 using namespace llvm;
66
67 #define DEBUG_TYPE "lli"
68
69 namespace {
70
71   enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
72
73   cl::opt<std::string>
74   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
75
76   cl::list<std::string>
77   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
78
79   cl::opt<bool> ForceInterpreter("force-interpreter",
80                                  cl::desc("Force interpretation: disable JIT"),
81                                  cl::init(false));
82
83   cl::opt<JITKind> UseJITKind("jit-kind",
84                               cl::desc("Choose underlying JIT kind."),
85                               cl::init(JITKind::MCJIT),
86                               cl::values(
87                                 clEnumValN(JITKind::MCJIT, "mcjit",
88                                            "MCJIT"),
89                                 clEnumValN(JITKind::OrcMCJITReplacement,
90                                            "orc-mcjit",
91                                            "Orc-based MCJIT replacement"),
92                                 clEnumValN(JITKind::OrcLazy,
93                                            "orc-lazy",
94                                            "Orc-based lazy JIT.")));
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> RelocModel(
190       "relocation-model", cl::desc("Choose relocation model"),
191       cl::values(
192           clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
193           clEnumValN(Reloc::PIC_, "pic",
194                      "Fully relocatable, position independent code"),
195           clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
196                      "Relocatable external references, non-relocatable code")));
197
198   cl::opt<llvm::CodeModel::Model>
199   CMModel("code-model",
200           cl::desc("Choose code model"),
201           cl::init(CodeModel::JITDefault),
202           cl::values(clEnumValN(CodeModel::JITDefault, "default",
203                                 "Target default JIT code model"),
204                      clEnumValN(CodeModel::Small, "small",
205                                 "Small code model"),
206                      clEnumValN(CodeModel::Kernel, "kernel",
207                                 "Kernel code model"),
208                      clEnumValN(CodeModel::Medium, "medium",
209                                 "Medium code model"),
210                      clEnumValN(CodeModel::Large, "large",
211                                 "Large code model")));
212
213   cl::opt<bool>
214   GenerateSoftFloatCalls("soft-float",
215     cl::desc("Generate software floating point library calls"),
216     cl::init(false));
217
218   cl::opt<llvm::FloatABI::ABIType>
219   FloatABIForCalls("float-abi",
220                    cl::desc("Choose float ABI type"),
221                    cl::init(FloatABI::Default),
222                    cl::values(
223                      clEnumValN(FloatABI::Default, "default",
224                                 "Target default float ABI type"),
225                      clEnumValN(FloatABI::Soft, "soft",
226                                 "Soft float ABI (implied by -soft-float)"),
227                      clEnumValN(FloatABI::Hard, "hard",
228                                 "Hard float ABI (uses FP registers)")));
229
230   ExitOnError ExitOnErr;
231 }
232
233 //===----------------------------------------------------------------------===//
234 // Object cache
235 //
236 // This object cache implementation writes cached objects to disk to the
237 // directory specified by CacheDir, using a filename provided in the module
238 // descriptor. The cache tries to load a saved object using that path if the
239 // file exists. CacheDir defaults to "", in which case objects are cached
240 // alongside their originating bitcodes.
241 //
242 class LLIObjectCache : public ObjectCache {
243 public:
244   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
245     // Add trailing '/' to cache dir if necessary.
246     if (!this->CacheDir.empty() &&
247         this->CacheDir[this->CacheDir.size() - 1] != '/')
248       this->CacheDir += '/';
249   }
250   ~LLIObjectCache() override {}
251
252   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
253     const std::string &ModuleID = M->getModuleIdentifier();
254     std::string CacheName;
255     if (!getCacheFilename(ModuleID, CacheName))
256       return;
257     if (!CacheDir.empty()) { // Create user-defined cache dir.
258       SmallString<128> dir(sys::path::parent_path(CacheName));
259       sys::fs::create_directories(Twine(dir));
260     }
261     std::error_code EC;
262     raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
263     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
264     outfile.close();
265   }
266
267   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
268     const std::string &ModuleID = M->getModuleIdentifier();
269     std::string CacheName;
270     if (!getCacheFilename(ModuleID, CacheName))
271       return nullptr;
272     // Load the object from the cache filename
273     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
274         MemoryBuffer::getFile(CacheName, -1, false);
275     // If the file isn't there, that's OK.
276     if (!IRObjectBuffer)
277       return nullptr;
278     // MCJIT will want to write into this buffer, and we don't want that
279     // because the file has probably just been mmapped.  Instead we make
280     // a copy.  The filed-based buffer will be released when it goes
281     // out of scope.
282     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
283   }
284
285 private:
286   std::string CacheDir;
287
288   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
289     std::string Prefix("file:");
290     size_t PrefixLength = Prefix.length();
291     if (ModID.substr(0, PrefixLength) != Prefix)
292       return false;
293         std::string CacheSubdir = ModID.substr(PrefixLength);
294 #if defined(_WIN32)
295         // Transform "X:\foo" => "/X\foo" for convenience.
296         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
297           CacheSubdir[1] = CacheSubdir[0];
298           CacheSubdir[0] = '/';
299         }
300 #endif
301     CacheName = CacheDir + CacheSubdir;
302     size_t pos = CacheName.rfind('.');
303     CacheName.replace(pos, CacheName.length() - pos, ".o");
304     return true;
305   }
306 };
307
308 // On Mingw and Cygwin, an external symbol named '__main' is called from the
309 // generated 'main' function to allow static initialization.  To avoid linking
310 // problems with remote targets (because lli's remote target support does not
311 // currently handle external linking) we add a secondary module which defines
312 // an empty '__main' function.
313 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
314                                   StringRef TargetTripleStr) {
315   IRBuilder<> Builder(Context);
316   Triple TargetTriple(TargetTripleStr);
317
318   // Create a new module.
319   std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
320   M->setTargetTriple(TargetTripleStr);
321
322   // Create an empty function named "__main".
323   Function *Result;
324   if (TargetTriple.isArch64Bit()) {
325     Result = Function::Create(
326       TypeBuilder<int64_t(void), false>::get(Context),
327       GlobalValue::ExternalLinkage, "__main", M.get());
328   } else {
329     Result = Function::Create(
330       TypeBuilder<int32_t(void), false>::get(Context),
331       GlobalValue::ExternalLinkage, "__main", M.get());
332   }
333   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
334   Builder.SetInsertPoint(BB);
335   Value *ReturnVal;
336   if (TargetTriple.isArch64Bit())
337     ReturnVal = ConstantInt::get(Context, APInt(64, 0));
338   else
339     ReturnVal = ConstantInt::get(Context, APInt(32, 0));
340   Builder.CreateRet(ReturnVal);
341
342   // Add this new module to the ExecutionEngine.
343   EE.addModule(std::move(M));
344 }
345
346 CodeGenOpt::Level getOptLevel() {
347   switch (OptLevel) {
348   default:
349     errs() << "lli: Invalid optimization level.\n";
350     exit(1);
351   case '0': return CodeGenOpt::None;
352   case '1': return CodeGenOpt::Less;
353   case ' ':
354   case '2': return CodeGenOpt::Default;
355   case '3': return CodeGenOpt::Aggressive;
356   }
357   llvm_unreachable("Unrecognized opt level.");
358 }
359
360 LLVM_ATTRIBUTE_NORETURN
361 static void reportError(SMDiagnostic Err, const char *ProgName) {
362   Err.print(ProgName, errs());
363   exit(1);
364 }
365
366 //===----------------------------------------------------------------------===//
367 // main Driver function
368 //
369 int main(int argc, char **argv, char * const *envp) {
370   sys::PrintStackTraceOnErrorSignal(argv[0]);
371   PrettyStackTraceProgram X(argc, argv);
372
373   atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
374
375   if (argc > 1)
376     ExitOnErr.setBanner(std::string(argv[0]) + ": ");
377
378   // If we have a native target, initialize it to ensure it is linked in and
379   // usable by the JIT.
380   InitializeNativeTarget();
381   InitializeNativeTargetAsmPrinter();
382   InitializeNativeTargetAsmParser();
383
384   cl::ParseCommandLineOptions(argc, argv,
385                               "llvm interpreter & dynamic compiler\n");
386
387   // If the user doesn't want core files, disable them.
388   if (DisableCoreFiles)
389     sys::Process::PreventCoreFiles();
390
391   LLVMContext Context;
392
393   // Load the bitcode...
394   SMDiagnostic Err;
395   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
396   Module *Mod = Owner.get();
397   if (!Mod)
398     reportError(Err, argv[0]);
399
400   if (UseJITKind == JITKind::OrcLazy) {
401     std::vector<std::unique_ptr<Module>> Ms;
402     Ms.push_back(std::move(Owner));
403     for (auto &ExtraMod : ExtraModules) {
404       Ms.push_back(parseIRFile(ExtraMod, Err, Context));
405       if (!Ms.back())
406         reportError(Err, argv[0]);
407     }
408     std::vector<std::string> Args;
409     Args.push_back(InputFile);
410     for (auto &Arg : InputArgv)
411       Args.push_back(Arg);
412     return runOrcLazyJIT(std::move(Ms), Args);
413   }
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     // Use *argv instead of argv[0] to work around a wrong GCC warning.
424     ExitOnError ExitOnErr(std::string(*argv) +
425                           ": bitcode didn't read correctly: ");
426     ExitOnErr(Mod->materializeAll());
427   }
428
429   std::string ErrorMsg;
430   EngineBuilder builder(std::move(Owner));
431   builder.setMArch(MArch);
432   builder.setMCPU(MCPU);
433   builder.setMAttrs(MAttrs);
434   if (RelocModel.getNumOccurrences())
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   std::unique_ptr<ExecutionEngine> 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   std::unique_ptr<LLIObjectCache> CacheManager;
483   if (EnableCacheManager) {
484     CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
485     EE->setObjectCache(CacheManager.get());
486   }
487
488   // Load any additional modules specified on the command line.
489   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
490     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
491     if (!XMod)
492       reportError(Err, argv[0]);
493     if (EnableCacheManager) {
494       std::string CacheName("file:");
495       CacheName.append(ExtraModules[i]);
496       XMod->setModuleIdentifier(CacheName);
497     }
498     EE->addModule(std::move(XMod));
499   }
500
501   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
502     Expected<object::OwningBinary<object::ObjectFile>> Obj =
503         object::ObjectFile::createObjectFile(ExtraObjects[i]);
504     if (!Obj) {
505       // TODO: Actually report errors helpfully.
506       consumeError(Obj.takeError());
507       reportError(Err, argv[0]);
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       reportError(Err, argv[0]);
518     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
519
520     Expected<std::unique_ptr<object::Archive>> ArOrErr =
521         object::Archive::create(ArBuf->getMemBufferRef());
522     if (!ArOrErr) {
523       std::string Buf;
524       raw_string_ostream OS(Buf);
525       logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
526       OS.flush();
527       errs() << Buf;
528       exit(1);
529     }
530     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
531
532     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
533
534     EE->addArchive(std::move(OB));
535   }
536
537   // If the target is Cygwin/MingW and we are generating remote code, we
538   // need an extra module to help out with linking.
539   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
540     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
541   }
542
543   // The following functions have no effect if their respective profiling
544   // support wasn't enabled in the build configuration.
545   EE->RegisterJITEventListener(
546                 JITEventListener::createOProfileJITEventListener());
547   EE->RegisterJITEventListener(
548                 JITEventListener::createIntelJITEventListener());
549
550   if (!NoLazyCompilation && RemoteMCJIT) {
551     errs() << "warning: remote mcjit does not support lazy compilation\n";
552     NoLazyCompilation = true;
553   }
554   EE->DisableLazyCompilation(NoLazyCompilation);
555
556   // If the user specifically requested an argv[0] to pass into the program,
557   // do it now.
558   if (!FakeArgv0.empty()) {
559     InputFile = static_cast<std::string>(FakeArgv0);
560   } else {
561     // Otherwise, if there is a .bc suffix on the executable strip it off, it
562     // might confuse the program.
563     if (StringRef(InputFile).endswith(".bc"))
564       InputFile.erase(InputFile.length() - 3);
565   }
566
567   // Add the module's name to the start of the vector of arguments to main().
568   InputArgv.insert(InputArgv.begin(), InputFile);
569
570   // Call the main function from M as if its signature were:
571   //   int main (int argc, char **argv, const char **envp)
572   // using the contents of Args to determine argc & argv, and the contents of
573   // EnvVars to determine envp.
574   //
575   Function *EntryFn = Mod->getFunction(EntryFunc);
576   if (!EntryFn) {
577     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
578     return -1;
579   }
580
581   // Reset errno to zero on entry to main.
582   errno = 0;
583
584   int Result = -1;
585
586   // Sanity check use of remote-jit: LLI currently only supports use of the
587   // remote JIT on Unix platforms.
588   if (RemoteMCJIT) {
589 #ifndef LLVM_ON_UNIX
590     errs() << "Warning: host does not support external remote targets.\n"
591            << "  Defaulting to local execution\n";
592     return -1;
593 #else
594     if (ChildExecPath.empty()) {
595       errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
596       exit(1);
597     } else if (!sys::fs::can_execute(ChildExecPath)) {
598       errs() << "Unable to find usable child executable: '" << ChildExecPath
599              << "'\n";
600       return -1;
601     }
602 #endif
603   }
604
605   if (!RemoteMCJIT) {
606     // If the program doesn't explicitly call exit, we will need the Exit
607     // function later on to make an explicit call, so get the function now.
608     Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
609                                                       Type::getInt32Ty(Context),
610                                                       nullptr);
611
612     // Run static constructors.
613     if (!ForceInterpreter) {
614       // Give MCJIT a chance to apply relocations and set page permissions.
615       EE->finalizeObject();
616     }
617     EE->runStaticConstructorsDestructors(false);
618
619     // Trigger compilation separately so code regions that need to be
620     // invalidated will be known.
621     (void)EE->getPointerToFunction(EntryFn);
622     // Clear instruction cache before code will be executed.
623     if (RTDyldMM)
624       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
625
626     // Run main.
627     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
628
629     // Run static destructors.
630     EE->runStaticConstructorsDestructors(true);
631
632     // If the program didn't call exit explicitly, we should call it now.
633     // This ensures that any atexit handlers get called correctly.
634     if (Function *ExitF = dyn_cast<Function>(Exit)) {
635       std::vector<GenericValue> Args;
636       GenericValue ResultGV;
637       ResultGV.IntVal = APInt(32, Result);
638       Args.push_back(ResultGV);
639       EE->runFunction(ExitF, Args);
640       errs() << "ERROR: exit(" << Result << ") returned!\n";
641       abort();
642     } else {
643       errs() << "ERROR: exit defined with wrong prototype!\n";
644       abort();
645     }
646   } else {
647     // else == "if (RemoteMCJIT)"
648
649     // Remote target MCJIT doesn't (yet) support static constructors. No reason
650     // it couldn't. This is a limitation of the LLI implemantation, not the
651     // MCJIT itself. FIXME.
652
653     // Lanch the remote process and get a channel to it.
654     std::unique_ptr<FDRawChannel> C = launchRemote();
655     if (!C) {
656       errs() << "Failed to launch remote JIT.\n";
657       exit(1);
658     }
659
660     // Create a remote target client running over the channel.
661     typedef orc::remote::OrcRemoteTargetClient<orc::rpc::RawByteChannel>
662       MyRemote;
663     auto R = ExitOnErr(MyRemote::Create(*C));
664
665     // Create a remote memory manager.
666     std::unique_ptr<MyRemote::RCMemoryManager> RemoteMM;
667     ExitOnErr(R->createRemoteMemoryManager(RemoteMM));
668
669     // Forward MCJIT's memory manager calls to the remote memory manager.
670     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
671       std::move(RemoteMM));
672
673     // Forward MCJIT's symbol resolution calls to the remote.
674     static_cast<ForwardingMemoryManager*>(RTDyldMM)->setResolver(
675       orc::createLambdaResolver(
676         [](const std::string &Name) { return nullptr; },
677         [&](const std::string &Name) {
678           if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
679             return JITSymbol(Addr, JITSymbolFlags::Exported);
680           return JITSymbol(nullptr);
681         }
682       ));
683
684     // Grab the target address of the JIT'd main function on the remote and call
685     // it.
686     // FIXME: argv and envp handling.
687     JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
688     EE->finalizeObject();
689     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
690                  << format("%llx", Entry) << "\n");
691     Result = ExitOnErr(R->callIntVoid(Entry));
692
693     // Like static constructors, the remote target MCJIT support doesn't handle
694     // this yet. It could. FIXME.
695
696     // Delete the EE - we need to tear it down *before* we terminate the session
697     // with the remote, otherwise it'll crash when it tries to release resources
698     // on a remote that has already been disconnected.
699     EE.reset();
700
701     // Signal the remote target that we're done JITing.
702     ExitOnErr(R->terminateSession());
703   }
704
705   return Result;
706 }
707
708 std::unique_ptr<FDRawChannel> launchRemote() {
709 #ifndef LLVM_ON_UNIX
710   llvm_unreachable("launchRemote not supported on non-Unix platforms");
711 #else
712   int PipeFD[2][2];
713   pid_t ChildPID;
714
715   // Create two pipes.
716   if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
717     perror("Error creating pipe: ");
718
719   ChildPID = fork();
720
721   if (ChildPID == 0) {
722     // In the child...
723
724     // Close the parent ends of the pipes
725     close(PipeFD[0][1]);
726     close(PipeFD[1][0]);
727
728
729     // Execute the child process.
730     std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
731     {
732       ChildPath.reset(new char[ChildExecPath.size() + 1]);
733       std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
734       ChildPath[ChildExecPath.size()] = '\0';
735       std::string ChildInStr = utostr(PipeFD[0][0]);
736       ChildIn.reset(new char[ChildInStr.size() + 1]);
737       std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
738       ChildIn[ChildInStr.size()] = '\0';
739       std::string ChildOutStr = utostr(PipeFD[1][1]);
740       ChildOut.reset(new char[ChildOutStr.size() + 1]);
741       std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
742       ChildOut[ChildOutStr.size()] = '\0';
743     }
744
745     char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
746     int rc = execv(ChildExecPath.c_str(), args);
747     if (rc != 0)
748       perror("Error executing child process: ");
749     llvm_unreachable("Error executing child process");
750   }
751   // else we're the parent...
752
753   // Close the child ends of the pipes
754   close(PipeFD[0][0]);
755   close(PipeFD[1][1]);
756
757   // Return an RPC channel connected to our end of the pipes.
758   return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);
759 #endif
760 }