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