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/MCJIT.h"
27 #include "llvm/ExecutionEngine/ObjectCache.h"
28 #include "llvm/ExecutionEngine/OrcMCJITReplacement.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> UseOrcMCJITReplacement("use-orcmcjit",
79 cl::desc("Use the experimental "
80 "OrcMCJITReplacement as a "
81 "drop-in replacement for "
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 ChildExecPath("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"), cl::init(""));
103 // Determine optimization level.
106 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
107 "(default = '-O2')"),
113 TargetTriple("mtriple", cl::desc("Override target triple for module"));
117 cl::desc("Architecture to generate assembly for (see --version)"));
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
125 cl::list<std::string>
128 cl::desc("Target specific attributes (-mattr=help for details)"),
129 cl::value_desc("a1,+a2,-a3,..."));
132 EntryFunc("entry-function",
133 cl::desc("Specify the entry function (default = 'main') "
134 "of the executable"),
135 cl::value_desc("function"),
138 cl::list<std::string>
139 ExtraModules("extra-module",
140 cl::desc("Extra modules to be loaded"),
141 cl::value_desc("input bitcode"));
143 cl::list<std::string>
144 ExtraObjects("extra-object",
145 cl::desc("Extra object files to be loaded"),
146 cl::value_desc("input object"));
148 cl::list<std::string>
149 ExtraArchives("extra-archive",
150 cl::desc("Extra archive files to be loaded"),
151 cl::value_desc("input archive"));
154 EnableCacheManager("enable-cache-manager",
155 cl::desc("Use cache manager to save/load mdoules"),
159 ObjectCacheDir("object-cache-dir",
160 cl::desc("Directory to store cached object files "
161 "(must be user writable)"),
165 FakeArgv0("fake-argv0",
166 cl::desc("Override the 'argv[0]' value passed into the executing"
167 " program"), cl::value_desc("executable"));
170 DisableCoreFiles("disable-core-files", cl::Hidden,
171 cl::desc("Disable emission of core files if possible"));
174 NoLazyCompilation("disable-lazy-compilation",
175 cl::desc("Disable JIT lazy compilation"),
178 cl::opt<Reloc::Model>
179 RelocModel("relocation-model",
180 cl::desc("Choose relocation model"),
181 cl::init(Reloc::Default),
183 clEnumValN(Reloc::Default, "default",
184 "Target default relocation model"),
185 clEnumValN(Reloc::Static, "static",
186 "Non-relocatable code"),
187 clEnumValN(Reloc::PIC_, "pic",
188 "Fully relocatable, position independent code"),
189 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
190 "Relocatable external references, non-relocatable code"),
193 cl::opt<llvm::CodeModel::Model>
194 CMModel("code-model",
195 cl::desc("Choose code model"),
196 cl::init(CodeModel::JITDefault),
197 cl::values(clEnumValN(CodeModel::JITDefault, "default",
198 "Target default JIT code model"),
199 clEnumValN(CodeModel::Small, "small",
201 clEnumValN(CodeModel::Kernel, "kernel",
202 "Kernel code model"),
203 clEnumValN(CodeModel::Medium, "medium",
204 "Medium code model"),
205 clEnumValN(CodeModel::Large, "large",
210 GenerateSoftFloatCalls("soft-float",
211 cl::desc("Generate software floating point library calls"),
214 cl::opt<llvm::FloatABI::ABIType>
215 FloatABIForCalls("float-abi",
216 cl::desc("Choose float ABI type"),
217 cl::init(FloatABI::Default),
219 clEnumValN(FloatABI::Default, "default",
220 "Target default float ABI type"),
221 clEnumValN(FloatABI::Soft, "soft",
222 "Soft float ABI (implied by -soft-float)"),
223 clEnumValN(FloatABI::Hard, "hard",
224 "Hard float ABI (uses FP registers)"),
227 // In debug builds, make this default to true.
229 #define EMIT_DEBUG false
231 #define EMIT_DEBUG true
233 EmitJitDebugInfo("jit-emit-debug",
234 cl::desc("Emit debug information to debugger"),
235 cl::init(EMIT_DEBUG));
239 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
241 cl::desc("Emit debug info objfiles to disk"),
245 //===----------------------------------------------------------------------===//
248 // This object cache implementation writes cached objects to disk to the
249 // directory specified by CacheDir, using a filename provided in the module
250 // descriptor. The cache tries to load a saved object using that path if the
251 // file exists. CacheDir defaults to "", in which case objects are cached
252 // alongside their originating bitcodes.
254 class LLIObjectCache : public ObjectCache {
256 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
257 // Add trailing '/' to cache dir if necessary.
258 if (!this->CacheDir.empty() &&
259 this->CacheDir[this->CacheDir.size() - 1] != '/')
260 this->CacheDir += '/';
262 virtual ~LLIObjectCache() {}
264 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
265 const std::string ModuleID = M->getModuleIdentifier();
266 std::string CacheName;
267 if (!getCacheFilename(ModuleID, CacheName))
269 if (!CacheDir.empty()) { // Create user-defined cache dir.
270 SmallString<128> dir(CacheName);
271 sys::path::remove_filename(dir);
272 sys::fs::create_directories(Twine(dir));
275 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
276 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
280 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
281 const std::string ModuleID = M->getModuleIdentifier();
282 std::string CacheName;
283 if (!getCacheFilename(ModuleID, CacheName))
285 // Load the object from the cache filename
286 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
287 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
288 // If the file isn't there, that's OK.
291 // MCJIT will want to write into this buffer, and we don't want that
292 // because the file has probably just been mmapped. Instead we make
293 // a copy. The filed-based buffer will be released when it goes
295 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
299 std::string CacheDir;
301 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
302 std::string Prefix("file:");
303 size_t PrefixLength = Prefix.length();
304 if (ModID.substr(0, PrefixLength) != Prefix)
306 std::string CacheSubdir = ModID.substr(PrefixLength);
308 // Transform "X:\foo" => "/X\foo" for convenience.
309 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
310 CacheSubdir[1] = CacheSubdir[0];
311 CacheSubdir[0] = '/';
314 CacheName = CacheDir + CacheSubdir;
315 size_t pos = CacheName.rfind('.');
316 CacheName.replace(pos, CacheName.length() - pos, ".o");
321 static ExecutionEngine *EE = nullptr;
322 static LLIObjectCache *CacheManager = nullptr;
324 static void do_shutdown() {
325 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
326 #ifndef DO_NOTHING_ATEXIT
334 // On Mingw and Cygwin, an external symbol named '__main' is called from the
335 // generated 'main' function to allow static intialization. To avoid linking
336 // problems with remote targets (because lli's remote target support does not
337 // currently handle external linking) we add a secondary module which defines
338 // an empty '__main' function.
339 static void addCygMingExtraModule(ExecutionEngine *EE,
340 LLVMContext &Context,
341 StringRef TargetTripleStr) {
342 IRBuilder<> Builder(Context);
343 Triple TargetTriple(TargetTripleStr);
345 // Create a new module.
346 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
347 M->setTargetTriple(TargetTripleStr);
349 // Create an empty function named "__main".
351 if (TargetTriple.isArch64Bit()) {
352 Result = Function::Create(
353 TypeBuilder<int64_t(void), false>::get(Context),
354 GlobalValue::ExternalLinkage, "__main", M.get());
356 Result = Function::Create(
357 TypeBuilder<int32_t(void), false>::get(Context),
358 GlobalValue::ExternalLinkage, "__main", M.get());
360 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
361 Builder.SetInsertPoint(BB);
363 if (TargetTriple.isArch64Bit())
364 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
366 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
367 Builder.CreateRet(ReturnVal);
369 // Add this new module to the ExecutionEngine.
370 EE->addModule(std::move(M));
374 //===----------------------------------------------------------------------===//
375 // main Driver function
377 int main(int argc, char **argv, char * const *envp) {
378 sys::PrintStackTraceOnErrorSignal();
379 PrettyStackTraceProgram X(argc, argv);
381 LLVMContext &Context = getGlobalContext();
382 atexit(do_shutdown); // Call llvm_shutdown() on exit.
384 // If we have a native target, initialize it to ensure it is linked in and
385 // usable by the JIT.
386 InitializeNativeTarget();
387 InitializeNativeTargetAsmPrinter();
388 InitializeNativeTargetAsmParser();
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 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
400 Module *Mod = Owner.get();
402 Err.print(argv[0], errs());
406 if (EnableCacheManager) {
407 std::string CacheName("file:");
408 CacheName.append(InputFile);
409 Mod->setModuleIdentifier(CacheName);
412 // If not jitting lazily, load the whole bitcode file eagerly too.
413 if (NoLazyCompilation) {
414 if (std::error_code EC = Mod->materializeAllPermanently()) {
415 errs() << argv[0] << ": bitcode didn't read correctly.\n";
416 errs() << "Reason: " << EC.message() << "\n";
421 std::string ErrorMsg;
422 EngineBuilder builder(std::move(Owner));
423 builder.setMArch(MArch);
424 builder.setMCPU(MCPU);
425 builder.setMAttrs(MAttrs);
426 builder.setRelocationModel(RelocModel);
427 builder.setCodeModel(CMModel);
428 builder.setErrorStr(&ErrorMsg);
429 builder.setEngineKind(ForceInterpreter
430 ? EngineKind::Interpreter
432 builder.setUseOrcMCJITReplacement(UseOrcMCJITReplacement);
434 // If we are supposed to override the target triple, do so now.
435 if (!TargetTriple.empty())
436 Mod->setTargetTriple(Triple::normalize(TargetTriple));
438 // Enable MCJIT if desired.
439 RTDyldMemoryManager *RTDyldMM = nullptr;
440 if (!ForceInterpreter) {
442 RTDyldMM = new RemoteMemoryManager();
444 RTDyldMM = new SectionMemoryManager();
446 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
447 // RTDyldMM: We still use it below, even though we don't own it.
448 builder.setMCJITMemoryManager(
449 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
450 } else if (RemoteMCJIT) {
451 errs() << "error: Remote process execution does not work with the "
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 = static_cast<std::string>(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