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 "llvm/IR/LLVMContext.h"
18 #include "RemoteMemoryManager.h"
19 #include "RemoteTarget.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/ExecutionEngine/Interpreter.h"
25 #include "llvm/ExecutionEngine/JIT.h"
26 #include "llvm/ExecutionEngine/JITEventListener.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/MCJIT.h"
29 #include "llvm/ExecutionEngine/ObjectCache.h"
30 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/TypeBuilder.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/DynamicLibrary.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Memory.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/Program.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Transforms/Instrumentation.h"
58 #include <cygwin/version.h>
59 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
60 #define DO_NOTHING_ATEXIT 1
68 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
71 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
73 cl::opt<bool> ForceInterpreter("force-interpreter",
74 cl::desc("Force interpretation: disable JIT"),
77 cl::opt<bool> UseMCJIT(
78 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
81 cl::opt<bool> DebugIR(
82 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
85 // The MCJIT supports building for a target address space separate from
86 // the JIT compilation process. Use a forked process and a copying
87 // memory manager with IPC to execute using this functionality.
88 cl::opt<bool> RemoteMCJIT("remote-mcjit",
89 cl::desc("Execute MCJIT'ed code in a separate process."),
92 // Manually specify the child process for remote execution. This overrides
93 // the simulated remote execution that allocates address space for child
94 // execution. The child process will be executed and will communicate with
95 // lli via stdin/stdout pipes.
97 MCJITRemoteProcess("mcjit-remote-process",
98 cl::desc("Specify the filename of the process to launch "
99 "for remote MCJIT execution. If none is specified,"
100 "\n\tremote execution will be simulated in-process."),
101 cl::value_desc("filename"),
104 // Determine optimization level.
107 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
108 "(default = '-O2')"),
114 TargetTriple("mtriple", cl::desc("Override target triple for module"));
118 cl::desc("Architecture to generate assembly for (see --version)"));
122 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123 cl::value_desc("cpu-name"),
126 cl::list<std::string>
129 cl::desc("Target specific attributes (-mattr=help for details)"),
130 cl::value_desc("a1,+a2,-a3,..."));
133 EntryFunc("entry-function",
134 cl::desc("Specify the entry function (default = 'main') "
135 "of the executable"),
136 cl::value_desc("function"),
139 cl::list<std::string>
140 ExtraModules("extra-module",
141 cl::desc("Extra modules to be loaded"),
142 cl::value_desc("input bitcode"));
144 cl::list<std::string>
145 ExtraObjects("extra-object",
146 cl::desc("Extra object files to be loaded"),
147 cl::value_desc("input object"));
149 cl::list<std::string>
150 ExtraArchives("extra-archive",
151 cl::desc("Extra archive files to be loaded"),
152 cl::value_desc("input archive"));
155 EnableCacheManager("enable-cache-manager",
156 cl::desc("Use cache manager to save/load mdoules"),
160 ObjectCacheDir("object-cache-dir",
161 cl::desc("Directory to store cached object files "
162 "(must be user writable)"),
166 FakeArgv0("fake-argv0",
167 cl::desc("Override the 'argv[0]' value passed into the executing"
168 " program"), cl::value_desc("executable"));
171 DisableCoreFiles("disable-core-files", cl::Hidden,
172 cl::desc("Disable emission of core files if possible"));
175 NoLazyCompilation("disable-lazy-compilation",
176 cl::desc("Disable JIT lazy compilation"),
179 cl::opt<Reloc::Model>
180 RelocModel("relocation-model",
181 cl::desc("Choose relocation model"),
182 cl::init(Reloc::Default),
184 clEnumValN(Reloc::Default, "default",
185 "Target default relocation model"),
186 clEnumValN(Reloc::Static, "static",
187 "Non-relocatable code"),
188 clEnumValN(Reloc::PIC_, "pic",
189 "Fully relocatable, position independent code"),
190 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
191 "Relocatable external references, non-relocatable code"),
194 cl::opt<llvm::CodeModel::Model>
195 CMModel("code-model",
196 cl::desc("Choose code model"),
197 cl::init(CodeModel::JITDefault),
198 cl::values(clEnumValN(CodeModel::JITDefault, "default",
199 "Target default JIT code model"),
200 clEnumValN(CodeModel::Small, "small",
202 clEnumValN(CodeModel::Kernel, "kernel",
203 "Kernel code model"),
204 clEnumValN(CodeModel::Medium, "medium",
205 "Medium code model"),
206 clEnumValN(CodeModel::Large, "large",
211 GenerateSoftFloatCalls("soft-float",
212 cl::desc("Generate software floating point library calls"),
215 cl::opt<llvm::FloatABI::ABIType>
216 FloatABIForCalls("float-abi",
217 cl::desc("Choose float ABI type"),
218 cl::init(FloatABI::Default),
220 clEnumValN(FloatABI::Default, "default",
221 "Target default float ABI type"),
222 clEnumValN(FloatABI::Soft, "soft",
223 "Soft float ABI (implied by -soft-float)"),
224 clEnumValN(FloatABI::Hard, "hard",
225 "Hard float ABI (uses FP registers)"),
228 // In debug builds, make this default to true.
230 #define EMIT_DEBUG false
232 #define EMIT_DEBUG true
234 EmitJitDebugInfo("jit-emit-debug",
235 cl::desc("Emit debug information to debugger"),
236 cl::init(EMIT_DEBUG));
240 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
242 cl::desc("Emit debug info objfiles to disk"),
246 //===----------------------------------------------------------------------===//
249 // This object cache implementation writes cached objects to disk to the
250 // directory specified by CacheDir, using a filename provided in the module
251 // descriptor. The cache tries to load a saved object using that path if the
252 // file exists. CacheDir defaults to "", in which case objects are cached
253 // alongside their originating bitcodes.
255 class LLIObjectCache : public ObjectCache {
257 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
258 // Add trailing '/' to cache dir if necessary.
259 if (!this->CacheDir.empty() &&
260 this->CacheDir[this->CacheDir.size() - 1] != '/')
261 this->CacheDir += '/';
263 virtual ~LLIObjectCache() {}
265 virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) {
266 const std::string ModuleID = M->getModuleIdentifier();
267 std::string CacheName;
268 if (!getCacheFilename(ModuleID, CacheName))
271 if (!CacheDir.empty()) { // Create user-defined cache dir.
272 SmallString<128> dir(CacheName);
273 sys::path::remove_filename(dir);
274 sys::fs::create_directories(Twine(dir));
276 raw_fd_ostream outfile(CacheName.c_str(), errStr, sys::fs::F_Binary);
277 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
281 virtual MemoryBuffer* getObject(const Module* M) {
282 const std::string ModuleID = M->getModuleIdentifier();
283 std::string CacheName;
284 if (!getCacheFilename(ModuleID, CacheName))
286 // Load the object from the cache filename
287 OwningPtr<MemoryBuffer> IRObjectBuffer;
288 MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false);
289 // If the file isn't there, that's OK.
292 // MCJIT will want to write into this buffer, and we don't want that
293 // because the file has probably just been mmapped. Instead we make
294 // a copy. The filed-based buffer will be released when it goes
296 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
300 std::string CacheDir;
302 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
303 std::string Prefix("file:");
304 size_t PrefixLength = Prefix.length();
305 if (ModID.substr(0, PrefixLength) != Prefix)
307 CacheName = CacheDir + ModID.substr(PrefixLength);
308 size_t pos = CacheName.rfind('.');
309 CacheName.replace(pos, CacheName.length() - pos, ".o");
314 static ExecutionEngine *EE = 0;
315 static LLIObjectCache *CacheManager = 0;
317 static void do_shutdown() {
318 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
319 #ifndef DO_NOTHING_ATEXIT
327 // On Mingw and Cygwin, an external symbol named '__main' is called from the
328 // generated 'main' function to allow static intialization. To avoid linking
329 // problems with remote targets (because lli's remote target support does not
330 // currently handle external linking) we add a secondary module which defines
331 // an empty '__main' function.
332 static void addCygMingExtraModule(ExecutionEngine *EE,
333 LLVMContext &Context,
334 StringRef TargetTripleStr) {
335 IRBuilder<> Builder(Context);
336 Triple TargetTriple(TargetTripleStr);
338 // Create a new module.
339 Module *M = new Module("CygMingHelper", Context);
340 M->setTargetTriple(TargetTripleStr);
342 // Create an empty function named "__main".
344 if (TargetTriple.isArch64Bit()) {
345 Result = Function::Create(
346 TypeBuilder<int64_t(void), false>::get(Context),
347 GlobalValue::ExternalLinkage, "__main", M);
349 Result = Function::Create(
350 TypeBuilder<int32_t(void), false>::get(Context),
351 GlobalValue::ExternalLinkage, "__main", M);
353 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
354 Builder.SetInsertPoint(BB);
356 if (TargetTriple.isArch64Bit())
357 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
359 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
360 Builder.CreateRet(ReturnVal);
362 // Add this new module to the ExecutionEngine.
367 //===----------------------------------------------------------------------===//
368 // main Driver function
370 int main(int argc, char **argv, char * const *envp) {
371 sys::PrintStackTraceOnErrorSignal();
372 PrettyStackTraceProgram X(argc, argv);
374 LLVMContext &Context = getGlobalContext();
375 atexit(do_shutdown); // Call llvm_shutdown() on exit.
377 // If we have a native target, initialize it to ensure it is linked in and
378 // usable by the JIT.
379 InitializeNativeTarget();
380 InitializeNativeTargetAsmPrinter();
381 InitializeNativeTargetAsmParser();
383 cl::ParseCommandLineOptions(argc, argv,
384 "llvm interpreter & dynamic compiler\n");
386 // If the user doesn't want core files, disable them.
387 if (DisableCoreFiles)
388 sys::Process::PreventCoreFiles();
390 // Load the bitcode...
392 Module *Mod = ParseIRFile(InputFile, Err, Context);
394 Err.print(argv[0], errs());
398 if (EnableCacheManager) {
400 std::string CacheName("file:");
401 CacheName.append(InputFile);
402 Mod->setModuleIdentifier(CacheName);
404 errs() << "warning: -enable-cache-manager can only be used with MCJIT.";
407 // If not jitting lazily, load the whole bitcode file eagerly too.
408 std::string ErrorMsg;
409 if (NoLazyCompilation) {
410 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
411 errs() << argv[0] << ": bitcode didn't read correctly.\n";
412 errs() << "Reason: " << ErrorMsg << "\n";
419 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
420 << " information will be emitted by the non-MC JIT engine. To see full"
421 << " source debug information, enable the flag '-use-mcjit'.\n";
424 ModulePass *DebugIRPass = createDebugIRPass();
425 DebugIRPass->runOnModule(*Mod);
428 EngineBuilder builder(Mod);
429 builder.setMArch(MArch);
430 builder.setMCPU(MCPU);
431 builder.setMAttrs(MAttrs);
432 builder.setRelocationModel(RelocModel);
433 builder.setCodeModel(CMModel);
434 builder.setErrorStr(&ErrorMsg);
435 builder.setEngineKind(ForceInterpreter
436 ? EngineKind::Interpreter
439 // If we are supposed to override the target triple, do so now.
440 if (!TargetTriple.empty())
441 Mod->setTargetTriple(Triple::normalize(TargetTriple));
443 // Enable MCJIT if desired.
444 RTDyldMemoryManager *RTDyldMM = 0;
445 if (UseMCJIT && !ForceInterpreter) {
446 builder.setUseMCJIT(true);
448 RTDyldMM = new RemoteMemoryManager();
450 RTDyldMM = new SectionMemoryManager();
451 builder.setMCJITMemoryManager(RTDyldMM);
454 errs() << "error: Remote process execution requires -use-mcjit\n";
457 builder.setJITMemoryManager(ForceInterpreter ? 0 :
458 JITMemoryManager::CreateDefaultMemManager());
461 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
464 errs() << argv[0] << ": invalid optimization level.\n";
467 case '0': OLvl = CodeGenOpt::None; break;
468 case '1': OLvl = CodeGenOpt::Less; break;
469 case '2': OLvl = CodeGenOpt::Default; break;
470 case '3': OLvl = CodeGenOpt::Aggressive; break;
472 builder.setOptLevel(OLvl);
474 TargetOptions Options;
475 Options.UseSoftFloat = GenerateSoftFloatCalls;
476 if (FloatABIForCalls != FloatABI::Default)
477 Options.FloatABIType = FloatABIForCalls;
478 if (GenerateSoftFloatCalls)
479 FloatABIForCalls = FloatABI::Soft;
481 // Remote target execution doesn't handle EH or debug registration.
483 Options.JITEmitDebugInfo = EmitJitDebugInfo;
484 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
487 builder.setTargetOptions(Options);
489 EE = builder.create();
491 if (!ErrorMsg.empty())
492 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
494 errs() << argv[0] << ": unknown error creating EE!\n";
498 if (EnableCacheManager) {
499 CacheManager = new LLIObjectCache(ObjectCacheDir);
500 EE->setObjectCache(CacheManager);
503 // Load any additional modules specified on the command line.
504 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
505 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
507 Err.print(argv[0], errs());
510 if (EnableCacheManager) {
512 std::string CacheName("file:");
513 CacheName.append(ExtraModules[i]);
514 XMod->setModuleIdentifier(CacheName);
516 // else, we already printed a warning above.
521 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
522 object::ObjectFile *Obj = object::ObjectFile::createObjectFile(
525 Err.print(argv[0], errs());
528 EE->addObjectFile(Obj);
531 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
532 OwningPtr<MemoryBuffer> ArBuf;
534 ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf);
536 Err.print(argv[0], errs());
539 object::Archive *Ar = new object::Archive(ArBuf.take(), ec);
541 Err.print(argv[0], errs());
547 // If the target is Cygwin/MingW and we are generating remote code, we
548 // need an extra module to help out with linking.
549 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
550 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
553 // The following functions have no effect if their respective profiling
554 // support wasn't enabled in the build configuration.
555 EE->RegisterJITEventListener(
556 JITEventListener::createOProfileJITEventListener());
557 EE->RegisterJITEventListener(
558 JITEventListener::createIntelJITEventListener());
560 if (!NoLazyCompilation && RemoteMCJIT) {
561 errs() << "warning: remote mcjit does not support lazy compilation\n";
562 NoLazyCompilation = true;
564 EE->DisableLazyCompilation(NoLazyCompilation);
566 // If the user specifically requested an argv[0] to pass into the program,
568 if (!FakeArgv0.empty()) {
569 InputFile = FakeArgv0;
571 // Otherwise, if there is a .bc suffix on the executable strip it off, it
572 // might confuse the program.
573 if (StringRef(InputFile).endswith(".bc"))
574 InputFile.erase(InputFile.length() - 3);
577 // Add the module's name to the start of the vector of arguments to main().
578 InputArgv.insert(InputArgv.begin(), InputFile);
580 // Call the main function from M as if its signature were:
581 // int main (int argc, char **argv, const char **envp)
582 // using the contents of Args to determine argc & argv, and the contents of
583 // EnvVars to determine envp.
585 Function *EntryFn = Mod->getFunction(EntryFunc);
587 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
591 // Reset errno to zero on entry to main.
597 // If the program doesn't explicitly call exit, we will need the Exit
598 // function later on to make an explicit call, so get the function now.
599 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
600 Type::getInt32Ty(Context),
603 // Run static constructors.
604 if (UseMCJIT && !ForceInterpreter) {
605 // Give MCJIT a chance to apply relocations and set page permissions.
606 EE->finalizeObject();
608 EE->runStaticConstructorsDestructors(false);
610 if (!UseMCJIT && NoLazyCompilation) {
611 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
613 if (Fn != EntryFn && !Fn->isDeclaration())
614 EE->getPointerToFunction(Fn);
618 // Trigger compilation separately so code regions that need to be
619 // invalidated will be known.
620 (void)EE->getPointerToFunction(EntryFn);
621 // Clear instruction cache before code will be executed.
623 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
626 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
628 // Run static destructors.
629 EE->runStaticConstructorsDestructors(true);
631 // If the program didn't call exit explicitly, we should call it now.
632 // This ensures that any atexit handlers get called correctly.
633 if (Function *ExitF = dyn_cast<Function>(Exit)) {
634 std::vector<GenericValue> Args;
635 GenericValue ResultGV;
636 ResultGV.IntVal = APInt(32, Result);
637 Args.push_back(ResultGV);
638 EE->runFunction(ExitF, Args);
639 errs() << "ERROR: exit(" << Result << ") returned!\n";
642 errs() << "ERROR: exit defined with wrong prototype!\n";
646 // else == "if (RemoteMCJIT)"
648 // Remote target MCJIT doesn't (yet) support static constructors. No reason
649 // it couldn't. This is a limitation of the LLI implemantation, not the
650 // MCJIT itself. FIXME.
652 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
653 // Everything is prepared now, so lay out our program for the target
654 // address space, assign the section addresses to resolve any relocations,
655 // and send it to the target.
657 OwningPtr<RemoteTarget> Target;
658 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
659 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
660 errs() << "Warning: host does not support external remote targets.\n"
661 << " Defaulting to simulated remote execution\n";
662 Target.reset(RemoteTarget::createRemoteTarget());
664 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
665 if (ChildEXE == "") {
666 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
669 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
672 // No child process name provided, use simulated remote execution.
673 Target.reset(RemoteTarget::createRemoteTarget());
676 // Give the memory manager a pointer to our remote target interface object.
677 MM->setRemoteTarget(Target.get());
679 // Create the remote target.
682 // Since we're executing in a (at least simulated) remote address space,
683 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
684 // grab the function address directly here and tell the remote target
685 // to execute the function.
687 // Our memory manager will map generated code into the remote address
688 // space as it is loaded and copy the bits over during the finalizeMemory
691 // FIXME: argv and envp handling.
692 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
694 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
695 << format("%llx", Entry) << "\n");
697 if (Target->executeCode(Entry, Result))
698 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
700 // Like static constructors, the remote target MCJIT support doesn't handle
701 // this yet. It could. FIXME.
703 // Stop the remote target