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