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