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