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/IR/LLVMContext.h"
17 #include "RemoteMemoryManager.h"
18 #include "RemoteTarget.h"
19 #include "RemoteTargetExternal.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
66 #define DEBUG_TYPE "lli"
70 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
73 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
75 cl::opt<bool> ForceInterpreter("force-interpreter",
76 cl::desc("Force interpretation: disable JIT"),
79 cl::opt<bool> UseMCJIT(
80 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
83 cl::opt<bool> DebugIR(
84 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
87 // The MCJIT supports building for a target address space separate from
88 // the JIT compilation process. Use a forked process and a copying
89 // memory manager with IPC to execute using this functionality.
90 cl::opt<bool> RemoteMCJIT("remote-mcjit",
91 cl::desc("Execute MCJIT'ed code in a separate process."),
94 // Manually specify the child process for remote execution. This overrides
95 // the simulated remote execution that allocates address space for child
96 // execution. The child process will be executed and will communicate with
97 // lli via stdin/stdout pipes.
99 ChildExecPath("mcjit-remote-process",
100 cl::desc("Specify the filename of the process to launch "
101 "for remote MCJIT execution. If none is specified,"
102 "\n\tremote execution will be simulated in-process."),
103 cl::value_desc("filename"), cl::init(""));
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 ObjectCacheDir("object-cache-dir",
162 cl::desc("Directory to store cached object files "
163 "(must be user writable)"),
167 FakeArgv0("fake-argv0",
168 cl::desc("Override the 'argv[0]' value passed into the executing"
169 " program"), cl::value_desc("executable"));
172 DisableCoreFiles("disable-core-files", cl::Hidden,
173 cl::desc("Disable emission of core files if possible"));
176 NoLazyCompilation("disable-lazy-compilation",
177 cl::desc("Disable JIT lazy compilation"),
180 cl::opt<Reloc::Model>
181 RelocModel("relocation-model",
182 cl::desc("Choose relocation model"),
183 cl::init(Reloc::Default),
185 clEnumValN(Reloc::Default, "default",
186 "Target default relocation model"),
187 clEnumValN(Reloc::Static, "static",
188 "Non-relocatable code"),
189 clEnumValN(Reloc::PIC_, "pic",
190 "Fully relocatable, position independent code"),
191 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
192 "Relocatable external references, non-relocatable code"),
195 cl::opt<llvm::CodeModel::Model>
196 CMModel("code-model",
197 cl::desc("Choose code model"),
198 cl::init(CodeModel::JITDefault),
199 cl::values(clEnumValN(CodeModel::JITDefault, "default",
200 "Target default JIT code model"),
201 clEnumValN(CodeModel::Small, "small",
203 clEnumValN(CodeModel::Kernel, "kernel",
204 "Kernel code model"),
205 clEnumValN(CodeModel::Medium, "medium",
206 "Medium code model"),
207 clEnumValN(CodeModel::Large, "large",
212 GenerateSoftFloatCalls("soft-float",
213 cl::desc("Generate software floating point library calls"),
216 cl::opt<llvm::FloatABI::ABIType>
217 FloatABIForCalls("float-abi",
218 cl::desc("Choose float ABI type"),
219 cl::init(FloatABI::Default),
221 clEnumValN(FloatABI::Default, "default",
222 "Target default float ABI type"),
223 clEnumValN(FloatABI::Soft, "soft",
224 "Soft float ABI (implied by -soft-float)"),
225 clEnumValN(FloatABI::Hard, "hard",
226 "Hard float ABI (uses FP registers)"),
229 // In debug builds, make this default to true.
231 #define EMIT_DEBUG false
233 #define EMIT_DEBUG true
235 EmitJitDebugInfo("jit-emit-debug",
236 cl::desc("Emit debug information to debugger"),
237 cl::init(EMIT_DEBUG));
241 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
243 cl::desc("Emit debug info objfiles to disk"),
247 //===----------------------------------------------------------------------===//
250 // This object cache implementation writes cached objects to disk to the
251 // directory specified by CacheDir, using a filename provided in the module
252 // descriptor. The cache tries to load a saved object using that path if the
253 // file exists. CacheDir defaults to "", in which case objects are cached
254 // alongside their originating bitcodes.
256 class LLIObjectCache : public ObjectCache {
258 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
259 // Add trailing '/' to cache dir if necessary.
260 if (!this->CacheDir.empty() &&
261 this->CacheDir[this->CacheDir.size() - 1] != '/')
262 this->CacheDir += '/';
264 virtual ~LLIObjectCache() {}
266 void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) override {
267 const std::string ModuleID = M->getModuleIdentifier();
268 std::string CacheName;
269 if (!getCacheFilename(ModuleID, CacheName))
272 if (!CacheDir.empty()) { // Create user-defined cache dir.
273 SmallString<128> dir(CacheName);
274 sys::path::remove_filename(dir);
275 sys::fs::create_directories(Twine(dir));
277 raw_fd_ostream outfile(CacheName.c_str(), errStr, sys::fs::F_None);
278 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
282 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
283 const std::string ModuleID = M->getModuleIdentifier();
284 std::string CacheName;
285 if (!getCacheFilename(ModuleID, CacheName))
287 // Load the object from the cache filename
288 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
289 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
290 // If the file isn't there, that's OK.
293 // MCJIT will want to write into this buffer, and we don't want that
294 // because the file has probably just been mmapped. Instead we make
295 // a copy. The filed-based buffer will be released when it goes
297 return std::unique_ptr<MemoryBuffer>(
298 MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer()));
302 std::string CacheDir;
304 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
305 std::string Prefix("file:");
306 size_t PrefixLength = Prefix.length();
307 if (ModID.substr(0, PrefixLength) != Prefix)
309 std::string CacheSubdir = ModID.substr(PrefixLength);
311 // Transform "X:\foo" => "/X\foo" for convenience.
312 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
313 CacheSubdir[1] = CacheSubdir[0];
314 CacheSubdir[0] = '/';
317 CacheName = CacheDir + CacheSubdir;
318 size_t pos = CacheName.rfind('.');
319 CacheName.replace(pos, CacheName.length() - pos, ".o");
324 static ExecutionEngine *EE = nullptr;
325 static LLIObjectCache *CacheManager = nullptr;
327 static void do_shutdown() {
328 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
329 #ifndef DO_NOTHING_ATEXIT
337 // On Mingw and Cygwin, an external symbol named '__main' is called from the
338 // generated 'main' function to allow static intialization. To avoid linking
339 // problems with remote targets (because lli's remote target support does not
340 // currently handle external linking) we add a secondary module which defines
341 // an empty '__main' function.
342 static void addCygMingExtraModule(ExecutionEngine *EE,
343 LLVMContext &Context,
344 StringRef TargetTripleStr) {
345 IRBuilder<> Builder(Context);
346 Triple TargetTriple(TargetTripleStr);
348 // Create a new module.
349 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
350 M->setTargetTriple(TargetTripleStr);
352 // Create an empty function named "__main".
354 if (TargetTriple.isArch64Bit()) {
355 Result = Function::Create(
356 TypeBuilder<int64_t(void), false>::get(Context),
357 GlobalValue::ExternalLinkage, "__main", M.get());
359 Result = Function::Create(
360 TypeBuilder<int32_t(void), false>::get(Context),
361 GlobalValue::ExternalLinkage, "__main", M.get());
363 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
364 Builder.SetInsertPoint(BB);
366 if (TargetTriple.isArch64Bit())
367 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
369 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
370 Builder.CreateRet(ReturnVal);
372 // Add this new module to the ExecutionEngine.
373 EE->addModule(std::move(M));
377 //===----------------------------------------------------------------------===//
378 // main Driver function
380 int main(int argc, char **argv, char * const *envp) {
381 sys::PrintStackTraceOnErrorSignal();
382 PrettyStackTraceProgram X(argc, argv);
384 LLVMContext &Context = getGlobalContext();
385 atexit(do_shutdown); // Call llvm_shutdown() on exit.
387 // If we have a native target, initialize it to ensure it is linked in and
388 // usable by the JIT.
389 InitializeNativeTarget();
390 InitializeNativeTargetAsmPrinter();
391 InitializeNativeTargetAsmParser();
393 cl::ParseCommandLineOptions(argc, argv,
394 "llvm interpreter & dynamic compiler\n");
396 // If the user doesn't want core files, disable them.
397 if (DisableCoreFiles)
398 sys::Process::PreventCoreFiles();
400 // Load the bitcode...
402 std::unique_ptr<Module> Owner(ParseIRFile(InputFile, Err, Context));
403 Module *Mod = Owner.get();
405 Err.print(argv[0], errs());
409 if (EnableCacheManager) {
411 std::string CacheName("file:");
412 CacheName.append(InputFile);
413 Mod->setModuleIdentifier(CacheName);
415 errs() << "warning: -enable-cache-manager can only be used with MCJIT.";
418 // If not jitting lazily, load the whole bitcode file eagerly too.
419 if (NoLazyCompilation) {
420 if (std::error_code EC = Mod->materializeAllPermanently()) {
421 errs() << argv[0] << ": bitcode didn't read correctly.\n";
422 errs() << "Reason: " << EC.message() << "\n";
429 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
430 << " information will be emitted by the non-MC JIT engine. To see full"
431 << " source debug information, enable the flag '-use-mcjit'.\n";
434 ModulePass *DebugIRPass = createDebugIRPass();
435 DebugIRPass->runOnModule(*Mod);
438 std::string ErrorMsg;
439 EngineBuilder builder(std::move(Owner));
440 builder.setMArch(MArch);
441 builder.setMCPU(MCPU);
442 builder.setMAttrs(MAttrs);
443 builder.setRelocationModel(RelocModel);
444 builder.setCodeModel(CMModel);
445 builder.setErrorStr(&ErrorMsg);
446 builder.setEngineKind(ForceInterpreter
447 ? EngineKind::Interpreter
450 // If we are supposed to override the target triple, do so now.
451 if (!TargetTriple.empty())
452 Mod->setTargetTriple(Triple::normalize(TargetTriple));
454 // Enable MCJIT if desired.
455 RTDyldMemoryManager *RTDyldMM = nullptr;
456 if (UseMCJIT && !ForceInterpreter) {
457 builder.setUseMCJIT(true);
459 RTDyldMM = new RemoteMemoryManager();
461 RTDyldMM = new SectionMemoryManager();
462 builder.setMCJITMemoryManager(RTDyldMM);
465 errs() << "error: Remote process execution requires -use-mcjit\n";
468 builder.setJITMemoryManager(ForceInterpreter ? nullptr :
469 JITMemoryManager::CreateDefaultMemManager());
472 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
475 errs() << argv[0] << ": invalid optimization level.\n";
478 case '0': OLvl = CodeGenOpt::None; break;
479 case '1': OLvl = CodeGenOpt::Less; break;
480 case '2': OLvl = CodeGenOpt::Default; break;
481 case '3': OLvl = CodeGenOpt::Aggressive; break;
483 builder.setOptLevel(OLvl);
485 TargetOptions Options;
486 Options.UseSoftFloat = GenerateSoftFloatCalls;
487 if (FloatABIForCalls != FloatABI::Default)
488 Options.FloatABIType = FloatABIForCalls;
489 if (GenerateSoftFloatCalls)
490 FloatABIForCalls = FloatABI::Soft;
492 // Remote target execution doesn't handle EH or debug registration.
494 Options.JITEmitDebugInfo = EmitJitDebugInfo;
495 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
498 builder.setTargetOptions(Options);
500 EE = builder.create();
502 if (!ErrorMsg.empty())
503 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
505 errs() << argv[0] << ": unknown error creating EE!\n";
509 if (EnableCacheManager) {
510 CacheManager = new LLIObjectCache(ObjectCacheDir);
511 EE->setObjectCache(CacheManager);
514 // Load any additional modules specified on the command line.
515 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
516 std::unique_ptr<Module> XMod(ParseIRFile(ExtraModules[i], Err, Context));
518 Err.print(argv[0], errs());
521 if (EnableCacheManager) {
523 std::string CacheName("file:");
524 CacheName.append(ExtraModules[i]);
525 XMod->setModuleIdentifier(CacheName);
527 // else, we already printed a warning above.
529 EE->addModule(std::move(XMod));
532 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
533 ErrorOr<std::unique_ptr<object::ObjectFile>> Obj =
534 object::ObjectFile::createObjectFile(ExtraObjects[i]);
536 Err.print(argv[0], errs());
539 EE->addObjectFile(std::move(Obj.get()));
542 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
543 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBuf =
544 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
546 Err.print(argv[0], errs());
550 ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
551 object::Archive::create(std::move(ArBuf.get()));
552 if (std::error_code EC = ArOrErr.getError()) {
553 errs() << EC.message();
556 EE->addArchive(std::move(ArOrErr.get()));
559 // If the target is Cygwin/MingW and we are generating remote code, we
560 // need an extra module to help out with linking.
561 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
562 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
565 // The following functions have no effect if their respective profiling
566 // support wasn't enabled in the build configuration.
567 EE->RegisterJITEventListener(
568 JITEventListener::createOProfileJITEventListener());
569 EE->RegisterJITEventListener(
570 JITEventListener::createIntelJITEventListener());
572 if (!NoLazyCompilation && RemoteMCJIT) {
573 errs() << "warning: remote mcjit does not support lazy compilation\n";
574 NoLazyCompilation = true;
576 EE->DisableLazyCompilation(NoLazyCompilation);
578 // If the user specifically requested an argv[0] to pass into the program,
580 if (!FakeArgv0.empty()) {
581 InputFile = FakeArgv0;
583 // Otherwise, if there is a .bc suffix on the executable strip it off, it
584 // might confuse the program.
585 if (StringRef(InputFile).endswith(".bc"))
586 InputFile.erase(InputFile.length() - 3);
589 // Add the module's name to the start of the vector of arguments to main().
590 InputArgv.insert(InputArgv.begin(), InputFile);
592 // Call the main function from M as if its signature were:
593 // int main (int argc, char **argv, const char **envp)
594 // using the contents of Args to determine argc & argv, and the contents of
595 // EnvVars to determine envp.
597 Function *EntryFn = Mod->getFunction(EntryFunc);
599 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
603 // Reset errno to zero on entry to main.
609 // If the program doesn't explicitly call exit, we will need the Exit
610 // function later on to make an explicit call, so get the function now.
611 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
612 Type::getInt32Ty(Context),
615 // Run static constructors.
616 if (UseMCJIT && !ForceInterpreter) {
617 // Give MCJIT a chance to apply relocations and set page permissions.
618 EE->finalizeObject();
620 EE->runStaticConstructorsDestructors(false);
622 if (!UseMCJIT && NoLazyCompilation) {
623 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
625 if (Fn != EntryFn && !Fn->isDeclaration())
626 EE->getPointerToFunction(Fn);
630 // Trigger compilation separately so code regions that need to be
631 // invalidated will be known.
632 (void)EE->getPointerToFunction(EntryFn);
633 // Clear instruction cache before code will be executed.
635 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
638 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
640 // Run static destructors.
641 EE->runStaticConstructorsDestructors(true);
643 // If the program didn't call exit explicitly, we should call it now.
644 // This ensures that any atexit handlers get called correctly.
645 if (Function *ExitF = dyn_cast<Function>(Exit)) {
646 std::vector<GenericValue> Args;
647 GenericValue ResultGV;
648 ResultGV.IntVal = APInt(32, Result);
649 Args.push_back(ResultGV);
650 EE->runFunction(ExitF, Args);
651 errs() << "ERROR: exit(" << Result << ") returned!\n";
654 errs() << "ERROR: exit defined with wrong prototype!\n";
658 // else == "if (RemoteMCJIT)"
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 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
665 // Everything is prepared now, so lay out our program for the target
666 // address space, assign the section addresses to resolve any relocations,
667 // and send it to the target.
669 std::unique_ptr<RemoteTarget> Target;
670 if (!ChildExecPath.empty()) { // Remote execution on a child process
672 // FIXME: Remove this pointless fallback mode which causes tests to "pass"
673 // on platforms where they should XFAIL.
674 errs() << "Warning: host does not support external remote targets.\n"
675 << " Defaulting to simulated remote execution\n";
676 Target.reset(new RemoteTarget);
678 if (!sys::fs::can_execute(ChildExecPath)) {
679 errs() << "Unable to find usable child executable: '" << ChildExecPath
683 Target.reset(new RemoteTargetExternal(ChildExecPath));
686 // No child process name provided, use simulated remote execution.
687 Target.reset(new RemoteTarget);
690 // Give the memory manager a pointer to our remote target interface object.
691 MM->setRemoteTarget(Target.get());
693 // Create the remote target.
694 if (!Target->create()) {
695 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
699 // Since we're executing in a (at least simulated) remote address space,
700 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
701 // grab the function address directly here and tell the remote target
702 // to execute the function.
704 // Our memory manager will map generated code into the remote address
705 // space as it is loaded and copy the bits over during the finalizeMemory
708 // FIXME: argv and envp handling.
709 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
711 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
712 << format("%llx", Entry) << "\n");
714 if (!Target->executeCode(Entry, Result))
715 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
717 // Like static constructors, the remote target MCJIT support doesn't handle
718 // this yet. It could. FIXME.
720 // Stop the remote target