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/SectionMemoryManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IRReader/IRReader.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/DynamicLibrary.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Memory.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/PluginLoader.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/Process.h"
44 #include "llvm/Support/Program.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Transforms/Instrumentation.h"
53 #include <cygwin/version.h>
54 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
55 #define DO_NOTHING_ATEXIT 1
63 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
66 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
68 cl::opt<bool> ForceInterpreter("force-interpreter",
69 cl::desc("Force interpretation: disable JIT"),
72 cl::opt<bool> UseMCJIT(
73 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
76 cl::opt<bool> DebugIR(
77 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
80 // The MCJIT supports building for a target address space separate from
81 // the JIT compilation process. Use a forked process and a copying
82 // memory manager with IPC to execute using this functionality.
83 cl::opt<bool> RemoteMCJIT("remote-mcjit",
84 cl::desc("Execute MCJIT'ed code in a separate process."),
87 // Manually specify the child process for remote execution. This overrides
88 // the simulated remote execution that allocates address space for child
89 // execution. The child process resides in the disk and communicates with lli
90 // via stdin/stdout pipes.
92 MCJITRemoteProcess("mcjit-remote-process",
93 cl::desc("Specify the filename of the process to launch "
94 "for remote MCJIT execution. If none is specified,"
95 "\n\tremote execution will be simulated in-process."),
96 cl::value_desc("filename"),
99 // Determine optimization level.
102 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
103 "(default = '-O2')"),
109 TargetTriple("mtriple", cl::desc("Override target triple for module"));
113 cl::desc("Architecture to generate assembly for (see --version)"));
117 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
118 cl::value_desc("cpu-name"),
121 cl::list<std::string>
124 cl::desc("Target specific attributes (-mattr=help for details)"),
125 cl::value_desc("a1,+a2,-a3,..."));
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-modules",
137 cl::desc("Extra modules to be loaded"),
138 cl::value_desc("<input bitcode 2>,<input bitcode 3>,..."));
141 FakeArgv0("fake-argv0",
142 cl::desc("Override the 'argv[0]' value passed into the executing"
143 " program"), cl::value_desc("executable"));
146 DisableCoreFiles("disable-core-files", cl::Hidden,
147 cl::desc("Disable emission of core files if possible"));
150 NoLazyCompilation("disable-lazy-compilation",
151 cl::desc("Disable JIT lazy compilation"),
154 cl::opt<Reloc::Model>
155 RelocModel("relocation-model",
156 cl::desc("Choose relocation model"),
157 cl::init(Reloc::Default),
159 clEnumValN(Reloc::Default, "default",
160 "Target default relocation model"),
161 clEnumValN(Reloc::Static, "static",
162 "Non-relocatable code"),
163 clEnumValN(Reloc::PIC_, "pic",
164 "Fully relocatable, position independent code"),
165 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
166 "Relocatable external references, non-relocatable code"),
169 cl::opt<llvm::CodeModel::Model>
170 CMModel("code-model",
171 cl::desc("Choose code model"),
172 cl::init(CodeModel::JITDefault),
173 cl::values(clEnumValN(CodeModel::JITDefault, "default",
174 "Target default JIT code model"),
175 clEnumValN(CodeModel::Small, "small",
177 clEnumValN(CodeModel::Kernel, "kernel",
178 "Kernel code model"),
179 clEnumValN(CodeModel::Medium, "medium",
180 "Medium code model"),
181 clEnumValN(CodeModel::Large, "large",
186 GenerateSoftFloatCalls("soft-float",
187 cl::desc("Generate software floating point library calls"),
190 cl::opt<llvm::FloatABI::ABIType>
191 FloatABIForCalls("float-abi",
192 cl::desc("Choose float ABI type"),
193 cl::init(FloatABI::Default),
195 clEnumValN(FloatABI::Default, "default",
196 "Target default float ABI type"),
197 clEnumValN(FloatABI::Soft, "soft",
198 "Soft float ABI (implied by -soft-float)"),
199 clEnumValN(FloatABI::Hard, "hard",
200 "Hard float ABI (uses FP registers)"),
203 // In debug builds, make this default to true.
205 #define EMIT_DEBUG false
207 #define EMIT_DEBUG true
209 EmitJitDebugInfo("jit-emit-debug",
210 cl::desc("Emit debug information to debugger"),
211 cl::init(EMIT_DEBUG));
215 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
217 cl::desc("Emit debug info objfiles to disk"),
221 static ExecutionEngine *EE = 0;
223 static void do_shutdown() {
224 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
225 #ifndef DO_NOTHING_ATEXIT
231 //===----------------------------------------------------------------------===//
232 // main Driver function
234 int main(int argc, char **argv, char * const *envp) {
235 sys::PrintStackTraceOnErrorSignal();
236 PrettyStackTraceProgram X(argc, argv);
238 LLVMContext &Context = getGlobalContext();
239 atexit(do_shutdown); // Call llvm_shutdown() on exit.
241 // If we have a native target, initialize it to ensure it is linked in and
242 // usable by the JIT.
243 InitializeNativeTarget();
244 InitializeNativeTargetAsmPrinter();
245 InitializeNativeTargetAsmParser();
247 cl::ParseCommandLineOptions(argc, argv,
248 "llvm interpreter & dynamic compiler\n");
250 // If the user doesn't want core files, disable them.
251 if (DisableCoreFiles)
252 sys::Process::PreventCoreFiles();
254 // Load the bitcode...
256 Module *Mod = ParseIRFile(InputFile, Err, Context);
258 Err.print(argv[0], errs());
262 // If not jitting lazily, load the whole bitcode file eagerly too.
263 std::string ErrorMsg;
264 if (NoLazyCompilation) {
265 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
266 errs() << argv[0] << ": bitcode didn't read correctly.\n";
267 errs() << "Reason: " << ErrorMsg << "\n";
274 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
275 << " information will be emitted by the non-MC JIT engine. To see full"
276 << " source debug information, enable the flag '-use-mcjit'.\n";
279 ModulePass *DebugIRPass = createDebugIRPass();
280 DebugIRPass->runOnModule(*Mod);
283 EngineBuilder builder(Mod);
284 builder.setMArch(MArch);
285 builder.setMCPU(MCPU);
286 builder.setMAttrs(MAttrs);
287 builder.setRelocationModel(RelocModel);
288 builder.setCodeModel(CMModel);
289 builder.setErrorStr(&ErrorMsg);
290 builder.setEngineKind(ForceInterpreter
291 ? EngineKind::Interpreter
294 // If we are supposed to override the target triple, do so now.
295 if (!TargetTriple.empty())
296 Mod->setTargetTriple(Triple::normalize(TargetTriple));
298 // Enable MCJIT if desired.
299 RTDyldMemoryManager *RTDyldMM = 0;
300 if (UseMCJIT && !ForceInterpreter) {
301 builder.setUseMCJIT(true);
303 RTDyldMM = new RemoteMemoryManager();
305 RTDyldMM = new SectionMemoryManager();
306 builder.setMCJITMemoryManager(RTDyldMM);
309 errs() << "error: Remote process execution requires -use-mcjit\n";
312 builder.setJITMemoryManager(ForceInterpreter ? 0 :
313 JITMemoryManager::CreateDefaultMemManager());
316 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
319 errs() << argv[0] << ": invalid optimization level.\n";
322 case '0': OLvl = CodeGenOpt::None; break;
323 case '1': OLvl = CodeGenOpt::Less; break;
324 case '2': OLvl = CodeGenOpt::Default; break;
325 case '3': OLvl = CodeGenOpt::Aggressive; break;
327 builder.setOptLevel(OLvl);
329 TargetOptions Options;
330 Options.UseSoftFloat = GenerateSoftFloatCalls;
331 if (FloatABIForCalls != FloatABI::Default)
332 Options.FloatABIType = FloatABIForCalls;
333 if (GenerateSoftFloatCalls)
334 FloatABIForCalls = FloatABI::Soft;
336 // Remote target execution doesn't handle EH or debug registration.
338 Options.JITEmitDebugInfo = EmitJitDebugInfo;
339 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
342 builder.setTargetOptions(Options);
344 EE = builder.create();
346 if (!ErrorMsg.empty())
347 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
349 errs() << argv[0] << ": unknown error creating EE!\n";
353 // Load any additional modules specified on the command line.
354 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
355 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
357 Err.print(argv[0], errs());
363 // The following functions have no effect if their respective profiling
364 // support wasn't enabled in the build configuration.
365 EE->RegisterJITEventListener(
366 JITEventListener::createOProfileJITEventListener());
367 EE->RegisterJITEventListener(
368 JITEventListener::createIntelJITEventListener());
370 if (!NoLazyCompilation && RemoteMCJIT) {
371 errs() << "warning: remote mcjit does not support lazy compilation\n";
372 NoLazyCompilation = true;
374 EE->DisableLazyCompilation(NoLazyCompilation);
376 // If the user specifically requested an argv[0] to pass into the program,
378 if (!FakeArgv0.empty()) {
379 InputFile = FakeArgv0;
381 // Otherwise, if there is a .bc suffix on the executable strip it off, it
382 // might confuse the program.
383 if (StringRef(InputFile).endswith(".bc"))
384 InputFile.erase(InputFile.length() - 3);
387 // Add the module's name to the start of the vector of arguments to main().
388 InputArgv.insert(InputArgv.begin(), InputFile);
390 // Call the main function from M as if its signature were:
391 // int main (int argc, char **argv, const char **envp)
392 // using the contents of Args to determine argc & argv, and the contents of
393 // EnvVars to determine envp.
395 Function *EntryFn = Mod->getFunction(EntryFunc);
397 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
401 // Reset errno to zero on entry to main.
407 // If the program doesn't explicitly call exit, we will need the Exit
408 // function later on to make an explicit call, so get the function now.
409 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
410 Type::getInt32Ty(Context),
413 // Run static constructors.
414 if (UseMCJIT && !ForceInterpreter) {
415 // Give MCJIT a chance to apply relocations and set page permissions.
416 EE->finalizeObject();
418 EE->runStaticConstructorsDestructors(false);
420 if (!UseMCJIT && NoLazyCompilation) {
421 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
423 if (Fn != EntryFn && !Fn->isDeclaration())
424 EE->getPointerToFunction(Fn);
428 // Trigger compilation separately so code regions that need to be
429 // invalidated will be known.
430 (void)EE->getPointerToFunction(EntryFn);
431 // Clear instruction cache before code will be executed.
433 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
436 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
438 // Run static destructors.
439 EE->runStaticConstructorsDestructors(true);
441 // If the program didn't call exit explicitly, we should call it now.
442 // This ensures that any atexit handlers get called correctly.
443 if (Function *ExitF = dyn_cast<Function>(Exit)) {
444 std::vector<GenericValue> Args;
445 GenericValue ResultGV;
446 ResultGV.IntVal = APInt(32, Result);
447 Args.push_back(ResultGV);
448 EE->runFunction(ExitF, Args);
449 errs() << "ERROR: exit(" << Result << ") returned!\n";
452 errs() << "ERROR: exit defined with wrong prototype!\n";
456 // else == "if (RemoteMCJIT)"
458 // Remote target MCJIT doesn't (yet) support static constructors. No reason
459 // it couldn't. This is a limitation of the LLI implemantation, not the
460 // MCJIT itself. FIXME.
462 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
463 // Everything is prepared now, so lay out our program for the target
464 // address space, assign the section addresses to resolve any relocations,
465 // and send it to the target.
467 OwningPtr<RemoteTarget> Target;
468 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
469 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
470 errs() << "Warning: host does not support external remote targets.\n"
471 << " Defaulting to simulated remote execution\n";
472 Target.reset(RemoteTarget::createRemoteTarget());
474 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
475 if (ChildEXE == "") {
476 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
479 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
482 // No child process name provided, use simulated remote execution.
483 Target.reset(RemoteTarget::createRemoteTarget());
486 // Give the memory manager a pointer to our remote target interface object.
487 MM->setRemoteTarget(Target.get());
489 // Create the remote target.
492 // Since we're executing in a (at least simulated) remote address space,
493 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
494 // grab the function address directly here and tell the remote target
495 // to execute the function.
497 // Our memory manager will map generated code into the remote address
498 // space as it is loaded and copy the bits over during the finalizeMemory
501 // FIXME: argv and envp handling.
502 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
504 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
505 << format("%llx", Entry) << "\n");
507 if (Target->executeCode(Entry, Result))
508 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
510 // Like static constructors, the remote target MCJIT support doesn't handle
511 // this yet. It could. FIXME.
513 // Stop the remote target