[MCJIT] Remove a few more references to JITMemoryManager that survived r218316.
[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 "llvm/IR/LLVMContext.h"
17 #include "RemoteMemoryManager.h"
18 #include "RemoteTarget.h"
19 #include "RemoteTargetExternal.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Bitcode/ReaderWriter.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/SectionMemoryManager.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/TypeBuilder.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/Object/Archive.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/DynamicLibrary.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Memory.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Process.h"
47 #include "llvm/Support/Program.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Transforms/Instrumentation.h"
53 #include <cerrno>
54
55 #ifdef __CYGWIN__
56 #include <cygwin/version.h>
57 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
58 #define DO_NOTHING_ATEXIT 1
59 #endif
60 #endif
61
62 using namespace llvm;
63
64 #define DEBUG_TYPE "lli"
65
66 namespace {
67   cl::opt<std::string>
68   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
69
70   cl::list<std::string>
71   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
72
73   cl::opt<bool> ForceInterpreter("force-interpreter",
74                                  cl::desc("Force interpretation: disable JIT"),
75                                  cl::init(false));
76
77   cl::opt<bool> DebugIR(
78     "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
79     cl::init(false));
80
81   // The MCJIT supports building for a target address space separate from
82   // the JIT compilation process. Use a forked process and a copying
83   // memory manager with IPC to execute using this functionality.
84   cl::opt<bool> RemoteMCJIT("remote-mcjit",
85     cl::desc("Execute MCJIT'ed code in a separate process."),
86     cl::init(false));
87
88   // Manually specify the child process for remote execution. This overrides
89   // the simulated remote execution that allocates address space for child
90   // execution. The child process will be executed and will communicate with
91   // lli via stdin/stdout pipes.
92   cl::opt<std::string>
93   ChildExecPath("mcjit-remote-process",
94                 cl::desc("Specify the filename of the process to launch "
95                          "for remote MCJIT execution.  If none is specified,"
96                          "\n\tremote execution will be simulated in-process."),
97                 cl::value_desc("filename"), cl::init(""));
98
99   // Determine optimization level.
100   cl::opt<char>
101   OptLevel("O",
102            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
103                     "(default = '-O2')"),
104            cl::Prefix,
105            cl::ZeroOrMore,
106            cl::init(' '));
107
108   cl::opt<std::string>
109   TargetTriple("mtriple", cl::desc("Override target triple for module"));
110
111   cl::opt<std::string>
112   MArch("march",
113         cl::desc("Architecture to generate assembly for (see --version)"));
114
115   cl::opt<std::string>
116   MCPU("mcpu",
117        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
118        cl::value_desc("cpu-name"),
119        cl::init(""));
120
121   cl::list<std::string>
122   MAttrs("mattr",
123          cl::CommaSeparated,
124          cl::desc("Target specific attributes (-mattr=help for details)"),
125          cl::value_desc("a1,+a2,-a3,..."));
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<Reloc::Model>
175   RelocModel("relocation-model",
176              cl::desc("Choose relocation model"),
177              cl::init(Reloc::Default),
178              cl::values(
179             clEnumValN(Reloc::Default, "default",
180                        "Target default relocation model"),
181             clEnumValN(Reloc::Static, "static",
182                        "Non-relocatable code"),
183             clEnumValN(Reloc::PIC_, "pic",
184                        "Fully relocatable, position independent code"),
185             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
186                        "Relocatable external references, non-relocatable code"),
187             clEnumValEnd));
188
189   cl::opt<llvm::CodeModel::Model>
190   CMModel("code-model",
191           cl::desc("Choose code model"),
192           cl::init(CodeModel::JITDefault),
193           cl::values(clEnumValN(CodeModel::JITDefault, "default",
194                                 "Target default JIT code model"),
195                      clEnumValN(CodeModel::Small, "small",
196                                 "Small code model"),
197                      clEnumValN(CodeModel::Kernel, "kernel",
198                                 "Kernel code model"),
199                      clEnumValN(CodeModel::Medium, "medium",
200                                 "Medium code model"),
201                      clEnumValN(CodeModel::Large, "large",
202                                 "Large code model"),
203                      clEnumValEnd));
204
205   cl::opt<bool>
206   GenerateSoftFloatCalls("soft-float",
207     cl::desc("Generate software floating point library calls"),
208     cl::init(false));
209
210   cl::opt<llvm::FloatABI::ABIType>
211   FloatABIForCalls("float-abi",
212                    cl::desc("Choose float ABI type"),
213                    cl::init(FloatABI::Default),
214                    cl::values(
215                      clEnumValN(FloatABI::Default, "default",
216                                 "Target default float ABI type"),
217                      clEnumValN(FloatABI::Soft, "soft",
218                                 "Soft float ABI (implied by -soft-float)"),
219                      clEnumValN(FloatABI::Hard, "hard",
220                                 "Hard float ABI (uses FP registers)"),
221                      clEnumValEnd));
222   cl::opt<bool>
223 // In debug builds, make this default to true.
224 #ifdef NDEBUG
225 #define EMIT_DEBUG false
226 #else
227 #define EMIT_DEBUG true
228 #endif
229   EmitJitDebugInfo("jit-emit-debug",
230     cl::desc("Emit debug information to debugger"),
231     cl::init(EMIT_DEBUG));
232 #undef EMIT_DEBUG
233
234   static cl::opt<bool>
235   EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
236     cl::Hidden,
237     cl::desc("Emit debug info objfiles to disk"),
238     cl::init(false));
239 }
240
241 //===----------------------------------------------------------------------===//
242 // Object cache
243 //
244 // This object cache implementation writes cached objects to disk to the
245 // directory specified by CacheDir, using a filename provided in the module
246 // descriptor. The cache tries to load a saved object using that path if the
247 // file exists. CacheDir defaults to "", in which case objects are cached
248 // alongside their originating bitcodes.
249 //
250 class LLIObjectCache : public ObjectCache {
251 public:
252   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
253     // Add trailing '/' to cache dir if necessary.
254     if (!this->CacheDir.empty() &&
255         this->CacheDir[this->CacheDir.size() - 1] != '/')
256       this->CacheDir += '/';
257   }
258   virtual ~LLIObjectCache() {}
259
260   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
261     const std::string ModuleID = M->getModuleIdentifier();
262     std::string CacheName;
263     if (!getCacheFilename(ModuleID, CacheName))
264       return;
265     if (!CacheDir.empty()) { // Create user-defined cache dir.
266       SmallString<128> dir(CacheName);
267       sys::path::remove_filename(dir);
268       sys::fs::create_directories(Twine(dir));
269     }
270     std::error_code EC;
271     raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
272     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
273     outfile.close();
274   }
275
276   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
277     const std::string ModuleID = M->getModuleIdentifier();
278     std::string CacheName;
279     if (!getCacheFilename(ModuleID, CacheName))
280       return nullptr;
281     // Load the object from the cache filename
282     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
283         MemoryBuffer::getFile(CacheName.c_str(), -1, false);
284     // If the file isn't there, that's OK.
285     if (!IRObjectBuffer)
286       return nullptr;
287     // MCJIT will want to write into this buffer, and we don't want that
288     // because the file has probably just been mmapped.  Instead we make
289     // a copy.  The filed-based buffer will be released when it goes
290     // out of scope.
291     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
292   }
293
294 private:
295   std::string CacheDir;
296
297   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
298     std::string Prefix("file:");
299     size_t PrefixLength = Prefix.length();
300     if (ModID.substr(0, PrefixLength) != Prefix)
301       return false;
302         std::string CacheSubdir = ModID.substr(PrefixLength);
303 #if defined(_WIN32)
304         // Transform "X:\foo" => "/X\foo" for convenience.
305         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
306           CacheSubdir[1] = CacheSubdir[0];
307           CacheSubdir[0] = '/';
308         }
309 #endif
310     CacheName = CacheDir + CacheSubdir;
311     size_t pos = CacheName.rfind('.');
312     CacheName.replace(pos, CacheName.length() - pos, ".o");
313     return true;
314   }
315 };
316
317 static ExecutionEngine *EE = nullptr;
318 static LLIObjectCache *CacheManager = nullptr;
319
320 static void do_shutdown() {
321   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
322 #ifndef DO_NOTHING_ATEXIT
323   delete EE;
324   if (CacheManager)
325     delete CacheManager;
326   llvm_shutdown();
327 #endif
328 }
329
330 // On Mingw and Cygwin, an external symbol named '__main' is called from the
331 // generated 'main' function to allow static intialization.  To avoid linking
332 // problems with remote targets (because lli's remote target support does not
333 // currently handle external linking) we add a secondary module which defines
334 // an empty '__main' function.
335 static void addCygMingExtraModule(ExecutionEngine *EE,
336                                   LLVMContext &Context,
337                                   StringRef TargetTripleStr) {
338   IRBuilder<> Builder(Context);
339   Triple TargetTriple(TargetTripleStr);
340
341   // Create a new module.
342   std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
343   M->setTargetTriple(TargetTripleStr);
344
345   // Create an empty function named "__main".
346   Function *Result;
347   if (TargetTriple.isArch64Bit()) {
348     Result = Function::Create(
349       TypeBuilder<int64_t(void), false>::get(Context),
350       GlobalValue::ExternalLinkage, "__main", M.get());
351   } else {
352     Result = Function::Create(
353       TypeBuilder<int32_t(void), false>::get(Context),
354       GlobalValue::ExternalLinkage, "__main", M.get());
355   }
356   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
357   Builder.SetInsertPoint(BB);
358   Value *ReturnVal;
359   if (TargetTriple.isArch64Bit())
360     ReturnVal = ConstantInt::get(Context, APInt(64, 0));
361   else
362     ReturnVal = ConstantInt::get(Context, APInt(32, 0));
363   Builder.CreateRet(ReturnVal);
364
365   // Add this new module to the ExecutionEngine.
366   EE->addModule(std::move(M));
367 }
368
369
370 //===----------------------------------------------------------------------===//
371 // main Driver function
372 //
373 int main(int argc, char **argv, char * const *envp) {
374   sys::PrintStackTraceOnErrorSignal();
375   PrettyStackTraceProgram X(argc, argv);
376
377   LLVMContext &Context = getGlobalContext();
378   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
379
380   // If we have a native target, initialize it to ensure it is linked in and
381   // usable by the JIT.
382   InitializeNativeTarget();
383   InitializeNativeTargetAsmPrinter();
384   InitializeNativeTargetAsmParser();
385
386   cl::ParseCommandLineOptions(argc, argv,
387                               "llvm interpreter & dynamic compiler\n");
388
389   // If the user doesn't want core files, disable them.
390   if (DisableCoreFiles)
391     sys::Process::PreventCoreFiles();
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     Err.print(argv[0], errs());
399     return 1;
400   }
401
402   if (EnableCacheManager) {
403     std::string CacheName("file:");
404     CacheName.append(InputFile);
405     Mod->setModuleIdentifier(CacheName);
406   }
407
408   // If not jitting lazily, load the whole bitcode file eagerly too.
409   if (NoLazyCompilation) {
410     if (std::error_code EC = Mod->materializeAllPermanently()) {
411       errs() << argv[0] << ": bitcode didn't read correctly.\n";
412       errs() << "Reason: " << EC.message() << "\n";
413       exit(1);
414     }
415   }
416
417   if (DebugIR) {
418     ModulePass *DebugIRPass = createDebugIRPass();
419     DebugIRPass->runOnModule(*Mod);
420   }
421
422   std::string ErrorMsg;
423   EngineBuilder builder(std::move(Owner));
424   builder.setMArch(MArch);
425   builder.setMCPU(MCPU);
426   builder.setMAttrs(MAttrs);
427   builder.setRelocationModel(RelocModel);
428   builder.setCodeModel(CMModel);
429   builder.setErrorStr(&ErrorMsg);
430   builder.setEngineKind(ForceInterpreter
431                         ? EngineKind::Interpreter
432                         : EngineKind::JIT);
433
434   // If we are supposed to override the target triple, do so now.
435   if (!TargetTriple.empty())
436     Mod->setTargetTriple(Triple::normalize(TargetTriple));
437
438   // Enable MCJIT if desired.
439   RTDyldMemoryManager *RTDyldMM = nullptr;
440   if (!ForceInterpreter) {
441     if (RemoteMCJIT)
442       RTDyldMM = new RemoteMemoryManager();
443     else
444       RTDyldMM = new SectionMemoryManager();
445     builder.setMCJITMemoryManager(RTDyldMM);
446   } else if (RemoteMCJIT) {
447     errs() << "error: Remote process execution does not work with the "
448               "interpreter.\n";
449     exit(1);
450   }
451
452   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
453   switch (OptLevel) {
454   default:
455     errs() << argv[0] << ": invalid optimization level.\n";
456     return 1;
457   case ' ': break;
458   case '0': OLvl = CodeGenOpt::None; break;
459   case '1': OLvl = CodeGenOpt::Less; break;
460   case '2': OLvl = CodeGenOpt::Default; break;
461   case '3': OLvl = CodeGenOpt::Aggressive; break;
462   }
463   builder.setOptLevel(OLvl);
464
465   TargetOptions Options;
466   Options.UseSoftFloat = GenerateSoftFloatCalls;
467   if (FloatABIForCalls != FloatABI::Default)
468     Options.FloatABIType = FloatABIForCalls;
469   if (GenerateSoftFloatCalls)
470     FloatABIForCalls = FloatABI::Soft;
471
472   // Remote target execution doesn't handle EH or debug registration.
473   if (!RemoteMCJIT) {
474     Options.JITEmitDebugInfo = EmitJitDebugInfo;
475     Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
476   }
477
478   builder.setTargetOptions(Options);
479
480   EE = builder.create();
481   if (!EE) {
482     if (!ErrorMsg.empty())
483       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
484     else
485       errs() << argv[0] << ": unknown error creating EE!\n";
486     exit(1);
487   }
488
489   if (EnableCacheManager) {
490     CacheManager = new LLIObjectCache(ObjectCacheDir);
491     EE->setObjectCache(CacheManager);
492   }
493
494   // Load any additional modules specified on the command line.
495   for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
496     std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
497     if (!XMod) {
498       Err.print(argv[0], errs());
499       return 1;
500     }
501     if (EnableCacheManager) {
502       std::string CacheName("file:");
503       CacheName.append(ExtraModules[i]);
504       XMod->setModuleIdentifier(CacheName);
505     }
506     EE->addModule(std::move(XMod));
507   }
508
509   for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
510     ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
511         object::ObjectFile::createObjectFile(ExtraObjects[i]);
512     if (!Obj) {
513       Err.print(argv[0], errs());
514       return 1;
515     }
516     object::OwningBinary<object::ObjectFile> &O = Obj.get();
517     EE->addObjectFile(std::move(O));
518   }
519
520   for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
521     ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
522         MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
523     if (!ArBufOrErr) {
524       Err.print(argv[0], errs());
525       return 1;
526     }
527     std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
528
529     ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
530         object::Archive::create(ArBuf->getMemBufferRef());
531     if (std::error_code EC = ArOrErr.getError()) {
532       errs() << EC.message();
533       return 1;
534     }
535     std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
536
537     object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
538
539     EE->addArchive(std::move(OB));
540   }
541
542   // If the target is Cygwin/MingW and we are generating remote code, we
543   // need an extra module to help out with linking.
544   if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
545     addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
546   }
547
548   // The following functions have no effect if their respective profiling
549   // support wasn't enabled in the build configuration.
550   EE->RegisterJITEventListener(
551                 JITEventListener::createOProfileJITEventListener());
552   EE->RegisterJITEventListener(
553                 JITEventListener::createIntelJITEventListener());
554
555   if (!NoLazyCompilation && RemoteMCJIT) {
556     errs() << "warning: remote mcjit does not support lazy compilation\n";
557     NoLazyCompilation = true;
558   }
559   EE->DisableLazyCompilation(NoLazyCompilation);
560
561   // If the user specifically requested an argv[0] to pass into the program,
562   // do it now.
563   if (!FakeArgv0.empty()) {
564     InputFile = FakeArgv0;
565   } else {
566     // Otherwise, if there is a .bc suffix on the executable strip it off, it
567     // might confuse the program.
568     if (StringRef(InputFile).endswith(".bc"))
569       InputFile.erase(InputFile.length() - 3);
570   }
571
572   // Add the module's name to the start of the vector of arguments to main().
573   InputArgv.insert(InputArgv.begin(), InputFile);
574
575   // Call the main function from M as if its signature were:
576   //   int main (int argc, char **argv, const char **envp)
577   // using the contents of Args to determine argc & argv, and the contents of
578   // EnvVars to determine envp.
579   //
580   Function *EntryFn = Mod->getFunction(EntryFunc);
581   if (!EntryFn) {
582     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
583     return -1;
584   }
585
586   // Reset errno to zero on entry to main.
587   errno = 0;
588
589   int Result;
590
591   if (!RemoteMCJIT) {
592     // If the program doesn't explicitly call exit, we will need the Exit
593     // function later on to make an explicit call, so get the function now.
594     Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
595                                                       Type::getInt32Ty(Context),
596                                                       NULL);
597
598     // Run static constructors.
599     if (!ForceInterpreter) {
600       // Give MCJIT a chance to apply relocations and set page permissions.
601       EE->finalizeObject();
602     }
603     EE->runStaticConstructorsDestructors(false);
604
605     // Trigger compilation separately so code regions that need to be
606     // invalidated will be known.
607     (void)EE->getPointerToFunction(EntryFn);
608     // Clear instruction cache before code will be executed.
609     if (RTDyldMM)
610       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
611
612     // Run main.
613     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
614
615     // Run static destructors.
616     EE->runStaticConstructorsDestructors(true);
617
618     // If the program didn't call exit explicitly, we should call it now.
619     // This ensures that any atexit handlers get called correctly.
620     if (Function *ExitF = dyn_cast<Function>(Exit)) {
621       std::vector<GenericValue> Args;
622       GenericValue ResultGV;
623       ResultGV.IntVal = APInt(32, Result);
624       Args.push_back(ResultGV);
625       EE->runFunction(ExitF, Args);
626       errs() << "ERROR: exit(" << Result << ") returned!\n";
627       abort();
628     } else {
629       errs() << "ERROR: exit defined with wrong prototype!\n";
630       abort();
631     }
632   } else {
633     // else == "if (RemoteMCJIT)"
634
635     // Remote target MCJIT doesn't (yet) support static constructors. No reason
636     // it couldn't. This is a limitation of the LLI implemantation, not the
637     // MCJIT itself. FIXME.
638     //
639     RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
640     // Everything is prepared now, so lay out our program for the target
641     // address space, assign the section addresses to resolve any relocations,
642     // and send it to the target.
643
644     std::unique_ptr<RemoteTarget> Target;
645     if (!ChildExecPath.empty()) { // Remote execution on a child process
646 #ifndef LLVM_ON_UNIX
647       // FIXME: Remove this pointless fallback mode which causes tests to "pass"
648       // on platforms where they should XFAIL.
649       errs() << "Warning: host does not support external remote targets.\n"
650              << "  Defaulting to simulated remote execution\n";
651       Target.reset(new RemoteTarget);
652 #else
653       if (!sys::fs::can_execute(ChildExecPath)) {
654         errs() << "Unable to find usable child executable: '" << ChildExecPath
655                << "'\n";
656         return -1;
657       }
658       Target.reset(new RemoteTargetExternal(ChildExecPath));
659 #endif
660     } else {
661       // No child process name provided, use simulated remote execution.
662       Target.reset(new RemoteTarget);
663     }
664
665     // Give the memory manager a pointer to our remote target interface object.
666     MM->setRemoteTarget(Target.get());
667
668     // Create the remote target.
669     if (!Target->create()) {
670       errs() << "ERROR: " << Target->getErrorMsg() << "\n";
671       return EXIT_FAILURE;
672     }
673
674     // Since we're executing in a (at least simulated) remote address space,
675     // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
676     // grab the function address directly here and tell the remote target
677     // to execute the function.
678     //
679     // Our memory manager will map generated code into the remote address
680     // space as it is loaded and copy the bits over during the finalizeMemory
681     // operation.
682     //
683     // FIXME: argv and envp handling.
684     uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
685
686     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
687                  << format("%llx", Entry) << "\n");
688
689     if (!Target->executeCode(Entry, Result))
690       errs() << "ERROR: " << Target->getErrorMsg() << "\n";
691
692     // Like static constructors, the remote target MCJIT support doesn't handle
693     // this yet. It could. FIXME.
694
695     // Stop the remote target
696     Target->stop();
697   }
698
699   return Result;
700 }