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"
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 cl::opt<bool> DebugIR(
83 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
86 // The MCJIT supports building for a target address space separate from
87 // the JIT compilation process. Use a forked process and a copying
88 // memory manager with IPC to execute using this functionality.
89 cl::opt<bool> RemoteMCJIT("remote-mcjit",
90 cl::desc("Execute MCJIT'ed code in a separate process."),
93 // Manually specify the child process for remote execution. This overrides
94 // the simulated remote execution that allocates address space for child
95 // execution. The child process will be executed and will communicate with
96 // lli via stdin/stdout pipes.
98 MCJITRemoteProcess("mcjit-remote-process",
99 cl::desc("Specify the filename of the process to launch "
100 "for remote MCJIT execution. If none is specified,"
101 "\n\tremote execution will be simulated in-process."),
102 cl::value_desc("filename"),
105 // Determine optimization level.
108 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
109 "(default = '-O2')"),
115 TargetTriple("mtriple", cl::desc("Override target triple for module"));
119 cl::desc("Architecture to generate assembly for (see --version)"));
123 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
124 cl::value_desc("cpu-name"),
127 cl::list<std::string>
130 cl::desc("Target specific attributes (-mattr=help for details)"),
131 cl::value_desc("a1,+a2,-a3,..."));
134 EntryFunc("entry-function",
135 cl::desc("Specify the entry function (default = 'main') "
136 "of the executable"),
137 cl::value_desc("function"),
140 cl::list<std::string>
141 ExtraModules("extra-module",
142 cl::desc("Extra modules to be loaded"),
143 cl::value_desc("input bitcode"));
145 cl::list<std::string>
146 ExtraObjects("extra-object",
147 cl::desc("Extra object files to be loaded"),
148 cl::value_desc("input object"));
150 cl::list<std::string>
151 ExtraArchives("extra-archive",
152 cl::desc("Extra archive files to be loaded"),
153 cl::value_desc("input archive"));
156 EnableCacheManager("enable-cache-manager",
157 cl::desc("Use cache manager to save/load mdoules."),
161 FakeArgv0("fake-argv0",
162 cl::desc("Override the 'argv[0]' value passed into the executing"
163 " program"), cl::value_desc("executable"));
166 DisableCoreFiles("disable-core-files", cl::Hidden,
167 cl::desc("Disable emission of core files if possible"));
170 NoLazyCompilation("disable-lazy-compilation",
171 cl::desc("Disable JIT lazy compilation"),
174 cl::opt<Reloc::Model>
175 RelocModel("relocation-model",
176 cl::desc("Choose relocation model"),
177 cl::init(Reloc::Default),
179 clEnumValN(Reloc::Default, "default",
180 "Target default relocation model"),
181 clEnumValN(Reloc::Static, "static",
182 "Non-relocatable code"),
183 clEnumValN(Reloc::PIC_, "pic",
184 "Fully relocatable, position independent code"),
185 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
186 "Relocatable external references, non-relocatable code"),
189 cl::opt<llvm::CodeModel::Model>
190 CMModel("code-model",
191 cl::desc("Choose code model"),
192 cl::init(CodeModel::JITDefault),
193 cl::values(clEnumValN(CodeModel::JITDefault, "default",
194 "Target default JIT code model"),
195 clEnumValN(CodeModel::Small, "small",
197 clEnumValN(CodeModel::Kernel, "kernel",
198 "Kernel code model"),
199 clEnumValN(CodeModel::Medium, "medium",
200 "Medium code model"),
201 clEnumValN(CodeModel::Large, "large",
206 GenerateSoftFloatCalls("soft-float",
207 cl::desc("Generate software floating point library calls"),
210 cl::opt<llvm::FloatABI::ABIType>
211 FloatABIForCalls("float-abi",
212 cl::desc("Choose float ABI type"),
213 cl::init(FloatABI::Default),
215 clEnumValN(FloatABI::Default, "default",
216 "Target default float ABI type"),
217 clEnumValN(FloatABI::Soft, "soft",
218 "Soft float ABI (implied by -soft-float)"),
219 clEnumValN(FloatABI::Hard, "hard",
220 "Hard float ABI (uses FP registers)"),
223 // In debug builds, make this default to true.
225 #define EMIT_DEBUG false
227 #define EMIT_DEBUG true
229 EmitJitDebugInfo("jit-emit-debug",
230 cl::desc("Emit debug information to debugger"),
231 cl::init(EMIT_DEBUG));
235 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
237 cl::desc("Emit debug info objfiles to disk"),
241 //===----------------------------------------------------------------------===//
244 // This object cache implementation writes cached objects to disk using a
245 // filename provided in the module descriptor and tries to load a saved object
246 // using that filename if the file exists.
248 class LLIObjectCache : public ObjectCache {
251 virtual ~LLIObjectCache() {}
253 virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) {
254 const std::string ModuleID = M->getModuleIdentifier();
255 std::string CacheName;
256 if (!getCacheFilename(ModuleID, CacheName))
258 std::ofstream outfile(CacheName.c_str(), std::ofstream::binary);
259 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
263 virtual MemoryBuffer* getObject(const Module* M) {
264 const std::string ModuleID = M->getModuleIdentifier();
265 std::string CacheName;
266 if (!getCacheFilename(ModuleID, CacheName))
268 // Load the object from the cache filename
269 OwningPtr<MemoryBuffer> IRObjectBuffer;
270 MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false);
271 // If the file isn't there, that's OK.
274 // MCJIT will want to write into this buffer, and we don't want that
275 // because the file has probably just been mmapped. Instead we make
276 // a copy. The filed-based buffer will be released when it goes
278 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
282 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
283 std::string Prefix("file:");
284 size_t PrefixLength = Prefix.length();
285 if (ModID.substr(0, PrefixLength) != Prefix)
287 CacheName = ModID.substr(PrefixLength);
288 size_t pos = CacheName.rfind('.');
289 CacheName.replace(pos, CacheName.length() - pos, ".o");
294 static ExecutionEngine *EE = 0;
295 static LLIObjectCache *CacheManager = 0;
297 static void do_shutdown() {
298 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
299 #ifndef DO_NOTHING_ATEXIT
307 // On Mingw and Cygwin, an external symbol named '__main' is called from the
308 // generated 'main' function to allow static intialization. To avoid linking
309 // problems with remote targets (because lli's remote target support does not
310 // currently handle external linking) we add a secondary module which defines
311 // an empty '__main' function.
312 static void addCygMingExtraModule(ExecutionEngine *EE,
313 LLVMContext &Context,
314 StringRef TargetTripleStr) {
315 IRBuilder<> Builder(Context);
316 Triple TargetTriple(TargetTripleStr);
318 // Create a new module.
319 Module *M = new Module("CygMingHelper", Context);
320 M->setTargetTriple(TargetTripleStr);
322 // Create an empty function named "__main".
324 if (TargetTriple.isArch64Bit()) {
325 Result = Function::Create(
326 TypeBuilder<int64_t(void), false>::get(Context),
327 GlobalValue::ExternalLinkage, "__main", M);
329 Result = Function::Create(
330 TypeBuilder<int32_t(void), false>::get(Context),
331 GlobalValue::ExternalLinkage, "__main", M);
333 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
334 Builder.SetInsertPoint(BB);
336 if (TargetTriple.isArch64Bit())
337 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
339 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
340 Builder.CreateRet(ReturnVal);
342 // Add this new module to the ExecutionEngine.
347 //===----------------------------------------------------------------------===//
348 // main Driver function
350 int main(int argc, char **argv, char * const *envp) {
351 sys::PrintStackTraceOnErrorSignal();
352 PrettyStackTraceProgram X(argc, argv);
354 LLVMContext &Context = getGlobalContext();
355 atexit(do_shutdown); // Call llvm_shutdown() on exit.
357 // If we have a native target, initialize it to ensure it is linked in and
358 // usable by the JIT.
359 InitializeNativeTarget();
360 InitializeNativeTargetAsmPrinter();
361 InitializeNativeTargetAsmParser();
363 cl::ParseCommandLineOptions(argc, argv,
364 "llvm interpreter & dynamic compiler\n");
366 // If the user doesn't want core files, disable them.
367 if (DisableCoreFiles)
368 sys::Process::PreventCoreFiles();
370 // Load the bitcode...
372 Module *Mod = ParseIRFile(InputFile, Err, Context);
374 Err.print(argv[0], errs());
378 if (EnableCacheManager) {
380 std::string CacheName("file:");
381 CacheName.append(InputFile);
382 Mod->setModuleIdentifier(CacheName);
384 errs() << "warning: -enable-cache-manager can only be used with MCJIT.";
387 // If not jitting lazily, load the whole bitcode file eagerly too.
388 std::string ErrorMsg;
389 if (NoLazyCompilation) {
390 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
391 errs() << argv[0] << ": bitcode didn't read correctly.\n";
392 errs() << "Reason: " << ErrorMsg << "\n";
399 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
400 << " information will be emitted by the non-MC JIT engine. To see full"
401 << " source debug information, enable the flag '-use-mcjit'.\n";
404 ModulePass *DebugIRPass = createDebugIRPass();
405 DebugIRPass->runOnModule(*Mod);
408 EngineBuilder builder(Mod);
409 builder.setMArch(MArch);
410 builder.setMCPU(MCPU);
411 builder.setMAttrs(MAttrs);
412 builder.setRelocationModel(RelocModel);
413 builder.setCodeModel(CMModel);
414 builder.setErrorStr(&ErrorMsg);
415 builder.setEngineKind(ForceInterpreter
416 ? EngineKind::Interpreter
419 // If we are supposed to override the target triple, do so now.
420 if (!TargetTriple.empty())
421 Mod->setTargetTriple(Triple::normalize(TargetTriple));
423 // Enable MCJIT if desired.
424 RTDyldMemoryManager *RTDyldMM = 0;
425 if (UseMCJIT && !ForceInterpreter) {
426 builder.setUseMCJIT(true);
428 RTDyldMM = new RemoteMemoryManager();
430 RTDyldMM = new SectionMemoryManager();
431 builder.setMCJITMemoryManager(RTDyldMM);
434 errs() << "error: Remote process execution requires -use-mcjit\n";
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.UseSoftFloat = GenerateSoftFloatCalls;
456 if (FloatABIForCalls != FloatABI::Default)
457 Options.FloatABIType = FloatABIForCalls;
458 if (GenerateSoftFloatCalls)
459 FloatABIForCalls = FloatABI::Soft;
461 // Remote target execution doesn't handle EH or debug registration.
463 Options.JITEmitDebugInfo = EmitJitDebugInfo;
464 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
467 builder.setTargetOptions(Options);
469 EE = builder.create();
471 if (!ErrorMsg.empty())
472 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
474 errs() << argv[0] << ": unknown error creating EE!\n";
478 if (EnableCacheManager) {
479 CacheManager = new LLIObjectCache;
480 EE->setObjectCache(CacheManager);
483 // Load any additional modules specified on the command line.
484 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
485 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
487 Err.print(argv[0], errs());
490 if (EnableCacheManager) {
492 std::string CacheName("file:");
493 CacheName.append(ExtraModules[i]);
494 XMod->setModuleIdentifier(CacheName);
496 // else, we already printed a warning above.
501 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
502 object::ObjectFile *Obj = object::ObjectFile::createObjectFile(
505 Err.print(argv[0], errs());
508 EE->addObjectFile(Obj);
511 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
512 OwningPtr<MemoryBuffer> ArBuf;
514 ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf);
516 Err.print(argv[0], errs());
519 object::Archive *Ar = new object::Archive(ArBuf.take(), ec);
521 Err.print(argv[0], errs());
527 // If the target is Cygwin/MingW and we are generating remote code, we
528 // need an extra module to help out with linking.
529 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
530 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
533 // The following functions have no effect if their respective profiling
534 // support wasn't enabled in the build configuration.
535 EE->RegisterJITEventListener(
536 JITEventListener::createOProfileJITEventListener());
537 EE->RegisterJITEventListener(
538 JITEventListener::createIntelJITEventListener());
540 if (!NoLazyCompilation && RemoteMCJIT) {
541 errs() << "warning: remote mcjit does not support lazy compilation\n";
542 NoLazyCompilation = true;
544 EE->DisableLazyCompilation(NoLazyCompilation);
546 // If the user specifically requested an argv[0] to pass into the program,
548 if (!FakeArgv0.empty()) {
549 InputFile = FakeArgv0;
551 // Otherwise, if there is a .bc suffix on the executable strip it off, it
552 // might confuse the program.
553 if (StringRef(InputFile).endswith(".bc"))
554 InputFile.erase(InputFile.length() - 3);
557 // Add the module's name to the start of the vector of arguments to main().
558 InputArgv.insert(InputArgv.begin(), InputFile);
560 // Call the main function from M as if its signature were:
561 // int main (int argc, char **argv, const char **envp)
562 // using the contents of Args to determine argc & argv, and the contents of
563 // EnvVars to determine envp.
565 Function *EntryFn = Mod->getFunction(EntryFunc);
567 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
571 // Reset errno to zero on entry to main.
577 // If the program doesn't explicitly call exit, we will need the Exit
578 // function later on to make an explicit call, so get the function now.
579 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
580 Type::getInt32Ty(Context),
583 // Run static constructors.
584 if (UseMCJIT && !ForceInterpreter) {
585 // Give MCJIT a chance to apply relocations and set page permissions.
586 EE->finalizeObject();
588 EE->runStaticConstructorsDestructors(false);
590 if (!UseMCJIT && NoLazyCompilation) {
591 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
593 if (Fn != EntryFn && !Fn->isDeclaration())
594 EE->getPointerToFunction(Fn);
598 // Trigger compilation separately so code regions that need to be
599 // invalidated will be known.
600 (void)EE->getPointerToFunction(EntryFn);
601 // Clear instruction cache before code will be executed.
603 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
606 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
608 // Run static destructors.
609 EE->runStaticConstructorsDestructors(true);
611 // If the program didn't call exit explicitly, we should call it now.
612 // This ensures that any atexit handlers get called correctly.
613 if (Function *ExitF = dyn_cast<Function>(Exit)) {
614 std::vector<GenericValue> Args;
615 GenericValue ResultGV;
616 ResultGV.IntVal = APInt(32, Result);
617 Args.push_back(ResultGV);
618 EE->runFunction(ExitF, Args);
619 errs() << "ERROR: exit(" << Result << ") returned!\n";
622 errs() << "ERROR: exit defined with wrong prototype!\n";
626 // else == "if (RemoteMCJIT)"
628 // Remote target MCJIT doesn't (yet) support static constructors. No reason
629 // it couldn't. This is a limitation of the LLI implemantation, not the
630 // MCJIT itself. FIXME.
632 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
633 // Everything is prepared now, so lay out our program for the target
634 // address space, assign the section addresses to resolve any relocations,
635 // and send it to the target.
637 OwningPtr<RemoteTarget> Target;
638 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
639 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
640 errs() << "Warning: host does not support external remote targets.\n"
641 << " Defaulting to simulated remote execution\n";
642 Target.reset(RemoteTarget::createRemoteTarget());
644 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
645 if (ChildEXE == "") {
646 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
649 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
652 // No child process name provided, use simulated remote execution.
653 Target.reset(RemoteTarget::createRemoteTarget());
656 // Give the memory manager a pointer to our remote target interface object.
657 MM->setRemoteTarget(Target.get());
659 // Create the remote target.
662 // Since we're executing in a (at least simulated) remote address space,
663 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
664 // grab the function address directly here and tell the remote target
665 // to execute the function.
667 // Our memory manager will map generated code into the remote address
668 // space as it is loaded and copy the bits over during the finalizeMemory
671 // FIXME: argv and envp handling.
672 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
674 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
675 << format("%llx", Entry) << "\n");
677 if (Target->executeCode(Entry, Result))
678 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
680 // Like static constructors, the remote target MCJIT support doesn't handle
681 // this yet. It could. FIXME.
683 // Stop the remote target