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/JITEventListener.h"
26 #include "llvm/ExecutionEngine/JITMemoryManager.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/ExecutionEngine/ObjectCache.h"
29 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/TypeBuilder.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/Object/Archive.h"
36 #include "llvm/Object/ObjectFile.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/DynamicLibrary.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Memory.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/PluginLoader.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/Process.h"
48 #include "llvm/Support/Program.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Transforms/Instrumentation.h"
57 #include <cygwin/version.h>
58 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
59 #define DO_NOTHING_ATEXIT 1
65 #define DEBUG_TYPE "lli"
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> DebugIR(
79 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
82 // The MCJIT supports building for a target address space separate from
83 // the JIT compilation process. Use a forked process and a copying
84 // memory manager with IPC to execute using this functionality.
85 cl::opt<bool> RemoteMCJIT("remote-mcjit",
86 cl::desc("Execute MCJIT'ed code in a separate process."),
89 // Manually specify the child process for remote execution. This overrides
90 // the simulated remote execution that allocates address space for child
91 // execution. The child process will be executed and will communicate with
92 // lli via stdin/stdout pipes.
94 ChildExecPath("mcjit-remote-process",
95 cl::desc("Specify the filename of the process to launch "
96 "for remote MCJIT execution. If none is specified,"
97 "\n\tremote execution will be simulated in-process."),
98 cl::value_desc("filename"), cl::init(""));
100 // Determine optimization level.
103 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
104 "(default = '-O2')"),
110 TargetTriple("mtriple", cl::desc("Override target triple for module"));
114 cl::desc("Architecture to generate assembly for (see --version)"));
118 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
119 cl::value_desc("cpu-name"),
122 cl::list<std::string>
125 cl::desc("Target specific attributes (-mattr=help for details)"),
126 cl::value_desc("a1,+a2,-a3,..."));
129 EntryFunc("entry-function",
130 cl::desc("Specify the entry function (default = 'main') "
131 "of the executable"),
132 cl::value_desc("function"),
135 cl::list<std::string>
136 ExtraModules("extra-module",
137 cl::desc("Extra modules to be loaded"),
138 cl::value_desc("input bitcode"));
140 cl::list<std::string>
141 ExtraObjects("extra-object",
142 cl::desc("Extra object files to be loaded"),
143 cl::value_desc("input object"));
145 cl::list<std::string>
146 ExtraArchives("extra-archive",
147 cl::desc("Extra archive files to be loaded"),
148 cl::value_desc("input archive"));
151 EnableCacheManager("enable-cache-manager",
152 cl::desc("Use cache manager to save/load mdoules"),
156 ObjectCacheDir("object-cache-dir",
157 cl::desc("Directory to store cached object files "
158 "(must be user writable)"),
162 FakeArgv0("fake-argv0",
163 cl::desc("Override the 'argv[0]' value passed into the executing"
164 " program"), cl::value_desc("executable"));
167 DisableCoreFiles("disable-core-files", cl::Hidden,
168 cl::desc("Disable emission of core files if possible"));
171 NoLazyCompilation("disable-lazy-compilation",
172 cl::desc("Disable JIT lazy compilation"),
175 cl::opt<Reloc::Model>
176 RelocModel("relocation-model",
177 cl::desc("Choose relocation model"),
178 cl::init(Reloc::Default),
180 clEnumValN(Reloc::Default, "default",
181 "Target default relocation model"),
182 clEnumValN(Reloc::Static, "static",
183 "Non-relocatable code"),
184 clEnumValN(Reloc::PIC_, "pic",
185 "Fully relocatable, position independent code"),
186 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
187 "Relocatable external references, non-relocatable code"),
190 cl::opt<llvm::CodeModel::Model>
191 CMModel("code-model",
192 cl::desc("Choose code model"),
193 cl::init(CodeModel::JITDefault),
194 cl::values(clEnumValN(CodeModel::JITDefault, "default",
195 "Target default JIT code model"),
196 clEnumValN(CodeModel::Small, "small",
198 clEnumValN(CodeModel::Kernel, "kernel",
199 "Kernel code model"),
200 clEnumValN(CodeModel::Medium, "medium",
201 "Medium code model"),
202 clEnumValN(CodeModel::Large, "large",
207 GenerateSoftFloatCalls("soft-float",
208 cl::desc("Generate software floating point library calls"),
211 cl::opt<llvm::FloatABI::ABIType>
212 FloatABIForCalls("float-abi",
213 cl::desc("Choose float ABI type"),
214 cl::init(FloatABI::Default),
216 clEnumValN(FloatABI::Default, "default",
217 "Target default float ABI type"),
218 clEnumValN(FloatABI::Soft, "soft",
219 "Soft float ABI (implied by -soft-float)"),
220 clEnumValN(FloatABI::Hard, "hard",
221 "Hard float ABI (uses FP registers)"),
224 // In debug builds, make this default to true.
226 #define EMIT_DEBUG false
228 #define EMIT_DEBUG true
230 EmitJitDebugInfo("jit-emit-debug",
231 cl::desc("Emit debug information to debugger"),
232 cl::init(EMIT_DEBUG));
236 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
238 cl::desc("Emit debug info objfiles to disk"),
242 //===----------------------------------------------------------------------===//
245 // This object cache implementation writes cached objects to disk to the
246 // directory specified by CacheDir, using a filename provided in the module
247 // descriptor. The cache tries to load a saved object using that path if the
248 // file exists. CacheDir defaults to "", in which case objects are cached
249 // alongside their originating bitcodes.
251 class LLIObjectCache : public ObjectCache {
253 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
254 // Add trailing '/' to cache dir if necessary.
255 if (!this->CacheDir.empty() &&
256 this->CacheDir[this->CacheDir.size() - 1] != '/')
257 this->CacheDir += '/';
259 virtual ~LLIObjectCache() {}
261 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
262 const std::string ModuleID = M->getModuleIdentifier();
263 std::string CacheName;
264 if (!getCacheFilename(ModuleID, CacheName))
266 if (!CacheDir.empty()) { // Create user-defined cache dir.
267 SmallString<128> dir(CacheName);
268 sys::path::remove_filename(dir);
269 sys::fs::create_directories(Twine(dir));
272 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
273 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
277 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
278 const std::string ModuleID = M->getModuleIdentifier();
279 std::string CacheName;
280 if (!getCacheFilename(ModuleID, CacheName))
282 // Load the object from the cache filename
283 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
284 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
285 // If the file isn't there, that's OK.
288 // MCJIT will want to write into this buffer, and we don't want that
289 // because the file has probably just been mmapped. Instead we make
290 // a copy. The filed-based buffer will be released when it goes
292 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
296 std::string CacheDir;
298 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
299 std::string Prefix("file:");
300 size_t PrefixLength = Prefix.length();
301 if (ModID.substr(0, PrefixLength) != Prefix)
303 std::string CacheSubdir = ModID.substr(PrefixLength);
305 // Transform "X:\foo" => "/X\foo" for convenience.
306 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
307 CacheSubdir[1] = CacheSubdir[0];
308 CacheSubdir[0] = '/';
311 CacheName = CacheDir + CacheSubdir;
312 size_t pos = CacheName.rfind('.');
313 CacheName.replace(pos, CacheName.length() - pos, ".o");
318 static ExecutionEngine *EE = nullptr;
319 static LLIObjectCache *CacheManager = nullptr;
321 static void do_shutdown() {
322 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
323 #ifndef DO_NOTHING_ATEXIT
331 // On Mingw and Cygwin, an external symbol named '__main' is called from the
332 // generated 'main' function to allow static intialization. To avoid linking
333 // problems with remote targets (because lli's remote target support does not
334 // currently handle external linking) we add a secondary module which defines
335 // an empty '__main' function.
336 static void addCygMingExtraModule(ExecutionEngine *EE,
337 LLVMContext &Context,
338 StringRef TargetTripleStr) {
339 IRBuilder<> Builder(Context);
340 Triple TargetTriple(TargetTripleStr);
342 // Create a new module.
343 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
344 M->setTargetTriple(TargetTripleStr);
346 // Create an empty function named "__main".
348 if (TargetTriple.isArch64Bit()) {
349 Result = Function::Create(
350 TypeBuilder<int64_t(void), false>::get(Context),
351 GlobalValue::ExternalLinkage, "__main", M.get());
353 Result = Function::Create(
354 TypeBuilder<int32_t(void), false>::get(Context),
355 GlobalValue::ExternalLinkage, "__main", M.get());
357 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
358 Builder.SetInsertPoint(BB);
360 if (TargetTriple.isArch64Bit())
361 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
363 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
364 Builder.CreateRet(ReturnVal);
366 // Add this new module to the ExecutionEngine.
367 EE->addModule(std::move(M));
371 //===----------------------------------------------------------------------===//
372 // main Driver function
374 int main(int argc, char **argv, char * const *envp) {
375 sys::PrintStackTraceOnErrorSignal();
376 PrettyStackTraceProgram X(argc, argv);
378 LLVMContext &Context = getGlobalContext();
379 atexit(do_shutdown); // Call llvm_shutdown() on exit.
381 // If we have a native target, initialize it to ensure it is linked in and
382 // usable by the JIT.
383 InitializeNativeTarget();
384 InitializeNativeTargetAsmPrinter();
385 InitializeNativeTargetAsmParser();
387 cl::ParseCommandLineOptions(argc, argv,
388 "llvm interpreter & dynamic compiler\n");
390 // If the user doesn't want core files, disable them.
391 if (DisableCoreFiles)
392 sys::Process::PreventCoreFiles();
394 // Load the bitcode...
396 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
397 Module *Mod = Owner.get();
399 Err.print(argv[0], errs());
403 if (EnableCacheManager) {
404 std::string CacheName("file:");
405 CacheName.append(InputFile);
406 Mod->setModuleIdentifier(CacheName);
409 // If not jitting lazily, load the whole bitcode file eagerly too.
410 if (NoLazyCompilation) {
411 if (std::error_code EC = Mod->materializeAllPermanently()) {
412 errs() << argv[0] << ": bitcode didn't read correctly.\n";
413 errs() << "Reason: " << EC.message() << "\n";
419 ModulePass *DebugIRPass = createDebugIRPass();
420 DebugIRPass->runOnModule(*Mod);
423 std::string ErrorMsg;
424 EngineBuilder builder(std::move(Owner));
425 builder.setMArch(MArch);
426 builder.setMCPU(MCPU);
427 builder.setMAttrs(MAttrs);
428 builder.setRelocationModel(RelocModel);
429 builder.setCodeModel(CMModel);
430 builder.setErrorStr(&ErrorMsg);
431 builder.setEngineKind(ForceInterpreter
432 ? EngineKind::Interpreter
435 // If we are supposed to override the target triple, do so now.
436 if (!TargetTriple.empty())
437 Mod->setTargetTriple(Triple::normalize(TargetTriple));
439 // Enable MCJIT if desired.
440 RTDyldMemoryManager *RTDyldMM = nullptr;
441 if (!ForceInterpreter) {
443 RTDyldMM = new RemoteMemoryManager();
445 RTDyldMM = new SectionMemoryManager();
446 builder.setMCJITMemoryManager(RTDyldMM);
449 errs() << "error: Remote process execution requires -use-mcjit\n";
452 builder.setJITMemoryManager(ForceInterpreter ? nullptr :
453 JITMemoryManager::CreateDefaultMemManager());
456 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
459 errs() << argv[0] << ": invalid optimization level.\n";
462 case '0': OLvl = CodeGenOpt::None; break;
463 case '1': OLvl = CodeGenOpt::Less; break;
464 case '2': OLvl = CodeGenOpt::Default; break;
465 case '3': OLvl = CodeGenOpt::Aggressive; break;
467 builder.setOptLevel(OLvl);
469 TargetOptions Options;
470 Options.UseSoftFloat = GenerateSoftFloatCalls;
471 if (FloatABIForCalls != FloatABI::Default)
472 Options.FloatABIType = FloatABIForCalls;
473 if (GenerateSoftFloatCalls)
474 FloatABIForCalls = FloatABI::Soft;
476 // Remote target execution doesn't handle EH or debug registration.
478 Options.JITEmitDebugInfo = EmitJitDebugInfo;
479 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
482 builder.setTargetOptions(Options);
484 EE = builder.create();
486 if (!ErrorMsg.empty())
487 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
489 errs() << argv[0] << ": unknown error creating EE!\n";
493 if (EnableCacheManager) {
494 CacheManager = new LLIObjectCache(ObjectCacheDir);
495 EE->setObjectCache(CacheManager);
498 // Load any additional modules specified on the command line.
499 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
500 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
502 Err.print(argv[0], errs());
505 if (EnableCacheManager) {
506 std::string CacheName("file:");
507 CacheName.append(ExtraModules[i]);
508 XMod->setModuleIdentifier(CacheName);
510 EE->addModule(std::move(XMod));
513 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
514 ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
515 object::ObjectFile::createObjectFile(ExtraObjects[i]);
517 Err.print(argv[0], errs());
520 object::OwningBinary<object::ObjectFile> &O = Obj.get();
521 EE->addObjectFile(std::move(O));
524 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
525 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
526 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
528 Err.print(argv[0], errs());
531 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
533 ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
534 object::Archive::create(ArBuf->getMemBufferRef());
535 if (std::error_code EC = ArOrErr.getError()) {
536 errs() << EC.message();
539 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
541 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
543 EE->addArchive(std::move(OB));
546 // If the target is Cygwin/MingW and we are generating remote code, we
547 // need an extra module to help out with linking.
548 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
549 addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
552 // The following functions have no effect if their respective profiling
553 // support wasn't enabled in the build configuration.
554 EE->RegisterJITEventListener(
555 JITEventListener::createOProfileJITEventListener());
556 EE->RegisterJITEventListener(
557 JITEventListener::createIntelJITEventListener());
559 if (!NoLazyCompilation && RemoteMCJIT) {
560 errs() << "warning: remote mcjit does not support lazy compilation\n";
561 NoLazyCompilation = true;
563 EE->DisableLazyCompilation(NoLazyCompilation);
565 // If the user specifically requested an argv[0] to pass into the program,
567 if (!FakeArgv0.empty()) {
568 InputFile = FakeArgv0;
570 // Otherwise, if there is a .bc suffix on the executable strip it off, it
571 // might confuse the program.
572 if (StringRef(InputFile).endswith(".bc"))
573 InputFile.erase(InputFile.length() - 3);
576 // Add the module's name to the start of the vector of arguments to main().
577 InputArgv.insert(InputArgv.begin(), InputFile);
579 // Call the main function from M as if its signature were:
580 // int main (int argc, char **argv, const char **envp)
581 // using the contents of Args to determine argc & argv, and the contents of
582 // EnvVars to determine envp.
584 Function *EntryFn = Mod->getFunction(EntryFunc);
586 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
590 // Reset errno to zero on entry to main.
596 // If the program doesn't explicitly call exit, we will need the Exit
597 // function later on to make an explicit call, so get the function now.
598 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
599 Type::getInt32Ty(Context),
602 // Run static constructors.
603 if (!ForceInterpreter) {
604 // Give MCJIT a chance to apply relocations and set page permissions.
605 EE->finalizeObject();
607 EE->runStaticConstructorsDestructors(false);
609 // Trigger compilation separately so code regions that need to be
610 // invalidated will be known.
611 (void)EE->getPointerToFunction(EntryFn);
612 // Clear instruction cache before code will be executed.
614 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
617 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
619 // Run static destructors.
620 EE->runStaticConstructorsDestructors(true);
622 // If the program didn't call exit explicitly, we should call it now.
623 // This ensures that any atexit handlers get called correctly.
624 if (Function *ExitF = dyn_cast<Function>(Exit)) {
625 std::vector<GenericValue> Args;
626 GenericValue ResultGV;
627 ResultGV.IntVal = APInt(32, Result);
628 Args.push_back(ResultGV);
629 EE->runFunction(ExitF, Args);
630 errs() << "ERROR: exit(" << Result << ") returned!\n";
633 errs() << "ERROR: exit defined with wrong prototype!\n";
637 // else == "if (RemoteMCJIT)"
639 // Remote target MCJIT doesn't (yet) support static constructors. No reason
640 // it couldn't. This is a limitation of the LLI implemantation, not the
641 // MCJIT itself. FIXME.
643 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
644 // Everything is prepared now, so lay out our program for the target
645 // address space, assign the section addresses to resolve any relocations,
646 // and send it to the target.
648 std::unique_ptr<RemoteTarget> Target;
649 if (!ChildExecPath.empty()) { // Remote execution on a child process
651 // FIXME: Remove this pointless fallback mode which causes tests to "pass"
652 // on platforms where they should XFAIL.
653 errs() << "Warning: host does not support external remote targets.\n"
654 << " Defaulting to simulated remote execution\n";
655 Target.reset(new RemoteTarget);
657 if (!sys::fs::can_execute(ChildExecPath)) {
658 errs() << "Unable to find usable child executable: '" << ChildExecPath
662 Target.reset(new RemoteTargetExternal(ChildExecPath));
665 // No child process name provided, use simulated remote execution.
666 Target.reset(new RemoteTarget);
669 // Give the memory manager a pointer to our remote target interface object.
670 MM->setRemoteTarget(Target.get());
672 // Create the remote target.
673 if (!Target->create()) {
674 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
678 // Since we're executing in a (at least simulated) remote address space,
679 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
680 // grab the function address directly here and tell the remote target
681 // to execute the function.
683 // Our memory manager will map generated code into the remote address
684 // space as it is loaded and copy the bits over during the finalizeMemory
687 // FIXME: argv and envp handling.
688 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
690 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
691 << format("%llx", Entry) << "\n");
693 if (!Target->executeCode(Entry, Result))
694 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
696 // Like static constructors, the remote target MCJIT support doesn't handle
697 // this yet. It could. FIXME.
699 // Stop the remote target