6916d1609b8378c58ec8202f369855cd758137a8
[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 "OrcLazyJIT.h"
18 #include "RemoteMemoryManager.h"
19 #include "RemoteTarget.h"
20 #include "RemoteTargetExternal.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/ExecutionEngine/Interpreter.h"
26 #include "llvm/ExecutionEngine/JITEventListener.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/ExecutionEngine/ObjectCache.h"
29 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
30 #include "llvm/ExecutionEngine/SectionMemoryManager.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                                 clEnumValEnd));
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   MArch("march",
129         cl::desc("Architecture to generate assembly for (see --version)"));
130
131   cl::opt<std::string>
132   MCPU("mcpu",
133        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
134        cl::value_desc("cpu-name"),
135        cl::init(""));
136
137   cl::list<std::string>
138   MAttrs("mattr",
139          cl::CommaSeparated,
140          cl::desc("Target specific attributes (-mattr=help for details)"),
141          cl::value_desc("a1,+a2,-a3,..."));
142
143   cl::opt<std::string>
144   EntryFunc("entry-function",
145             cl::desc("Specify the entry function (default = 'main') "
146                      "of the executable"),
147             cl::value_desc("function"),
148             cl::init("main"));
149
150   cl::list<std::string>
151   ExtraModules("extra-module",
152          cl::desc("Extra modules to be loaded"),
153          cl::value_desc("input bitcode"));
154
155   cl::list<std::string>
156   ExtraObjects("extra-object",
157          cl::desc("Extra object files to be loaded"),
158          cl::value_desc("input object"));
159
160   cl::list<std::string>
161   ExtraArchives("extra-archive",
162          cl::desc("Extra archive files to be loaded"),
163          cl::value_desc("input archive"));
164
165   cl::opt<bool>
166   EnableCacheManager("enable-cache-manager",
167         cl::desc("Use cache manager to save/load mdoules"),
168         cl::init(false));
169
170   cl::opt<std::string>
171   ObjectCacheDir("object-cache-dir",
172                   cl::desc("Directory to store cached object files "
173                            "(must be user writable)"),
174                   cl::init(""));
175
176   cl::opt<std::string>
177   FakeArgv0("fake-argv0",
178             cl::desc("Override the 'argv[0]' value passed into the executing"
179                      " program"), cl::value_desc("executable"));
180
181   cl::opt<bool>
182   DisableCoreFiles("disable-core-files", cl::Hidden,
183                    cl::desc("Disable emission of core files if possible"));
184
185   cl::opt<bool>
186   NoLazyCompilation("disable-lazy-compilation",
187                   cl::desc("Disable JIT lazy compilation"),
188                   cl::init(false));
189
190   cl::opt<Reloc::Model>
191   RelocModel("relocation-model",
192              cl::desc("Choose relocation model"),
193              cl::init(Reloc::Default),
194              cl::values(
195             clEnumValN(Reloc::Default, "default",
196                        "Target default relocation model"),
197             clEnumValN(Reloc::Static, "static",
198                        "Non-relocatable code"),
199             clEnumValN(Reloc::PIC_, "pic",
200                        "Fully relocatable, position independent code"),
201             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
202                        "Relocatable external references, non-relocatable code"),
203             clEnumValEnd));
204
205   cl::opt<llvm::CodeModel::Model>
206   CMModel("code-model",
207           cl::desc("Choose code model"),
208           cl::init(CodeModel::JITDefault),
209           cl::values(clEnumValN(CodeModel::JITDefault, "default",
210                                 "Target default JIT code model"),
211                      clEnumValN(CodeModel::Small, "small",
212                                 "Small code model"),
213                      clEnumValN(CodeModel::Kernel, "kernel",
214                                 "Kernel code model"),
215                      clEnumValN(CodeModel::Medium, "medium",
216                                 "Medium code model"),
217                      clEnumValN(CodeModel::Large, "large",
218                                 "Large code model"),
219                      clEnumValEnd));
220
221   cl::opt<bool>
222   GenerateSoftFloatCalls("soft-float",
223     cl::desc("Generate software floating point library calls"),
224     cl::init(false));
225
226   cl::opt<llvm::FloatABI::ABIType>
227   FloatABIForCalls("float-abi",
228                    cl::desc("Choose float ABI type"),
229                    cl::init(FloatABI::Default),
230                    cl::values(
231                      clEnumValN(FloatABI::Default, "default",
232                                 "Target default float ABI type"),
233                      clEnumValN(FloatABI::Soft, "soft",
234                                 "Soft float ABI (implied by -soft-float)"),
235                      clEnumValN(FloatABI::Hard, "hard",
236                                 "Hard float ABI (uses FP registers)"),
237                      clEnumValEnd));
238 }
239
240 //===----------------------------------------------------------------------===//
241 // Object cache
242 //
243 // This object cache implementation writes cached objects to disk to the
244 // directory specified by CacheDir, using a filename provided in the module
245 // descriptor. The cache tries to load a saved object using that path if the
246 // file exists. CacheDir defaults to "", in which case objects are cached
247 // alongside their originating bitcodes.
248 //
249 class LLIObjectCache : public ObjectCache {
250 public:
251   LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
252     // Add trailing '/' to cache dir if necessary.
253     if (!this->CacheDir.empty() &&
254         this->CacheDir[this->CacheDir.size() - 1] != '/')
255       this->CacheDir += '/';
256   }
257   ~LLIObjectCache() override {}
258
259   void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
260     const std::string ModuleID = M->getModuleIdentifier();
261     std::string CacheName;
262     if (!getCacheFilename(ModuleID, CacheName))
263       return;
264     if (!CacheDir.empty()) { // Create user-defined cache dir.
265       SmallString<128> dir(CacheName);
266       sys::path::remove_filename(dir);
267       sys::fs::create_directories(Twine(dir));
268     }
269     std::error_code EC;
270     raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
271     outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
272     outfile.close();
273   }
274
275   std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
276     const std::string ModuleID = M->getModuleIdentifier();
277     std::string CacheName;
278     if (!getCacheFilename(ModuleID, CacheName))
279       return nullptr;
280     // Load the object from the cache filename
281     ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
282         MemoryBuffer::getFile(CacheName.c_str(), -1, false);
283     // If the file isn't there, that's OK.
284     if (!IRObjectBuffer)
285       return nullptr;
286     // MCJIT will want to write into this buffer, and we don't want that
287     // because the file has probably just been mmapped.  Instead we make
288     // a copy.  The filed-based buffer will be released when it goes
289     // out of scope.
290     return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
291   }
292
293 private:
294   std::string CacheDir;
295
296   bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
297     std::string Prefix("file:");
298     size_t PrefixLength = Prefix.length();
299     if (ModID.substr(0, PrefixLength) != Prefix)
300       return false;
301         std::string CacheSubdir = ModID.substr(PrefixLength);
302 #if defined(_WIN32)
303         // Transform "X:\foo" => "/X\foo" for convenience.
304         if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
305           CacheSubdir[1] = CacheSubdir[0];
306           CacheSubdir[0] = '/';
307         }
308 #endif
309     CacheName = CacheDir + CacheSubdir;
310     size_t pos = CacheName.rfind('.');
311     CacheName.replace(pos, CacheName.length() - pos, ".o");
312     return true;
313   }
314 };
315
316 static ExecutionEngine *EE = nullptr;
317 static LLIObjectCache *CacheManager = nullptr;
318
319 static void do_shutdown() {
320   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
321 #ifndef DO_NOTHING_ATEXIT
322   delete EE;
323   if (CacheManager)
324     delete CacheManager;
325   llvm_shutdown();
326 #endif
327 }
328
329 // On Mingw and Cygwin, an external symbol named '__main' is called from the
330 // generated 'main' function to allow static intialization.  To avoid linking
331 // problems with remote targets (because lli's remote target support does not
332 // currently handle external linking) we add a secondary module which defines
333 // an empty '__main' function.
334 static void addCygMingExtraModule(ExecutionEngine *EE,
335                                   LLVMContext &Context,
336                                   StringRef TargetTripleStr) {
337   IRBuilder<> Builder(Context);
338   Triple TargetTriple(TargetTripleStr);
339
340   // Create a new module.
341   std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
342   M->setTargetTriple(TargetTripleStr);
343
344   // Create an empty function named "__main".
345   Function *Result;
346   if (TargetTriple.isArch64Bit()) {
347     Result = Function::Create(
348       TypeBuilder<int64_t(void), false>::get(Context),
349       GlobalValue::ExternalLinkage, "__main", M.get());
350   } else {
351     Result = Function::Create(
352       TypeBuilder<int32_t(void), false>::get(Context),
353       GlobalValue::ExternalLinkage, "__main", M.get());
354   }
355   BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
356   Builder.SetInsertPoint(BB);
357   Value *ReturnVal;
358   if (TargetTriple.isArch64Bit())
359     ReturnVal = ConstantInt::get(Context, APInt(64, 0));
360   else
361     ReturnVal = ConstantInt::get(Context, APInt(32, 0));
362   Builder.CreateRet(ReturnVal);
363
364   // Add this new module to the ExecutionEngine.
365   EE->addModule(std::move(M));
366 }
367
368
369 //===----------------------------------------------------------------------===//
370 // main Driver function
371 //
372 int main(int argc, char **argv, char * const *envp) {
373   sys::PrintStackTraceOnErrorSignal();
374   PrettyStackTraceProgram X(argc, argv);
375
376   LLVMContext &Context = getGlobalContext();
377   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
378
379   // If we have a native target, initialize it to ensure it is linked in and
380   // usable by the JIT.
381   InitializeNativeTarget();
382   InitializeNativeTargetAsmPrinter();
383   InitializeNativeTargetAsmParser();
384
385   cl::ParseCommandLineOptions(argc, argv,
386                               "llvm interpreter & dynamic compiler\n");
387
388   // If the user doesn't want core files, disable them.
389   if (DisableCoreFiles)
390     sys::Process::PreventCoreFiles();
391
392   // Load the bitcode...
393   SMDiagnostic Err;
394   std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
395   Module *Mod = Owner.get();
396   if (!Mod) {
397     Err.print(argv[0], errs());
398     return 1;
399   }
400
401   if (UseJITKind == JITKind::OrcLazy)
402     return runOrcLazyJIT(std::move(Owner), argc, argv);
403
404   if (EnableCacheManager) {
405     std::string CacheName("file:");
406     CacheName.append(InputFile);
407     Mod->setModuleIdentifier(CacheName);
408   }
409
410   // If not jitting lazily, load the whole bitcode file eagerly too.
411   if (NoLazyCompilation) {
412     if (std::error_code EC = Mod->materializeAllPermanently()) {
413       errs() << argv[0] << ": bitcode didn't read correctly.\n";
414       errs() << "Reason: " << EC.message() << "\n";
415       exit(1);
416     }
417   }
418
419   std::string ErrorMsg;
420   EngineBuilder builder(std::move(Owner));
421   builder.setMArch(MArch);
422   builder.setMCPU(MCPU);
423   builder.setMAttrs(MAttrs);
424   builder.setRelocationModel(RelocModel);
425   builder.setCodeModel(CMModel);
426   builder.setErrorStr(&ErrorMsg);
427   builder.setEngineKind(ForceInterpreter
428                         ? EngineKind::Interpreter
429                         : EngineKind::JIT);
430   builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
431
432   // If we are supposed to override the target triple, do so now.
433   if (!TargetTriple.empty())
434     Mod->setTargetTriple(Triple::normalize(TargetTriple));
435
436   // Enable MCJIT if desired.
437   RTDyldMemoryManager *RTDyldMM = nullptr;
438   if (!ForceInterpreter) {
439     if (RemoteMCJIT)
440       RTDyldMM = new RemoteMemoryManager();
441     else
442       RTDyldMM = new SectionMemoryManager();
443
444     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
445     // RTDyldMM: We still use it below, even though we don't own it.
446     builder.setMCJITMemoryManager(
447       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
448   } else if (RemoteMCJIT) {
449     errs() << "error: Remote process execution does not work with the "
450               "interpreter.\n";
451     exit(1);
452   }
453
454   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
455   switch (OptLevel) {
456   default:
457     errs() << argv[0] << ": invalid optimization level.\n";
458     return 1;
459   case ' ': break;
460   case '0': OLvl = CodeGenOpt::None; break;
461   case '1': OLvl = CodeGenOpt::Less; break;
462   case '2': OLvl = CodeGenOpt::Default; break;
463   case '3': OLvl = CodeGenOpt::Aggressive; break;
464   }
465   builder.setOptLevel(OLvl);
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   if (!RemoteMCJIT) {
585     // If the program doesn't explicitly call exit, we will need the Exit
586     // function later on to make an explicit call, so get the function now.
587     Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
588                                                       Type::getInt32Ty(Context),
589                                                       nullptr);
590
591     // Run static constructors.
592     if (!ForceInterpreter) {
593       // Give MCJIT a chance to apply relocations and set page permissions.
594       EE->finalizeObject();
595     }
596     EE->runStaticConstructorsDestructors(false);
597
598     // Trigger compilation separately so code regions that need to be
599     // invalidated will be known.
600     (void)EE->getPointerToFunction(EntryFn);
601     // Clear instruction cache before code will be executed.
602     if (RTDyldMM)
603       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
604
605     // Run main.
606     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
607
608     // Run static destructors.
609     EE->runStaticConstructorsDestructors(true);
610
611     // If the program didn't call exit explicitly, we should call it now.
612     // This ensures that any atexit handlers get called correctly.
613     if (Function *ExitF = dyn_cast<Function>(Exit)) {
614       std::vector<GenericValue> Args;
615       GenericValue ResultGV;
616       ResultGV.IntVal = APInt(32, Result);
617       Args.push_back(ResultGV);
618       EE->runFunction(ExitF, Args);
619       errs() << "ERROR: exit(" << Result << ") returned!\n";
620       abort();
621     } else {
622       errs() << "ERROR: exit defined with wrong prototype!\n";
623       abort();
624     }
625   } else {
626     // else == "if (RemoteMCJIT)"
627
628     // Remote target MCJIT doesn't (yet) support static constructors. No reason
629     // it couldn't. This is a limitation of the LLI implemantation, not the
630     // MCJIT itself. FIXME.
631     //
632     RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
633     // Everything is prepared now, so lay out our program for the target
634     // address space, assign the section addresses to resolve any relocations,
635     // and send it to the target.
636
637     std::unique_ptr<RemoteTarget> Target;
638     if (!ChildExecPath.empty()) { // Remote execution on a child process
639 #ifndef LLVM_ON_UNIX
640       // FIXME: Remove this pointless fallback mode which causes tests to "pass"
641       // on platforms where they should XFAIL.
642       errs() << "Warning: host does not support external remote targets.\n"
643              << "  Defaulting to simulated remote execution\n";
644       Target.reset(new RemoteTarget);
645 #else
646       if (!sys::fs::can_execute(ChildExecPath)) {
647         errs() << "Unable to find usable child executable: '" << ChildExecPath
648                << "'\n";
649         return -1;
650       }
651       Target.reset(new RemoteTargetExternal(ChildExecPath));
652 #endif
653     } else {
654       // No child process name provided, use simulated remote execution.
655       Target.reset(new RemoteTarget);
656     }
657
658     // Give the memory manager a pointer to our remote target interface object.
659     MM->setRemoteTarget(Target.get());
660
661     // Create the remote target.
662     if (!Target->create()) {
663       errs() << "ERROR: " << Target->getErrorMsg() << "\n";
664       return EXIT_FAILURE;
665     }
666
667     // Since we're executing in a (at least simulated) remote address space,
668     // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
669     // grab the function address directly here and tell the remote target
670     // to execute the function.
671     //
672     // Our memory manager will map generated code into the remote address
673     // space as it is loaded and copy the bits over during the finalizeMemory
674     // operation.
675     //
676     // FIXME: argv and envp handling.
677     uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
678
679     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
680                  << format("%llx", Entry) << "\n");
681
682     if (!Target->executeCode(Entry, Result))
683       errs() << "ERROR: " << Target->getErrorMsg() << "\n";
684
685     // Like static constructors, the remote target MCJIT support doesn't handle
686     // this yet. It could. FIXME.
687
688     // Stop the remote target
689     Target->stop();
690   }
691
692   return Result;
693 }