Fixed format strings to avoid pointer truncation during 64-bit debugging.
[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 "RecordingMemoryManager.h"
18 #include "RemoteTarget.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
25 #include "llvm/ExecutionEngine/GenericValue.h"
26 #include "llvm/ExecutionEngine/Interpreter.h"
27 #include "llvm/ExecutionEngine/JIT.h"
28 #include "llvm/ExecutionEngine/JITEventListener.h"
29 #include "llvm/ExecutionEngine/JITMemoryManager.h"
30 #include "llvm/ExecutionEngine/MCJIT.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/IRReader.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/PluginLoader.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/DynamicLibrary.h"
44 #include "llvm/Support/Memory.h"
45 #include "llvm/Support/MathExtras.h"
46 #include <cerrno>
47
48 #ifdef __linux__
49 // These includes used by LLIMCJITMemoryManager::getPointerToNamedFunction()
50 // for Glibc trickery. Look comments in this function for more information.
51 #ifdef HAVE_SYS_STAT_H
52 #include <sys/stat.h>
53 #endif
54 #include <fcntl.h>
55 #include <unistd.h>
56 #endif
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 namespace {
68   cl::opt<std::string>
69   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
70
71   cl::list<std::string>
72   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
73
74   cl::opt<bool> ForceInterpreter("force-interpreter",
75                                  cl::desc("Force interpretation: disable JIT"),
76                                  cl::init(false));
77
78   cl::opt<bool> UseMCJIT(
79     "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
80     cl::init(false));
81
82   // The MCJIT supports building for a target address space separate from
83   // the JIT compilation process. Use a forked process and a copying
84   // memory manager with IPC to execute using this functionality.
85   cl::opt<bool> RemoteMCJIT("remote-mcjit",
86     cl::desc("Execute MCJIT'ed code in a separate process."),
87     cl::init(false));
88
89   // Determine optimization level.
90   cl::opt<char>
91   OptLevel("O",
92            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
93                     "(default = '-O2')"),
94            cl::Prefix,
95            cl::ZeroOrMore,
96            cl::init(' '));
97
98   cl::opt<std::string>
99   TargetTriple("mtriple", cl::desc("Override target triple for module"));
100
101   cl::opt<std::string>
102   MArch("march",
103         cl::desc("Architecture to generate assembly for (see --version)"));
104
105   cl::opt<std::string>
106   MCPU("mcpu",
107        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108        cl::value_desc("cpu-name"),
109        cl::init(""));
110
111   cl::list<std::string>
112   MAttrs("mattr",
113          cl::CommaSeparated,
114          cl::desc("Target specific attributes (-mattr=help for details)"),
115          cl::value_desc("a1,+a2,-a3,..."));
116
117   cl::opt<std::string>
118   EntryFunc("entry-function",
119             cl::desc("Specify the entry function (default = 'main') "
120                      "of the executable"),
121             cl::value_desc("function"),
122             cl::init("main"));
123
124   cl::opt<std::string>
125   FakeArgv0("fake-argv0",
126             cl::desc("Override the 'argv[0]' value passed into the executing"
127                      " program"), cl::value_desc("executable"));
128
129   cl::opt<bool>
130   DisableCoreFiles("disable-core-files", cl::Hidden,
131                    cl::desc("Disable emission of core files if possible"));
132
133   cl::opt<bool>
134   NoLazyCompilation("disable-lazy-compilation",
135                   cl::desc("Disable JIT lazy compilation"),
136                   cl::init(false));
137
138   cl::opt<Reloc::Model>
139   RelocModel("relocation-model",
140              cl::desc("Choose relocation model"),
141              cl::init(Reloc::Default),
142              cl::values(
143             clEnumValN(Reloc::Default, "default",
144                        "Target default relocation model"),
145             clEnumValN(Reloc::Static, "static",
146                        "Non-relocatable code"),
147             clEnumValN(Reloc::PIC_, "pic",
148                        "Fully relocatable, position independent code"),
149             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
150                        "Relocatable external references, non-relocatable code"),
151             clEnumValEnd));
152
153   cl::opt<llvm::CodeModel::Model>
154   CMModel("code-model",
155           cl::desc("Choose code model"),
156           cl::init(CodeModel::JITDefault),
157           cl::values(clEnumValN(CodeModel::JITDefault, "default",
158                                 "Target default JIT code model"),
159                      clEnumValN(CodeModel::Small, "small",
160                                 "Small code model"),
161                      clEnumValN(CodeModel::Kernel, "kernel",
162                                 "Kernel code model"),
163                      clEnumValN(CodeModel::Medium, "medium",
164                                 "Medium code model"),
165                      clEnumValN(CodeModel::Large, "large",
166                                 "Large code model"),
167                      clEnumValEnd));
168
169   cl::opt<bool>
170   EnableJITExceptionHandling("jit-enable-eh",
171     cl::desc("Emit exception handling information"),
172     cl::init(false));
173
174   cl::opt<bool>
175   GenerateSoftFloatCalls("soft-float",
176     cl::desc("Generate software floating point library calls"),
177     cl::init(false));
178
179   cl::opt<llvm::FloatABI::ABIType>
180   FloatABIForCalls("float-abi",
181                    cl::desc("Choose float ABI type"),
182                    cl::init(FloatABI::Default),
183                    cl::values(
184                      clEnumValN(FloatABI::Default, "default",
185                                 "Target default float ABI type"),
186                      clEnumValN(FloatABI::Soft, "soft",
187                                 "Soft float ABI (implied by -soft-float)"),
188                      clEnumValN(FloatABI::Hard, "hard",
189                                 "Hard float ABI (uses FP registers)"),
190                      clEnumValEnd));
191   cl::opt<bool>
192 // In debug builds, make this default to true.
193 #ifdef NDEBUG
194 #define EMIT_DEBUG false
195 #else
196 #define EMIT_DEBUG true
197 #endif
198   EmitJitDebugInfo("jit-emit-debug",
199     cl::desc("Emit debug information to debugger"),
200     cl::init(EMIT_DEBUG));
201 #undef EMIT_DEBUG
202
203   static cl::opt<bool>
204   EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
205     cl::Hidden,
206     cl::desc("Emit debug info objfiles to disk"),
207     cl::init(false));
208 }
209
210 static ExecutionEngine *EE = 0;
211
212 static void do_shutdown() {
213   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
214 #ifndef DO_NOTHING_ATEXIT
215   delete EE;
216   llvm_shutdown();
217 #endif
218 }
219
220 // Memory manager for MCJIT
221 class LLIMCJITMemoryManager : public JITMemoryManager {
222 public:
223   SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
224   SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
225   SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
226
227   LLIMCJITMemoryManager() { }
228   ~LLIMCJITMemoryManager();
229
230   virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
231                                        unsigned SectionID);
232
233   virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
234                                        unsigned SectionID);
235
236   virtual void *getPointerToNamedFunction(const std::string &Name,
237                                           bool AbortOnFailure = true);
238
239   // Invalidate instruction cache for code sections. Some platforms with
240   // separate data cache and instruction cache require explicit cache flush,
241   // otherwise JIT code manipulations (like resolved relocations) will get to
242   // the data cache but not to the instruction cache.
243   virtual void invalidateInstructionCache();
244
245   // The MCJITMemoryManager doesn't use the following functions, so we don't
246   // need implement them.
247   virtual void setMemoryWritable() {
248     llvm_unreachable("Unexpected call!");
249   }
250   virtual void setMemoryExecutable() {
251     llvm_unreachable("Unexpected call!");
252   }
253   virtual void setPoisonMemory(bool poison) {
254     llvm_unreachable("Unexpected call!");
255   }
256   virtual void AllocateGOT() {
257     llvm_unreachable("Unexpected call!");
258   }
259   virtual uint8_t *getGOTBase() const {
260     llvm_unreachable("Unexpected call!");
261     return 0;
262   }
263   virtual uint8_t *startFunctionBody(const Function *F,
264                                      uintptr_t &ActualSize){
265     llvm_unreachable("Unexpected call!");
266     return 0;
267   }
268   virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
269                                 unsigned Alignment) {
270     llvm_unreachable("Unexpected call!");
271     return 0;
272   }
273   virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
274                                uint8_t *FunctionEnd) {
275     llvm_unreachable("Unexpected call!");
276   }
277   virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
278     llvm_unreachable("Unexpected call!");
279     return 0;
280   }
281   virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
282     llvm_unreachable("Unexpected call!");
283     return 0;
284   }
285   virtual void deallocateFunctionBody(void *Body) {
286     llvm_unreachable("Unexpected call!");
287   }
288   virtual uint8_t* startExceptionTable(const Function* F,
289                                        uintptr_t &ActualSize) {
290     llvm_unreachable("Unexpected call!");
291     return 0;
292   }
293   virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
294                                  uint8_t *TableEnd, uint8_t* FrameRegister) {
295     llvm_unreachable("Unexpected call!");
296   }
297   virtual void deallocateExceptionTable(void *ET) {
298     llvm_unreachable("Unexpected call!");
299   }
300 };
301
302 uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
303                                                     unsigned Alignment,
304                                                     unsigned SectionID) {
305   if (!Alignment)
306     Alignment = 16;
307   // Ensure that enough memory is requested to allow aligning.
308   size_t NumElementsAligned = 1 + (Size + Alignment - 1)/Alignment;
309   uint8_t *Addr = (uint8_t*)calloc(NumElementsAligned, Alignment);
310
311   // Honour the alignment requirement.
312   uint8_t *AlignedAddr = (uint8_t*)RoundUpToAlignment((uint64_t)Addr, Alignment);
313
314   // Store the original address from calloc so we can free it later.
315   AllocatedDataMem.push_back(sys::MemoryBlock(Addr, NumElementsAligned*Alignment));
316   return AlignedAddr;
317 }
318
319 uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
320                                                     unsigned Alignment,
321                                                     unsigned SectionID) {
322   if (!Alignment)
323     Alignment = 16;
324   unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
325   uintptr_t Addr = 0;
326   // Look in the list of free code memory regions and use a block there if one
327   // is available.
328   for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
329     sys::MemoryBlock &MB = FreeCodeMem[i];
330     if (MB.size() >= NeedAllocate) {
331       Addr = (uintptr_t)MB.base();
332       uintptr_t EndOfBlock = Addr + MB.size();
333       // Align the address.
334       Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
335       // Store cutted free memory block.
336       FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
337                                         EndOfBlock - Addr - Size);
338       return (uint8_t*)Addr;
339     }
340   }
341
342   // No pre-allocated free block was large enough. Allocate a new memory region.
343   sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
344
345   AllocatedCodeMem.push_back(MB);
346   Addr = (uintptr_t)MB.base();
347   uintptr_t EndOfBlock = Addr + MB.size();
348   // Align the address.
349   Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
350   // The AllocateRWX may allocate much more memory than we need. In this case,
351   // we store the unused memory as a free memory block.
352   unsigned FreeSize = EndOfBlock-Addr-Size;
353   if (FreeSize > 16)
354     FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
355
356   // Return aligned address
357   return (uint8_t*)Addr;
358 }
359
360 void LLIMCJITMemoryManager::invalidateInstructionCache() {
361   for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
362     sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
363                                             AllocatedCodeMem[i].size());
364 }
365
366 static int jit_noop() {
367   return 0;
368 }
369
370 void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
371                                                        bool AbortOnFailure) {
372 #if defined(__linux__)
373   //===--------------------------------------------------------------------===//
374   // Function stubs that are invoked instead of certain library calls
375   //
376   // Force the following functions to be linked in to anything that uses the
377   // JIT. This is a hack designed to work around the all-too-clever Glibc
378   // strategy of making these functions work differently when inlined vs. when
379   // not inlined, and hiding their real definitions in a separate archive file
380   // that the dynamic linker can't see. For more info, search for
381   // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
382   if (Name == "stat") return (void*)(intptr_t)&stat;
383   if (Name == "fstat") return (void*)(intptr_t)&fstat;
384   if (Name == "lstat") return (void*)(intptr_t)&lstat;
385   if (Name == "stat64") return (void*)(intptr_t)&stat64;
386   if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
387   if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
388   if (Name == "atexit") return (void*)(intptr_t)&atexit;
389   if (Name == "mknod") return (void*)(intptr_t)&mknod;
390 #endif // __linux__
391
392   // We should not invoke parent's ctors/dtors from generated main()!
393   // On Mingw and Cygwin, the symbol __main is resolved to
394   // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
395   // (and register wrong callee's dtors with atexit(3)).
396   // We expect ExecutionEngine::runStaticConstructorsDestructors()
397   // is called before ExecutionEngine::runFunctionAsMain() is called.
398   if (Name == "__main") return (void*)(intptr_t)&jit_noop;
399
400   const char *NameStr = Name.c_str();
401   void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
402   if (Ptr) return Ptr;
403
404   // If it wasn't found and if it starts with an underscore ('_') character,
405   // try again without the underscore.
406   if (NameStr[0] == '_') {
407     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
408     if (Ptr) return Ptr;
409   }
410
411   if (AbortOnFailure)
412     report_fatal_error("Program used external function '" + Name +
413                       "' which could not be resolved!");
414   return 0;
415 }
416
417 LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
418   for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
419     sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
420   for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
421     free(AllocatedDataMem[i].base());
422 }
423
424
425 void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
426   // Lay out our sections in order, with all the code sections first, then
427   // all the data sections.
428   uint64_t CurOffset = 0;
429   unsigned MaxAlign = T->getPageAlignment();
430   SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
431   SmallVector<unsigned, 16> Sizes;
432   for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
433                                                    E = JMM->code_end();
434        I != E; ++I) {
435     DEBUG(dbgs() << "code region: size " << I->first.size()
436                  << ", alignment " << I->second << "\n");
437     // Align the current offset up to whatever is needed for the next
438     // section.
439     unsigned Align = I->second;
440     CurOffset = (CurOffset + Align - 1) / Align * Align;
441     // Save off the address of the new section and allocate its space.
442     Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
443     Sizes.push_back(I->first.size());
444     CurOffset += I->first.size();
445   }
446   // Adjust to keep code and data aligned on seperate pages.
447   CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
448   unsigned FirstDataIndex = Offsets.size();
449   for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
450                                                    E = JMM->data_end();
451        I != E; ++I) {
452     DEBUG(dbgs() << "data region: size " << I->first.size()
453                  << ", alignment " << I->second << "\n");
454     // Align the current offset up to whatever is needed for the next
455     // section.
456     unsigned Align = I->second;
457     CurOffset = (CurOffset + Align - 1) / Align * Align;
458     // Save off the address of the new section and allocate its space.
459     Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
460     Sizes.push_back(I->first.size());
461     CurOffset += I->first.size();
462   }
463
464   // Allocate space in the remote target.
465   uint64_t RemoteAddr;
466   if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
467     report_fatal_error(T->getErrorMsg());
468   // Map the section addresses so relocations will get updated in the local
469   // copies of the sections.
470   for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
471     uint64_t Addr = RemoteAddr + Offsets[i].second;
472     EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
473
474     DEBUG(dbgs() << "  Mapping local: " << Offsets[i].first
475                  << " to remote: " << format("%p", Addr) << "\n");
476
477   }
478   // Now load it all to the target.
479   for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
480     uint64_t Addr = RemoteAddr + Offsets[i].second;
481
482     if (i < FirstDataIndex) {
483       T->loadCode(Addr, Offsets[i].first, Sizes[i]);
484
485       DEBUG(dbgs() << "  loading code: " << Offsets[i].first
486             << " to remote: " << format("%p", Addr) << "\n");
487     } else {
488       T->loadData(Addr, Offsets[i].first, Sizes[i]);
489
490       DEBUG(dbgs() << "  loading data: " << Offsets[i].first
491             << " to remote: " << format("%p", Addr) << "\n");
492     }
493
494   }
495 }
496
497 //===----------------------------------------------------------------------===//
498 // main Driver function
499 //
500 int main(int argc, char **argv, char * const *envp) {
501   sys::PrintStackTraceOnErrorSignal();
502   PrettyStackTraceProgram X(argc, argv);
503
504   LLVMContext &Context = getGlobalContext();
505   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
506
507   // If we have a native target, initialize it to ensure it is linked in and
508   // usable by the JIT.
509   InitializeNativeTarget();
510   InitializeNativeTargetAsmPrinter();
511
512   cl::ParseCommandLineOptions(argc, argv,
513                               "llvm interpreter & dynamic compiler\n");
514
515   // If the user doesn't want core files, disable them.
516   if (DisableCoreFiles)
517     sys::Process::PreventCoreFiles();
518
519   // Load the bitcode...
520   SMDiagnostic Err;
521   Module *Mod = ParseIRFile(InputFile, Err, Context);
522   if (!Mod) {
523     Err.print(argv[0], errs());
524     return 1;
525   }
526
527   // If not jitting lazily, load the whole bitcode file eagerly too.
528   std::string ErrorMsg;
529   if (NoLazyCompilation) {
530     if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
531       errs() << argv[0] << ": bitcode didn't read correctly.\n";
532       errs() << "Reason: " << ErrorMsg << "\n";
533       exit(1);
534     }
535   }
536
537   EngineBuilder builder(Mod);
538   builder.setMArch(MArch);
539   builder.setMCPU(MCPU);
540   builder.setMAttrs(MAttrs);
541   builder.setRelocationModel(RelocModel);
542   builder.setCodeModel(CMModel);
543   builder.setErrorStr(&ErrorMsg);
544   builder.setEngineKind(ForceInterpreter
545                         ? EngineKind::Interpreter
546                         : EngineKind::JIT);
547
548   // If we are supposed to override the target triple, do so now.
549   if (!TargetTriple.empty())
550     Mod->setTargetTriple(Triple::normalize(TargetTriple));
551
552   // Enable MCJIT if desired.
553   JITMemoryManager *JMM = 0;
554   if (UseMCJIT && !ForceInterpreter) {
555     builder.setUseMCJIT(true);
556     if (RemoteMCJIT)
557       JMM = new RecordingMemoryManager();
558     else
559       JMM = new LLIMCJITMemoryManager();
560     builder.setJITMemoryManager(JMM);
561   } else {
562     if (RemoteMCJIT) {
563       errs() << "error: Remote process execution requires -use-mcjit\n";
564       exit(1);
565     }
566     builder.setJITMemoryManager(ForceInterpreter ? 0 :
567                                 JITMemoryManager::CreateDefaultMemManager());
568   }
569
570   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
571   switch (OptLevel) {
572   default:
573     errs() << argv[0] << ": invalid optimization level.\n";
574     return 1;
575   case ' ': break;
576   case '0': OLvl = CodeGenOpt::None; break;
577   case '1': OLvl = CodeGenOpt::Less; break;
578   case '2': OLvl = CodeGenOpt::Default; break;
579   case '3': OLvl = CodeGenOpt::Aggressive; break;
580   }
581   builder.setOptLevel(OLvl);
582
583   TargetOptions Options;
584   Options.UseSoftFloat = GenerateSoftFloatCalls;
585   if (FloatABIForCalls != FloatABI::Default)
586     Options.FloatABIType = FloatABIForCalls;
587   if (GenerateSoftFloatCalls)
588     FloatABIForCalls = FloatABI::Soft;
589
590   // Remote target execution doesn't handle EH or debug registration.
591   if (!RemoteMCJIT) {
592     Options.JITExceptionHandling = EnableJITExceptionHandling;
593     Options.JITEmitDebugInfo = EmitJitDebugInfo;
594     Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
595   }
596
597   builder.setTargetOptions(Options);
598
599   EE = builder.create();
600   if (!EE) {
601     if (!ErrorMsg.empty())
602       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
603     else
604       errs() << argv[0] << ": unknown error creating EE!\n";
605     exit(1);
606   }
607
608   // The following functions have no effect if their respective profiling
609   // support wasn't enabled in the build configuration.
610   EE->RegisterJITEventListener(
611                 JITEventListener::createOProfileJITEventListener());
612   EE->RegisterJITEventListener(
613                 JITEventListener::createIntelJITEventListener());
614
615   if (!NoLazyCompilation && RemoteMCJIT) {
616     errs() << "warning: remote mcjit does not support lazy compilation\n";
617     NoLazyCompilation = true;
618   }
619   EE->DisableLazyCompilation(NoLazyCompilation);
620
621   // If the user specifically requested an argv[0] to pass into the program,
622   // do it now.
623   if (!FakeArgv0.empty()) {
624     InputFile = FakeArgv0;
625   } else {
626     // Otherwise, if there is a .bc suffix on the executable strip it off, it
627     // might confuse the program.
628     if (StringRef(InputFile).endswith(".bc"))
629       InputFile.erase(InputFile.length() - 3);
630   }
631
632   // Add the module's name to the start of the vector of arguments to main().
633   InputArgv.insert(InputArgv.begin(), InputFile);
634
635   // Call the main function from M as if its signature were:
636   //   int main (int argc, char **argv, const char **envp)
637   // using the contents of Args to determine argc & argv, and the contents of
638   // EnvVars to determine envp.
639   //
640   Function *EntryFn = Mod->getFunction(EntryFunc);
641   if (!EntryFn) {
642     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
643     return -1;
644   }
645
646   // If the program doesn't explicitly call exit, we will need the Exit
647   // function later on to make an explicit call, so get the function now.
648   Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
649                                                     Type::getInt32Ty(Context),
650                                                     NULL);
651
652   // Reset errno to zero on entry to main.
653   errno = 0;
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   // Run static constructors.
660   if (!RemoteMCJIT)
661     EE->runStaticConstructorsDestructors(false);
662
663   if (NoLazyCompilation) {
664     for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
665       Function *Fn = &*I;
666       if (Fn != EntryFn && !Fn->isDeclaration())
667         EE->getPointerToFunction(Fn);
668     }
669   }
670
671   int Result;
672   if (RemoteMCJIT) {
673     RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
674     // Everything is prepared now, so lay out our program for the target
675     // address space, assign the section addresses to resolve any relocations,
676     // and send it to the target.
677     RemoteTarget Target;
678     Target.create();
679
680     // Ask for a pointer to the entry function. This triggers the actual
681     // compilation.
682     (void)EE->getPointerToFunction(EntryFn);
683
684     // Enough has been compiled to execute the entry function now, so
685     // layout the target memory.
686     layoutRemoteTargetMemory(&Target, MM);
687
688     // Since we're executing in a (at least simulated) remote address space,
689     // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
690     // grab the function address directly here and tell the remote target
691     // to execute the function.
692     // FIXME: argv and envp handling.
693     uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
694
695     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
696                  << format("%p", Entry) << "\n");
697
698     if (Target.executeCode(Entry, Result))
699       errs() << "ERROR: " << Target.getErrorMsg() << "\n";
700
701     Target.stop();
702   } else {
703     // Trigger compilation separately so code regions that need to be 
704     // invalidated will be known.
705     (void)EE->getPointerToFunction(EntryFn);
706     // Clear instruction cache before code will be executed.
707     if (JMM)
708       static_cast<LLIMCJITMemoryManager*>(JMM)->invalidateInstructionCache();
709
710     // Run main.
711     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
712   }
713
714   // Like static constructors, the remote target MCJIT support doesn't handle
715   // this yet. It could. FIXME.
716   if (!RemoteMCJIT) {
717     // Run static destructors.
718     EE->runStaticConstructorsDestructors(true);
719
720     // If the program didn't call exit explicitly, we should call it now.
721     // This ensures that any atexit handlers get called correctly.
722     if (Function *ExitF = dyn_cast<Function>(Exit)) {
723       std::vector<GenericValue> Args;
724       GenericValue ResultGV;
725       ResultGV.IntVal = APInt(32, Result);
726       Args.push_back(ResultGV);
727       EE->runFunction(ExitF, Args);
728       errs() << "ERROR: exit(" << Result << ") returned!\n";
729       abort();
730     } else {
731       errs() << "ERROR: exit defined with wrong prototype!\n";
732       abort();
733     }
734   }
735   return Result;
736 }