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