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 "OrcLazyJIT.h"
17 #include "RemoteJITUtils.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Bitcode/BitcodeReader.h"
21 #include "llvm/CodeGen/CommandFlags.def"
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/Orc/OrcRemoteTargetClient.h"
29 #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
30 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/TypeBuilder.h"
36 #include "llvm/IRReader/IRReader.h"
37 #include "llvm/Object/Archive.h"
38 #include "llvm/Object/ObjectFile.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/DynamicLibrary.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Memory.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/PluginLoader.h"
49 #include "llvm/Support/PrettyStackTrace.h"
50 #include "llvm/Support/Process.h"
51 #include "llvm/Support/Program.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/TargetSelect.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Instrumentation.h"
60 #include <cygwin/version.h>
61 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
62 #define DO_NOTHING_ATEXIT 1
68 #define DEBUG_TYPE "lli"
72 enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
75 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
78 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
80 cl::opt<bool> ForceInterpreter("force-interpreter",
81 cl::desc("Force interpretation: disable JIT"),
84 cl::opt<JITKind> UseJITKind("jit-kind",
85 cl::desc("Choose underlying JIT kind."),
86 cl::init(JITKind::MCJIT),
88 clEnumValN(JITKind::MCJIT, "mcjit",
90 clEnumValN(JITKind::OrcMCJITReplacement,
92 "Orc-based MCJIT replacement"),
93 clEnumValN(JITKind::OrcLazy,
95 "Orc-based lazy JIT.")));
97 // The MCJIT supports building for a target address space separate from
98 // the JIT compilation process. Use a forked process and a copying
99 // memory manager with IPC to execute using this functionality.
100 cl::opt<bool> RemoteMCJIT("remote-mcjit",
101 cl::desc("Execute MCJIT'ed code in a separate process."),
104 // Manually specify the child process for remote execution. This overrides
105 // the simulated remote execution that allocates address space for child
106 // execution. The child process will be executed and will communicate with
107 // lli via stdin/stdout pipes.
109 ChildExecPath("mcjit-remote-process",
110 cl::desc("Specify the filename of the process to launch "
111 "for remote MCJIT execution. If none is specified,"
112 "\n\tremote execution will be simulated in-process."),
113 cl::value_desc("filename"), cl::init(""));
115 // Determine optimization level.
118 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
119 "(default = '-O2')"),
125 TargetTriple("mtriple", cl::desc("Override target triple for module"));
128 EntryFunc("entry-function",
129 cl::desc("Specify the entry function (default = 'main') "
130 "of the executable"),
131 cl::value_desc("function"),
134 cl::list<std::string>
135 ExtraModules("extra-module",
136 cl::desc("Extra modules to be loaded"),
137 cl::value_desc("input bitcode"));
139 cl::list<std::string>
140 ExtraObjects("extra-object",
141 cl::desc("Extra object files to be loaded"),
142 cl::value_desc("input object"));
144 cl::list<std::string>
145 ExtraArchives("extra-archive",
146 cl::desc("Extra archive files to be loaded"),
147 cl::value_desc("input archive"));
150 EnableCacheManager("enable-cache-manager",
151 cl::desc("Use cache manager to save/load mdoules"),
155 ObjectCacheDir("object-cache-dir",
156 cl::desc("Directory to store cached object files "
157 "(must be user writable)"),
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"),
175 GenerateSoftFloatCalls("soft-float",
176 cl::desc("Generate software floating point library calls"),
179 ExitOnError ExitOnErr;
182 //===----------------------------------------------------------------------===//
185 // This object cache implementation writes cached objects to disk to the
186 // directory specified by CacheDir, using a filename provided in the module
187 // descriptor. The cache tries to load a saved object using that path if the
188 // file exists. CacheDir defaults to "", in which case objects are cached
189 // alongside their originating bitcodes.
191 class LLIObjectCache : public ObjectCache {
193 LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
194 // Add trailing '/' to cache dir if necessary.
195 if (!this->CacheDir.empty() &&
196 this->CacheDir[this->CacheDir.size() - 1] != '/')
197 this->CacheDir += '/';
199 ~LLIObjectCache() override {}
201 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
202 const std::string &ModuleID = M->getModuleIdentifier();
203 std::string CacheName;
204 if (!getCacheFilename(ModuleID, CacheName))
206 if (!CacheDir.empty()) { // Create user-defined cache dir.
207 SmallString<128> dir(sys::path::parent_path(CacheName));
208 sys::fs::create_directories(Twine(dir));
211 raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
212 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
216 std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
217 const std::string &ModuleID = M->getModuleIdentifier();
218 std::string CacheName;
219 if (!getCacheFilename(ModuleID, CacheName))
221 // Load the object from the cache filename
222 ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
223 MemoryBuffer::getFile(CacheName, -1, false);
224 // If the file isn't there, that's OK.
227 // MCJIT will want to write into this buffer, and we don't want that
228 // because the file has probably just been mmapped. Instead we make
229 // a copy. The filed-based buffer will be released when it goes
231 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
235 std::string CacheDir;
237 bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
238 std::string Prefix("file:");
239 size_t PrefixLength = Prefix.length();
240 if (ModID.substr(0, PrefixLength) != Prefix)
242 std::string CacheSubdir = ModID.substr(PrefixLength);
244 // Transform "X:\foo" => "/X\foo" for convenience.
245 if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
246 CacheSubdir[1] = CacheSubdir[0];
247 CacheSubdir[0] = '/';
250 CacheName = CacheDir + CacheSubdir;
251 size_t pos = CacheName.rfind('.');
252 CacheName.replace(pos, CacheName.length() - pos, ".o");
257 // On Mingw and Cygwin, an external symbol named '__main' is called from the
258 // generated 'main' function to allow static initialization. To avoid linking
259 // problems with remote targets (because lli's remote target support does not
260 // currently handle external linking) we add a secondary module which defines
261 // an empty '__main' function.
262 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
263 StringRef TargetTripleStr) {
264 IRBuilder<> Builder(Context);
265 Triple TargetTriple(TargetTripleStr);
267 // Create a new module.
268 std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
269 M->setTargetTriple(TargetTripleStr);
271 // Create an empty function named "__main".
273 if (TargetTriple.isArch64Bit()) {
274 Result = Function::Create(
275 TypeBuilder<int64_t(void), false>::get(Context),
276 GlobalValue::ExternalLinkage, "__main", M.get());
278 Result = Function::Create(
279 TypeBuilder<int32_t(void), false>::get(Context),
280 GlobalValue::ExternalLinkage, "__main", M.get());
282 BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
283 Builder.SetInsertPoint(BB);
285 if (TargetTriple.isArch64Bit())
286 ReturnVal = ConstantInt::get(Context, APInt(64, 0));
288 ReturnVal = ConstantInt::get(Context, APInt(32, 0));
289 Builder.CreateRet(ReturnVal);
291 // Add this new module to the ExecutionEngine.
292 EE.addModule(std::move(M));
295 CodeGenOpt::Level getOptLevel() {
298 errs() << "lli: Invalid optimization level.\n";
300 case '0': return CodeGenOpt::None;
301 case '1': return CodeGenOpt::Less;
303 case '2': return CodeGenOpt::Default;
304 case '3': return CodeGenOpt::Aggressive;
306 llvm_unreachable("Unrecognized opt level.");
309 LLVM_ATTRIBUTE_NORETURN
310 static void reportError(SMDiagnostic Err, const char *ProgName) {
311 Err.print(ProgName, errs());
315 //===----------------------------------------------------------------------===//
316 // main Driver function
318 int main(int argc, char **argv, char * const *envp) {
319 sys::PrintStackTraceOnErrorSignal(argv[0]);
320 PrettyStackTraceProgram X(argc, argv);
322 atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
325 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
327 // If we have a native target, initialize it to ensure it is linked in and
328 // usable by the JIT.
329 InitializeNativeTarget();
330 InitializeNativeTargetAsmPrinter();
331 InitializeNativeTargetAsmParser();
333 cl::ParseCommandLineOptions(argc, argv,
334 "llvm interpreter & dynamic compiler\n");
336 // If the user doesn't want core files, disable them.
337 if (DisableCoreFiles)
338 sys::Process::PreventCoreFiles();
342 // Load the bitcode...
344 std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
345 Module *Mod = Owner.get();
347 reportError(Err, argv[0]);
349 if (UseJITKind == JITKind::OrcLazy) {
350 std::vector<std::unique_ptr<Module>> Ms;
351 Ms.push_back(std::move(Owner));
352 for (auto &ExtraMod : ExtraModules) {
353 Ms.push_back(parseIRFile(ExtraMod, Err, Context));
355 reportError(Err, argv[0]);
357 std::vector<std::string> Args;
358 Args.push_back(InputFile);
359 for (auto &Arg : InputArgv)
361 return runOrcLazyJIT(std::move(Ms), Args);
364 if (EnableCacheManager) {
365 std::string CacheName("file:");
366 CacheName.append(InputFile);
367 Mod->setModuleIdentifier(CacheName);
370 // If not jitting lazily, load the whole bitcode file eagerly too.
371 if (NoLazyCompilation) {
372 // Use *argv instead of argv[0] to work around a wrong GCC warning.
373 ExitOnError ExitOnErr(std::string(*argv) +
374 ": bitcode didn't read correctly: ");
375 ExitOnErr(Mod->materializeAll());
378 std::string ErrorMsg;
379 EngineBuilder builder(std::move(Owner));
380 builder.setMArch(MArch);
381 builder.setMCPU(MCPU);
382 builder.setMAttrs(MAttrs);
383 if (RelocModel.getNumOccurrences())
384 builder.setRelocationModel(RelocModel);
385 if (CMModel.getNumOccurrences())
386 builder.setCodeModel(CMModel);
387 builder.setErrorStr(&ErrorMsg);
388 builder.setEngineKind(ForceInterpreter
389 ? EngineKind::Interpreter
391 builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
393 // If we are supposed to override the target triple, do so now.
394 if (!TargetTriple.empty())
395 Mod->setTargetTriple(Triple::normalize(TargetTriple));
397 // Enable MCJIT if desired.
398 RTDyldMemoryManager *RTDyldMM = nullptr;
399 if (!ForceInterpreter) {
401 RTDyldMM = new ForwardingMemoryManager();
403 RTDyldMM = new SectionMemoryManager();
405 // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
406 // RTDyldMM: We still use it below, even though we don't own it.
407 builder.setMCJITMemoryManager(
408 std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
409 } else if (RemoteMCJIT) {
410 errs() << "error: Remote process execution does not work with the "
415 builder.setOptLevel(getOptLevel());
417 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
418 if (FloatABIForCalls != FloatABI::Default)
419 Options.FloatABIType = FloatABIForCalls;
421 builder.setTargetOptions(Options);
423 std::unique_ptr<ExecutionEngine> EE(builder.create());
425 if (!ErrorMsg.empty())
426 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
428 errs() << argv[0] << ": unknown error creating EE!\n";
432 std::unique_ptr<LLIObjectCache> CacheManager;
433 if (EnableCacheManager) {
434 CacheManager.reset(new LLIObjectCache(ObjectCacheDir));
435 EE->setObjectCache(CacheManager.get());
438 // Load any additional modules specified on the command line.
439 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
440 std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
442 reportError(Err, argv[0]);
443 if (EnableCacheManager) {
444 std::string CacheName("file:");
445 CacheName.append(ExtraModules[i]);
446 XMod->setModuleIdentifier(CacheName);
448 EE->addModule(std::move(XMod));
451 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
452 Expected<object::OwningBinary<object::ObjectFile>> Obj =
453 object::ObjectFile::createObjectFile(ExtraObjects[i]);
455 // TODO: Actually report errors helpfully.
456 consumeError(Obj.takeError());
457 reportError(Err, argv[0]);
459 object::OwningBinary<object::ObjectFile> &O = Obj.get();
460 EE->addObjectFile(std::move(O));
463 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
464 ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
465 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
467 reportError(Err, argv[0]);
468 std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
470 Expected<std::unique_ptr<object::Archive>> ArOrErr =
471 object::Archive::create(ArBuf->getMemBufferRef());
474 raw_string_ostream OS(Buf);
475 logAllUnhandledErrors(ArOrErr.takeError(), OS, "");
480 std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
482 object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
484 EE->addArchive(std::move(OB));
487 // If the target is Cygwin/MingW and we are generating remote code, we
488 // need an extra module to help out with linking.
489 if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
490 addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
493 // The following functions have no effect if their respective profiling
494 // support wasn't enabled in the build configuration.
495 EE->RegisterJITEventListener(
496 JITEventListener::createOProfileJITEventListener());
497 EE->RegisterJITEventListener(
498 JITEventListener::createIntelJITEventListener());
500 if (!NoLazyCompilation && RemoteMCJIT) {
501 errs() << "warning: remote mcjit does not support lazy compilation\n";
502 NoLazyCompilation = true;
504 EE->DisableLazyCompilation(NoLazyCompilation);
506 // If the user specifically requested an argv[0] to pass into the program,
508 if (!FakeArgv0.empty()) {
509 InputFile = static_cast<std::string>(FakeArgv0);
511 // Otherwise, if there is a .bc suffix on the executable strip it off, it
512 // might confuse the program.
513 if (StringRef(InputFile).endswith(".bc"))
514 InputFile.erase(InputFile.length() - 3);
517 // Add the module's name to the start of the vector of arguments to main().
518 InputArgv.insert(InputArgv.begin(), InputFile);
520 // Call the main function from M as if its signature were:
521 // int main (int argc, char **argv, const char **envp)
522 // using the contents of Args to determine argc & argv, and the contents of
523 // EnvVars to determine envp.
525 Function *EntryFn = Mod->getFunction(EntryFunc);
527 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
531 // Reset errno to zero on entry to main.
536 // Sanity check use of remote-jit: LLI currently only supports use of the
537 // remote JIT on Unix platforms.
540 errs() << "Warning: host does not support external remote targets.\n"
541 << " Defaulting to local execution\n";
544 if (ChildExecPath.empty()) {
545 errs() << "-remote-mcjit requires -mcjit-remote-process.\n";
547 } else if (!sys::fs::can_execute(ChildExecPath)) {
548 errs() << "Unable to find usable child executable: '" << ChildExecPath
556 // If the program doesn't explicitly call exit, we will need the Exit
557 // function later on to make an explicit call, so get the function now.
558 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
559 Type::getInt32Ty(Context));
561 // Run static constructors.
562 if (!ForceInterpreter) {
563 // Give MCJIT a chance to apply relocations and set page permissions.
564 EE->finalizeObject();
566 EE->runStaticConstructorsDestructors(false);
568 // Trigger compilation separately so code regions that need to be
569 // invalidated will be known.
570 (void)EE->getPointerToFunction(EntryFn);
571 // Clear instruction cache before code will be executed.
573 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
576 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
578 // Run static destructors.
579 EE->runStaticConstructorsDestructors(true);
581 // If the program didn't call exit explicitly, we should call it now.
582 // This ensures that any atexit handlers get called correctly.
583 if (Function *ExitF = dyn_cast<Function>(Exit)) {
584 std::vector<GenericValue> Args;
585 GenericValue ResultGV;
586 ResultGV.IntVal = APInt(32, Result);
587 Args.push_back(ResultGV);
588 EE->runFunction(ExitF, Args);
589 errs() << "ERROR: exit(" << Result << ") returned!\n";
592 errs() << "ERROR: exit defined with wrong prototype!\n";
596 // else == "if (RemoteMCJIT)"
598 // Remote target MCJIT doesn't (yet) support static constructors. No reason
599 // it couldn't. This is a limitation of the LLI implementation, not the
600 // MCJIT itself. FIXME.
602 // Lanch the remote process and get a channel to it.
603 std::unique_ptr<FDRawChannel> C = launchRemote();
605 errs() << "Failed to launch remote JIT.\n";
609 // Create a remote target client running over the channel.
610 typedef orc::remote::OrcRemoteTargetClient MyRemote;
611 auto R = ExitOnErr(MyRemote::Create(*C, ExitOnErr));
613 // Create a remote memory manager.
614 auto RemoteMM = ExitOnErr(R->createRemoteMemoryManager());
616 // Forward MCJIT's memory manager calls to the remote memory manager.
617 static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr(
618 std::move(RemoteMM));
620 // Forward MCJIT's symbol resolution calls to the remote.
621 static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver(
622 orc::createLambdaResolver(
623 [](const std::string &Name) { return nullptr; },
624 [&](const std::string &Name) {
625 if (auto Addr = ExitOnErr(R->getSymbolAddress(Name)))
626 return JITSymbol(Addr, JITSymbolFlags::Exported);
627 return JITSymbol(nullptr);
630 // Grab the target address of the JIT'd main function on the remote and call
632 // FIXME: argv and envp handling.
633 JITTargetAddress Entry = EE->getFunctionAddress(EntryFn->getName().str());
634 EE->finalizeObject();
635 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
636 << format("%llx", Entry) << "\n");
637 Result = ExitOnErr(R->callIntVoid(Entry));
639 // Like static constructors, the remote target MCJIT support doesn't handle
640 // this yet. It could. FIXME.
642 // Delete the EE - we need to tear it down *before* we terminate the session
643 // with the remote, otherwise it'll crash when it tries to release resources
644 // on a remote that has already been disconnected.
647 // Signal the remote target that we're done JITing.
648 ExitOnErr(R->terminateSession());
654 std::unique_ptr<FDRawChannel> launchRemote() {
656 llvm_unreachable("launchRemote not supported on non-Unix platforms");
662 if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0)
663 perror("Error creating pipe: ");
670 // Close the parent ends of the pipes
675 // Execute the child process.
676 std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut;
678 ChildPath.reset(new char[ChildExecPath.size() + 1]);
679 std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]);
680 ChildPath[ChildExecPath.size()] = '\0';
681 std::string ChildInStr = utostr(PipeFD[0][0]);
682 ChildIn.reset(new char[ChildInStr.size() + 1]);
683 std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]);
684 ChildIn[ChildInStr.size()] = '\0';
685 std::string ChildOutStr = utostr(PipeFD[1][1]);
686 ChildOut.reset(new char[ChildOutStr.size() + 1]);
687 std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]);
688 ChildOut[ChildOutStr.size()] = '\0';
691 char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr };
692 int rc = execv(ChildExecPath.c_str(), args);
694 perror("Error executing child process: ");
695 llvm_unreachable("Error executing child process");
697 // else we're the parent...
699 // Close the child ends of the pipes
703 // Return an RPC channel connected to our end of the pipes.
704 return llvm::make_unique<FDRawChannel>(PipeFD[1][0], PipeFD[0][1]);