1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
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
59 #include <cygwin/version.h>
60 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
61 #define DO_NOTHING_ATEXIT 1
69 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
72 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
74 cl::opt<bool> ForceInterpreter("force-interpreter",
75 cl::desc("Force interpretation: disable JIT"),
78 cl::opt<bool> UseMCJIT(
79 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
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."),
89 // Determine optimization level.
92 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
99 TargetTriple("mtriple", cl::desc("Override target triple for module"));
103 cl::desc("Architecture to generate assembly for (see --version)"));
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
111 cl::list<std::string>
114 cl::desc("Target specific attributes (-mattr=help for details)"),
115 cl::value_desc("a1,+a2,-a3,..."));
118 EntryFunc("entry-function",
119 cl::desc("Specify the entry function (default = 'main') "
120 "of the executable"),
121 cl::value_desc("function"),
125 FakeArgv0("fake-argv0",
126 cl::desc("Override the 'argv[0]' value passed into the executing"
127 " program"), cl::value_desc("executable"));
130 DisableCoreFiles("disable-core-files", cl::Hidden,
131 cl::desc("Disable emission of core files if possible"));
134 NoLazyCompilation("disable-lazy-compilation",
135 cl::desc("Disable JIT lazy compilation"),
138 cl::opt<Reloc::Model>
139 RelocModel("relocation-model",
140 cl::desc("Choose relocation model"),
141 cl::init(Reloc::Default),
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"),
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",
161 clEnumValN(CodeModel::Kernel, "kernel",
162 "Kernel code model"),
163 clEnumValN(CodeModel::Medium, "medium",
164 "Medium code model"),
165 clEnumValN(CodeModel::Large, "large",
170 EnableJITExceptionHandling("jit-enable-eh",
171 cl::desc("Emit exception handling information"),
175 GenerateSoftFloatCalls("soft-float",
176 cl::desc("Generate software floating point library calls"),
179 cl::opt<llvm::FloatABI::ABIType>
180 FloatABIForCalls("float-abi",
181 cl::desc("Choose float ABI type"),
182 cl::init(FloatABI::Default),
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)"),
192 // In debug builds, make this default to true.
194 #define EMIT_DEBUG false
196 #define EMIT_DEBUG true
198 EmitJitDebugInfo("jit-emit-debug",
199 cl::desc("Emit debug information to debugger"),
200 cl::init(EMIT_DEBUG));
204 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
206 cl::desc("Emit debug info objfiles to disk"),
210 static ExecutionEngine *EE = 0;
212 static void do_shutdown() {
213 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
214 #ifndef DO_NOTHING_ATEXIT
220 // Memory manager for MCJIT
221 class LLIMCJITMemoryManager : public JITMemoryManager {
223 SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
224 SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
225 SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
227 LLIMCJITMemoryManager() { }
228 ~LLIMCJITMemoryManager();
230 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
233 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
236 virtual void *getPointerToNamedFunction(const std::string &Name,
237 bool AbortOnFailure = true);
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();
245 // The RTDyldMemoryManager doesn't use the following functions, so we don't
246 // need implement them.
247 virtual void setMemoryWritable() {
248 llvm_unreachable("Unexpected call!");
250 virtual void setMemoryExecutable() {
251 llvm_unreachable("Unexpected call!");
253 virtual void setPoisonMemory(bool poison) {
254 llvm_unreachable("Unexpected call!");
256 virtual void AllocateGOT() {
257 llvm_unreachable("Unexpected call!");
259 virtual uint8_t *getGOTBase() const {
260 llvm_unreachable("Unexpected call!");
263 virtual uint8_t *startFunctionBody(const Function *F,
264 uintptr_t &ActualSize){
265 llvm_unreachable("Unexpected call!");
268 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
269 unsigned Alignment) {
270 llvm_unreachable("Unexpected call!");
273 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
274 uint8_t *FunctionEnd) {
275 llvm_unreachable("Unexpected call!");
277 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
278 llvm_unreachable("Unexpected call!");
281 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
282 llvm_unreachable("Unexpected call!");
285 virtual void deallocateFunctionBody(void *Body) {
286 llvm_unreachable("Unexpected call!");
288 virtual uint8_t* startExceptionTable(const Function* F,
289 uintptr_t &ActualSize) {
290 llvm_unreachable("Unexpected call!");
293 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
294 uint8_t *TableEnd, uint8_t* FrameRegister) {
295 llvm_unreachable("Unexpected call!");
297 virtual void deallocateExceptionTable(void *ET) {
298 llvm_unreachable("Unexpected call!");
302 uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
304 unsigned SectionID) {
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);
311 // Honour the alignment requirement.
312 uint8_t *AlignedAddr = (uint8_t*)RoundUpToAlignment((uint64_t)Addr, Alignment);
314 // Store the original address from calloc so we can free it later.
315 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, NumElementsAligned*Alignment));
319 uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
321 unsigned SectionID) {
324 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
326 // Look in the list of free code memory regions and use a block there if one
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;
342 // No pre-allocated free block was large enough. Allocate a new memory region.
343 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
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;
354 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
356 // Return aligned address
357 return (uint8_t*)Addr;
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());
366 static int jit_noop() {
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
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;
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;
400 const char *NameStr = Name.c_str();
401 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
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);
412 report_fatal_error("Program used external function '" + Name +
413 "' which could not be resolved!");
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());
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(),
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
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();
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(),
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
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();
464 // Allocate space in the remote target.
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);
474 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
475 << " to remote: " << format("%p", Addr) << "\n");
479 // Trigger application of relocations
480 EE->finalizeObject();
482 // Now load it all to the target.
483 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
484 uint64_t Addr = RemoteAddr + Offsets[i].second;
486 if (i < FirstDataIndex) {
487 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
489 DEBUG(dbgs() << " loading code: " << Offsets[i].first
490 << " to remote: " << format("%p", Addr) << "\n");
492 T->loadData(Addr, Offsets[i].first, Sizes[i]);
494 DEBUG(dbgs() << " loading data: " << Offsets[i].first
495 << " to remote: " << format("%p", Addr) << "\n");
501 //===----------------------------------------------------------------------===//
502 // main Driver function
504 int main(int argc, char **argv, char * const *envp) {
505 sys::PrintStackTraceOnErrorSignal();
506 PrettyStackTraceProgram X(argc, argv);
508 LLVMContext &Context = getGlobalContext();
509 atexit(do_shutdown); // Call llvm_shutdown() on exit.
511 // If we have a native target, initialize it to ensure it is linked in and
512 // usable by the JIT.
513 InitializeNativeTarget();
514 InitializeNativeTargetAsmPrinter();
515 InitializeNativeTargetAsmParser();
517 cl::ParseCommandLineOptions(argc, argv,
518 "llvm interpreter & dynamic compiler\n");
520 // If the user doesn't want core files, disable them.
521 if (DisableCoreFiles)
522 sys::Process::PreventCoreFiles();
524 // Load the bitcode...
526 Module *Mod = ParseIRFile(InputFile, Err, Context);
528 Err.print(argv[0], errs());
532 // If not jitting lazily, load the whole bitcode file eagerly too.
533 std::string ErrorMsg;
534 if (NoLazyCompilation) {
535 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
536 errs() << argv[0] << ": bitcode didn't read correctly.\n";
537 errs() << "Reason: " << ErrorMsg << "\n";
542 EngineBuilder builder(Mod);
543 builder.setMArch(MArch);
544 builder.setMCPU(MCPU);
545 builder.setMAttrs(MAttrs);
546 builder.setRelocationModel(RelocModel);
547 builder.setCodeModel(CMModel);
548 builder.setErrorStr(&ErrorMsg);
549 builder.setEngineKind(ForceInterpreter
550 ? EngineKind::Interpreter
553 // If we are supposed to override the target triple, do so now.
554 if (!TargetTriple.empty())
555 Mod->setTargetTriple(Triple::normalize(TargetTriple));
557 // Enable MCJIT if desired.
558 JITMemoryManager *JMM = 0;
559 if (UseMCJIT && !ForceInterpreter) {
560 builder.setUseMCJIT(true);
562 JMM = new RecordingMemoryManager();
564 JMM = new LLIMCJITMemoryManager();
565 builder.setJITMemoryManager(JMM);
568 errs() << "error: Remote process execution requires -use-mcjit\n";
571 builder.setJITMemoryManager(ForceInterpreter ? 0 :
572 JITMemoryManager::CreateDefaultMemManager());
575 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
578 errs() << argv[0] << ": invalid optimization level.\n";
581 case '0': OLvl = CodeGenOpt::None; break;
582 case '1': OLvl = CodeGenOpt::Less; break;
583 case '2': OLvl = CodeGenOpt::Default; break;
584 case '3': OLvl = CodeGenOpt::Aggressive; break;
586 builder.setOptLevel(OLvl);
588 TargetOptions Options;
589 Options.UseSoftFloat = GenerateSoftFloatCalls;
590 if (FloatABIForCalls != FloatABI::Default)
591 Options.FloatABIType = FloatABIForCalls;
592 if (GenerateSoftFloatCalls)
593 FloatABIForCalls = FloatABI::Soft;
595 // Remote target execution doesn't handle EH or debug registration.
597 Options.JITExceptionHandling = EnableJITExceptionHandling;
598 Options.JITEmitDebugInfo = EmitJitDebugInfo;
599 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
602 builder.setTargetOptions(Options);
604 EE = builder.create();
606 if (!ErrorMsg.empty())
607 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
609 errs() << argv[0] << ": unknown error creating EE!\n";
613 // The following functions have no effect if their respective profiling
614 // support wasn't enabled in the build configuration.
615 EE->RegisterJITEventListener(
616 JITEventListener::createOProfileJITEventListener());
617 EE->RegisterJITEventListener(
618 JITEventListener::createIntelJITEventListener());
620 if (!NoLazyCompilation && RemoteMCJIT) {
621 errs() << "warning: remote mcjit does not support lazy compilation\n";
622 NoLazyCompilation = true;
624 EE->DisableLazyCompilation(NoLazyCompilation);
626 // If the user specifically requested an argv[0] to pass into the program,
628 if (!FakeArgv0.empty()) {
629 InputFile = FakeArgv0;
631 // Otherwise, if there is a .bc suffix on the executable strip it off, it
632 // might confuse the program.
633 if (StringRef(InputFile).endswith(".bc"))
634 InputFile.erase(InputFile.length() - 3);
637 // Add the module's name to the start of the vector of arguments to main().
638 InputArgv.insert(InputArgv.begin(), InputFile);
640 // Call the main function from M as if its signature were:
641 // int main (int argc, char **argv, const char **envp)
642 // using the contents of Args to determine argc & argv, and the contents of
643 // EnvVars to determine envp.
645 Function *EntryFn = Mod->getFunction(EntryFunc);
647 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
651 // If the program doesn't explicitly call exit, we will need the Exit
652 // function later on to make an explicit call, so get the function now.
653 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
654 Type::getInt32Ty(Context),
657 // Reset errno to zero on entry to main.
660 // Remote target MCJIT doesn't (yet) support static constructors. No reason
661 // it couldn't. This is a limitation of the LLI implemantation, not the
662 // MCJIT itself. FIXME.
664 // Run static constructors.
666 EE->runStaticConstructorsDestructors(false);
668 if (NoLazyCompilation) {
669 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
671 if (Fn != EntryFn && !Fn->isDeclaration())
672 EE->getPointerToFunction(Fn);
678 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
679 // Everything is prepared now, so lay out our program for the target
680 // address space, assign the section addresses to resolve any relocations,
681 // and send it to the target.
685 // Ask for a pointer to the entry function. This triggers the actual
687 (void)EE->getPointerToFunction(EntryFn);
689 // Enough has been compiled to execute the entry function now, so
690 // layout the target memory.
691 layoutRemoteTargetMemory(&Target, MM);
693 // Since we're executing in a (at least simulated) remote address space,
694 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
695 // grab the function address directly here and tell the remote target
696 // to execute the function.
697 // FIXME: argv and envp handling.
698 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
700 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
701 << format("%p", Entry) << "\n");
703 if (Target.executeCode(Entry, Result))
704 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
708 // Trigger compilation separately so code regions that need to be
709 // invalidated will be known.
710 (void)EE->getPointerToFunction(EntryFn);
711 // Clear instruction cache before code will be executed.
713 static_cast<LLIMCJITMemoryManager*>(JMM)->invalidateInstructionCache();
716 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
719 // Like static constructors, the remote target MCJIT support doesn't handle
720 // this yet. It could. FIXME.
722 // Run static destructors.
723 EE->runStaticConstructorsDestructors(true);
725 // If the program didn't call exit explicitly, we should call it now.
726 // This ensures that any atexit handlers get called correctly.
727 if (Function *ExitF = dyn_cast<Function>(Exit)) {
728 std::vector<GenericValue> Args;
729 GenericValue ResultGV;
730 ResultGV.IntVal = APInt(32, Result);
731 Args.push_back(ResultGV);
732 EE->runFunction(ExitF, Args);
733 errs() << "ERROR: exit(" << Result << ") returned!\n";
736 errs() << "ERROR: exit defined with wrong prototype!\n";