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