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 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/Type.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/ExecutionEngine/Interpreter.h"
24 #include "llvm/ExecutionEngine/JIT.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/ExecutionEngine/JITMemoryManager.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/Process.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/DynamicLibrary.h"
39 #include "llvm/Support/Memory.h"
43 // These includes used by LLIMCJITMemoryManager::getPointerToNamedFunction()
44 // for Glibc trickery. Look comments in this function for more information.
45 #ifdef HAVE_SYS_STAT_H
53 #include <cygwin/version.h>
54 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
55 #define DO_NOTHING_ATEXIT 1
63 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
66 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
68 cl::opt<bool> ForceInterpreter("force-interpreter",
69 cl::desc("Force interpretation: disable JIT"),
72 cl::opt<bool> UseMCJIT(
73 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
76 // Determine optimization level.
79 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
86 TargetTriple("mtriple", cl::desc("Override target triple for module"));
90 cl::desc("Architecture to generate assembly for (see --version)"));
94 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
95 cl::value_desc("cpu-name"),
101 cl::desc("Target specific attributes (-mattr=help for details)"),
102 cl::value_desc("a1,+a2,-a3,..."));
105 EntryFunc("entry-function",
106 cl::desc("Specify the entry function (default = 'main') "
107 "of the executable"),
108 cl::value_desc("function"),
112 FakeArgv0("fake-argv0",
113 cl::desc("Override the 'argv[0]' value passed into the executing"
114 " program"), cl::value_desc("executable"));
117 DisableCoreFiles("disable-core-files", cl::Hidden,
118 cl::desc("Disable emission of core files if possible"));
121 NoLazyCompilation("disable-lazy-compilation",
122 cl::desc("Disable JIT lazy compilation"),
125 cl::opt<Reloc::Model>
126 RelocModel("relocation-model",
127 cl::desc("Choose relocation model"),
128 cl::init(Reloc::Default),
130 clEnumValN(Reloc::Default, "default",
131 "Target default relocation model"),
132 clEnumValN(Reloc::Static, "static",
133 "Non-relocatable code"),
134 clEnumValN(Reloc::PIC_, "pic",
135 "Fully relocatable, position independent code"),
136 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
137 "Relocatable external references, non-relocatable code"),
140 cl::opt<llvm::CodeModel::Model>
141 CMModel("code-model",
142 cl::desc("Choose code model"),
143 cl::init(CodeModel::JITDefault),
144 cl::values(clEnumValN(CodeModel::JITDefault, "default",
145 "Target default JIT code model"),
146 clEnumValN(CodeModel::Small, "small",
148 clEnumValN(CodeModel::Kernel, "kernel",
149 "Kernel code model"),
150 clEnumValN(CodeModel::Medium, "medium",
151 "Medium code model"),
152 clEnumValN(CodeModel::Large, "large",
157 EnableJITExceptionHandling("jit-enable-eh",
158 cl::desc("Emit exception handling information"),
162 // In debug builds, make this default to true.
164 #define EMIT_DEBUG false
166 #define EMIT_DEBUG true
168 EmitJitDebugInfo("jit-emit-debug",
169 cl::desc("Emit debug information to debugger"),
170 cl::init(EMIT_DEBUG));
174 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
176 cl::desc("Emit debug info objfiles to disk"),
180 static ExecutionEngine *EE = 0;
182 static void do_shutdown() {
183 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
184 #ifndef DO_NOTHING_ATEXIT
190 // Memory manager for MCJIT
191 class LLIMCJITMemoryManager : public JITMemoryManager {
193 SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
194 SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
195 SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
197 LLIMCJITMemoryManager() { }
198 ~LLIMCJITMemoryManager();
200 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
203 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
206 virtual void *getPointerToNamedFunction(const std::string &Name,
207 bool AbortOnFailure = true);
209 // Invalidate instruction cache for code sections. Some platforms with
210 // separate data cache and instruction cache require explicit cache flush,
211 // otherwise JIT code manipulations (like resolved relocations) will get to
212 // the data cache but not to the instruction cache.
213 virtual void invalidateInstructionCache();
215 // The MCJITMemoryManager doesn't use the following functions, so we don't
216 // need implement them.
217 virtual void setMemoryWritable() {
218 llvm_unreachable("Unexpected call!");
220 virtual void setMemoryExecutable() {
221 llvm_unreachable("Unexpected call!");
223 virtual void setPoisonMemory(bool poison) {
224 llvm_unreachable("Unexpected call!");
226 virtual void AllocateGOT() {
227 llvm_unreachable("Unexpected call!");
229 virtual uint8_t *getGOTBase() const {
230 llvm_unreachable("Unexpected call!");
233 virtual uint8_t *startFunctionBody(const Function *F,
234 uintptr_t &ActualSize){
235 llvm_unreachable("Unexpected call!");
238 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
239 unsigned Alignment) {
240 llvm_unreachable("Unexpected call!");
243 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
244 uint8_t *FunctionEnd) {
245 llvm_unreachable("Unexpected call!");
247 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
248 llvm_unreachable("Unexpected call!");
251 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
252 llvm_unreachable("Unexpected call!");
255 virtual void deallocateFunctionBody(void *Body) {
256 llvm_unreachable("Unexpected call!");
258 virtual uint8_t* startExceptionTable(const Function* F,
259 uintptr_t &ActualSize) {
260 llvm_unreachable("Unexpected call!");
263 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
264 uint8_t *TableEnd, uint8_t* FrameRegister) {
265 llvm_unreachable("Unexpected call!");
267 virtual void deallocateExceptionTable(void *ET) {
268 llvm_unreachable("Unexpected call!");
272 uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
274 unsigned SectionID) {
277 uint8_t *Addr = (uint8_t*)calloc((Size + Alignment - 1)/Alignment, Alignment);
278 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, Size));
282 uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
284 unsigned SectionID) {
287 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
289 // Look in the list of free code memory regions and use a block there if one
291 for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
292 sys::MemoryBlock &MB = FreeCodeMem[i];
293 if (MB.size() >= NeedAllocate) {
294 Addr = (uintptr_t)MB.base();
295 uintptr_t EndOfBlock = Addr + MB.size();
296 // Align the address.
297 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
298 // Store cutted free memory block.
299 FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
300 EndOfBlock - Addr - Size);
301 return (uint8_t*)Addr;
305 // No pre-allocated free block was large enough. Allocate a new memory region.
306 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
308 AllocatedCodeMem.push_back(MB);
309 Addr = (uintptr_t)MB.base();
310 uintptr_t EndOfBlock = Addr + MB.size();
311 // Align the address.
312 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
313 // The AllocateRWX may allocate much more memory than we need. In this case,
314 // we store the unused memory as a free memory block.
315 unsigned FreeSize = EndOfBlock-Addr-Size;
317 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
319 // Return aligned address
320 return (uint8_t*)Addr;
323 void LLIMCJITMemoryManager::invalidateInstructionCache() {
324 for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
325 sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
326 AllocatedCodeMem[i].size());
329 void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
330 bool AbortOnFailure) {
331 #if defined(__linux__)
332 //===--------------------------------------------------------------------===//
333 // Function stubs that are invoked instead of certain library calls
335 // Force the following functions to be linked in to anything that uses the
336 // JIT. This is a hack designed to work around the all-too-clever Glibc
337 // strategy of making these functions work differently when inlined vs. when
338 // not inlined, and hiding their real definitions in a separate archive file
339 // that the dynamic linker can't see. For more info, search for
340 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
341 if (Name == "stat") return (void*)(intptr_t)&stat;
342 if (Name == "fstat") return (void*)(intptr_t)&fstat;
343 if (Name == "lstat") return (void*)(intptr_t)&lstat;
344 if (Name == "stat64") return (void*)(intptr_t)&stat64;
345 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
346 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
347 if (Name == "atexit") return (void*)(intptr_t)&atexit;
348 if (Name == "mknod") return (void*)(intptr_t)&mknod;
351 const char *NameStr = Name.c_str();
352 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
355 // If it wasn't found and if it starts with an underscore ('_') character,
356 // try again without the underscore.
357 if (NameStr[0] == '_') {
358 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
363 report_fatal_error("Program used external function '" + Name +
364 "' which could not be resolved!");
368 LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
369 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
370 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
371 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
372 free(AllocatedDataMem[i].base());
375 //===----------------------------------------------------------------------===//
376 // main Driver function
378 int main(int argc, char **argv, char * const *envp) {
379 sys::PrintStackTraceOnErrorSignal();
380 PrettyStackTraceProgram X(argc, argv);
382 LLVMContext &Context = getGlobalContext();
383 atexit(do_shutdown); // Call llvm_shutdown() on exit.
385 // If we have a native target, initialize it to ensure it is linked in and
386 // usable by the JIT.
387 InitializeNativeTarget();
388 InitializeNativeTargetAsmPrinter();
390 cl::ParseCommandLineOptions(argc, argv,
391 "llvm interpreter & dynamic compiler\n");
393 // If the user doesn't want core files, disable them.
394 if (DisableCoreFiles)
395 sys::Process::PreventCoreFiles();
397 // Load the bitcode...
399 Module *Mod = ParseIRFile(InputFile, Err, Context);
401 Err.print(argv[0], errs());
405 // If not jitting lazily, load the whole bitcode file eagerly too.
406 std::string ErrorMsg;
407 if (NoLazyCompilation) {
408 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
409 errs() << argv[0] << ": bitcode didn't read correctly.\n";
410 errs() << "Reason: " << ErrorMsg << "\n";
415 EngineBuilder builder(Mod);
416 builder.setMArch(MArch);
417 builder.setMCPU(MCPU);
418 builder.setMAttrs(MAttrs);
419 builder.setRelocationModel(RelocModel);
420 builder.setCodeModel(CMModel);
421 builder.setErrorStr(&ErrorMsg);
422 builder.setEngineKind(ForceInterpreter
423 ? EngineKind::Interpreter
426 // If we are supposed to override the target triple, do so now.
427 if (!TargetTriple.empty())
428 Mod->setTargetTriple(Triple::normalize(TargetTriple));
430 // Enable MCJIT if desired.
431 LLIMCJITMemoryManager *JMM = 0;
432 if (UseMCJIT && !ForceInterpreter) {
433 builder.setUseMCJIT(true);
434 JMM = new LLIMCJITMemoryManager();
435 builder.setJITMemoryManager(JMM);
437 builder.setJITMemoryManager(ForceInterpreter ? 0 :
438 JITMemoryManager::CreateDefaultMemManager());
441 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
444 errs() << argv[0] << ": invalid optimization level.\n";
447 case '0': OLvl = CodeGenOpt::None; break;
448 case '1': OLvl = CodeGenOpt::Less; break;
449 case '2': OLvl = CodeGenOpt::Default; break;
450 case '3': OLvl = CodeGenOpt::Aggressive; break;
452 builder.setOptLevel(OLvl);
454 TargetOptions Options;
455 Options.JITExceptionHandling = EnableJITExceptionHandling;
456 Options.JITEmitDebugInfo = EmitJitDebugInfo;
457 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
458 builder.setTargetOptions(Options);
460 EE = builder.create();
462 if (!ErrorMsg.empty())
463 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
465 errs() << argv[0] << ": unknown error creating EE!\n";
469 // Clear instruction cache before code will be executed.
471 JMM->invalidateInstructionCache();
473 // The following functions have no effect if their respective profiling
474 // support wasn't enabled in the build configuration.
475 EE->RegisterJITEventListener(
476 JITEventListener::createOProfileJITEventListener());
477 EE->RegisterJITEventListener(
478 JITEventListener::createIntelJITEventListener());
480 EE->DisableLazyCompilation(NoLazyCompilation);
482 // If the user specifically requested an argv[0] to pass into the program,
484 if (!FakeArgv0.empty()) {
485 InputFile = FakeArgv0;
487 // Otherwise, if there is a .bc suffix on the executable strip it off, it
488 // might confuse the program.
489 if (StringRef(InputFile).endswith(".bc"))
490 InputFile.erase(InputFile.length() - 3);
493 // Add the module's name to the start of the vector of arguments to main().
494 InputArgv.insert(InputArgv.begin(), InputFile);
496 // Call the main function from M as if its signature were:
497 // int main (int argc, char **argv, const char **envp)
498 // using the contents of Args to determine argc & argv, and the contents of
499 // EnvVars to determine envp.
501 Function *EntryFn = Mod->getFunction(EntryFunc);
503 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
507 // If the program doesn't explicitly call exit, we will need the Exit
508 // function later on to make an explicit call, so get the function now.
509 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
510 Type::getInt32Ty(Context),
513 // Reset errno to zero on entry to main.
516 // Run static constructors.
517 EE->runStaticConstructorsDestructors(false);
519 if (NoLazyCompilation) {
520 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
522 if (Fn != EntryFn && !Fn->isDeclaration())
523 EE->getPointerToFunction(Fn);
528 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
530 // Run static destructors.
531 EE->runStaticConstructorsDestructors(true);
533 // If the program didn't call exit explicitly, we should call it now.
534 // This ensures that any atexit handlers get called correctly.
535 if (Function *ExitF = dyn_cast<Function>(Exit)) {
536 std::vector<GenericValue> Args;
537 GenericValue ResultGV;
538 ResultGV.IntVal = APInt(32, Result);
539 Args.push_back(ResultGV);
540 EE->runFunction(ExitF, Args);
541 errs() << "ERROR: exit(" << Result << ") returned!\n";
544 errs() << "ERROR: exit defined with wrong prototype!\n";