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-module",
136 cl::desc("Extra modules to be loaded"),
137 cl::value_desc("<input bitcode 2>,<input bitcode 3>,..."));
140 FakeArgv0("fake-argv0",
141 cl::desc("Override the 'argv[0]' value passed into the executing"
142 " program"), cl::value_desc("executable"));
145 DisableCoreFiles("disable-core-files", cl::Hidden,
146 cl::desc("Disable emission of core files if possible"));
149 NoLazyCompilation("disable-lazy-compilation",
150 cl::desc("Disable JIT lazy compilation"),
153 cl::opt<Reloc::Model>
154 RelocModel("relocation-model",
155 cl::desc("Choose relocation model"),
156 cl::init(Reloc::Default),
158 clEnumValN(Reloc::Default, "default",
159 "Target default relocation model"),
160 clEnumValN(Reloc::Static, "static",
161 "Non-relocatable code"),
162 clEnumValN(Reloc::PIC_, "pic",
163 "Fully relocatable, position independent code"),
164 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
165 "Relocatable external references, non-relocatable code"),
168 cl::opt<llvm::CodeModel::Model>
169 CMModel("code-model",
170 cl::desc("Choose code model"),
171 cl::init(CodeModel::JITDefault),
172 cl::values(clEnumValN(CodeModel::JITDefault, "default",
173 "Target default JIT code model"),
174 clEnumValN(CodeModel::Small, "small",
176 clEnumValN(CodeModel::Kernel, "kernel",
177 "Kernel code model"),
178 clEnumValN(CodeModel::Medium, "medium",
179 "Medium code model"),
180 clEnumValN(CodeModel::Large, "large",
185 GenerateSoftFloatCalls("soft-float",
186 cl::desc("Generate software floating point library calls"),
189 cl::opt<llvm::FloatABI::ABIType>
190 FloatABIForCalls("float-abi",
191 cl::desc("Choose float ABI type"),
192 cl::init(FloatABI::Default),
194 clEnumValN(FloatABI::Default, "default",
195 "Target default float ABI type"),
196 clEnumValN(FloatABI::Soft, "soft",
197 "Soft float ABI (implied by -soft-float)"),
198 clEnumValN(FloatABI::Hard, "hard",
199 "Hard float ABI (uses FP registers)"),
202 // In debug builds, make this default to true.
204 #define EMIT_DEBUG false
206 #define EMIT_DEBUG true
208 EmitJitDebugInfo("jit-emit-debug",
209 cl::desc("Emit debug information to debugger"),
210 cl::init(EMIT_DEBUG));
214 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
216 cl::desc("Emit debug info objfiles to disk"),
220 static ExecutionEngine *EE = 0;
222 static void do_shutdown() {
223 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
224 #ifndef DO_NOTHING_ATEXIT
230 //===----------------------------------------------------------------------===//
231 // main Driver function
233 int main(int argc, char **argv, char * const *envp) {
234 sys::PrintStackTraceOnErrorSignal();
235 PrettyStackTraceProgram X(argc, argv);
237 LLVMContext &Context = getGlobalContext();
238 atexit(do_shutdown); // Call llvm_shutdown() on exit.
240 // If we have a native target, initialize it to ensure it is linked in and
241 // usable by the JIT.
242 InitializeNativeTarget();
243 InitializeNativeTargetAsmPrinter();
244 InitializeNativeTargetAsmParser();
246 cl::ParseCommandLineOptions(argc, argv,
247 "llvm interpreter & dynamic compiler\n");
249 // If the user doesn't want core files, disable them.
250 if (DisableCoreFiles)
251 sys::Process::PreventCoreFiles();
253 // Load the bitcode...
255 Module *Mod = ParseIRFile(InputFile, Err, Context);
257 Err.print(argv[0], errs());
261 // If not jitting lazily, load the whole bitcode file eagerly too.
262 std::string ErrorMsg;
263 if (NoLazyCompilation) {
264 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
265 errs() << argv[0] << ": bitcode didn't read correctly.\n";
266 errs() << "Reason: " << ErrorMsg << "\n";
273 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
274 << " information will be emitted by the non-MC JIT engine. To see full"
275 << " source debug information, enable the flag '-use-mcjit'.\n";
278 ModulePass *DebugIRPass = createDebugIRPass();
279 DebugIRPass->runOnModule(*Mod);
282 EngineBuilder builder(Mod);
283 builder.setMArch(MArch);
284 builder.setMCPU(MCPU);
285 builder.setMAttrs(MAttrs);
286 builder.setRelocationModel(RelocModel);
287 builder.setCodeModel(CMModel);
288 builder.setErrorStr(&ErrorMsg);
289 builder.setEngineKind(ForceInterpreter
290 ? EngineKind::Interpreter
293 // If we are supposed to override the target triple, do so now.
294 if (!TargetTriple.empty())
295 Mod->setTargetTriple(Triple::normalize(TargetTriple));
297 // Enable MCJIT if desired.
298 RTDyldMemoryManager *RTDyldMM = 0;
299 if (UseMCJIT && !ForceInterpreter) {
300 builder.setUseMCJIT(true);
302 RTDyldMM = new RemoteMemoryManager();
304 RTDyldMM = new SectionMemoryManager();
305 builder.setMCJITMemoryManager(RTDyldMM);
308 errs() << "error: Remote process execution requires -use-mcjit\n";
311 builder.setJITMemoryManager(ForceInterpreter ? 0 :
312 JITMemoryManager::CreateDefaultMemManager());
315 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
318 errs() << argv[0] << ": invalid optimization level.\n";
321 case '0': OLvl = CodeGenOpt::None; break;
322 case '1': OLvl = CodeGenOpt::Less; break;
323 case '2': OLvl = CodeGenOpt::Default; break;
324 case '3': OLvl = CodeGenOpt::Aggressive; break;
326 builder.setOptLevel(OLvl);
328 TargetOptions Options;
329 Options.UseSoftFloat = GenerateSoftFloatCalls;
330 if (FloatABIForCalls != FloatABI::Default)
331 Options.FloatABIType = FloatABIForCalls;
332 if (GenerateSoftFloatCalls)
333 FloatABIForCalls = FloatABI::Soft;
335 // Remote target execution doesn't handle EH or debug registration.
337 Options.JITEmitDebugInfo = EmitJitDebugInfo;
338 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
341 builder.setTargetOptions(Options);
343 EE = builder.create();
345 if (!ErrorMsg.empty())
346 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
348 errs() << argv[0] << ": unknown error creating EE!\n";
352 // Load any additional modules specified on the command line.
353 for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
354 Module *XMod = ParseIRFile(ExtraModules[i], Err, Context);
356 Err.print(argv[0], errs());
362 // The following functions have no effect if their respective profiling
363 // support wasn't enabled in the build configuration.
364 EE->RegisterJITEventListener(
365 JITEventListener::createOProfileJITEventListener());
366 EE->RegisterJITEventListener(
367 JITEventListener::createIntelJITEventListener());
369 if (!NoLazyCompilation && RemoteMCJIT) {
370 errs() << "warning: remote mcjit does not support lazy compilation\n";
371 NoLazyCompilation = true;
373 EE->DisableLazyCompilation(NoLazyCompilation);
375 // If the user specifically requested an argv[0] to pass into the program,
377 if (!FakeArgv0.empty()) {
378 InputFile = FakeArgv0;
380 // Otherwise, if there is a .bc suffix on the executable strip it off, it
381 // might confuse the program.
382 if (StringRef(InputFile).endswith(".bc"))
383 InputFile.erase(InputFile.length() - 3);
386 // Add the module's name to the start of the vector of arguments to main().
387 InputArgv.insert(InputArgv.begin(), InputFile);
389 // Call the main function from M as if its signature were:
390 // int main (int argc, char **argv, const char **envp)
391 // using the contents of Args to determine argc & argv, and the contents of
392 // EnvVars to determine envp.
394 Function *EntryFn = Mod->getFunction(EntryFunc);
396 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
400 // Reset errno to zero on entry to main.
406 // If the program doesn't explicitly call exit, we will need the Exit
407 // function later on to make an explicit call, so get the function now.
408 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
409 Type::getInt32Ty(Context),
412 // Run static constructors.
413 if (UseMCJIT && !ForceInterpreter) {
414 // Give MCJIT a chance to apply relocations and set page permissions.
415 EE->finalizeObject();
417 EE->runStaticConstructorsDestructors(false);
419 if (!UseMCJIT && NoLazyCompilation) {
420 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
422 if (Fn != EntryFn && !Fn->isDeclaration())
423 EE->getPointerToFunction(Fn);
427 // Trigger compilation separately so code regions that need to be
428 // invalidated will be known.
429 (void)EE->getPointerToFunction(EntryFn);
430 // Clear instruction cache before code will be executed.
432 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
435 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
437 // Run static destructors.
438 EE->runStaticConstructorsDestructors(true);
440 // If the program didn't call exit explicitly, we should call it now.
441 // This ensures that any atexit handlers get called correctly.
442 if (Function *ExitF = dyn_cast<Function>(Exit)) {
443 std::vector<GenericValue> Args;
444 GenericValue ResultGV;
445 ResultGV.IntVal = APInt(32, Result);
446 Args.push_back(ResultGV);
447 EE->runFunction(ExitF, Args);
448 errs() << "ERROR: exit(" << Result << ") returned!\n";
451 errs() << "ERROR: exit defined with wrong prototype!\n";
455 // else == "if (RemoteMCJIT)"
457 // Remote target MCJIT doesn't (yet) support static constructors. No reason
458 // it couldn't. This is a limitation of the LLI implemantation, not the
459 // MCJIT itself. FIXME.
461 RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
462 // Everything is prepared now, so lay out our program for the target
463 // address space, assign the section addresses to resolve any relocations,
464 // and send it to the target.
466 OwningPtr<RemoteTarget> Target;
467 if (!MCJITRemoteProcess.empty()) { // Remote execution on a child process
468 if (!RemoteTarget::hostSupportsExternalRemoteTarget()) {
469 errs() << "Warning: host does not support external remote targets.\n"
470 << " Defaulting to simulated remote execution\n";
471 Target.reset(RemoteTarget::createRemoteTarget());
473 std::string ChildEXE = sys::FindProgramByName(MCJITRemoteProcess);
474 if (ChildEXE == "") {
475 errs() << "Unable to find child target: '\''" << MCJITRemoteProcess << "\'\n";
478 Target.reset(RemoteTarget::createExternalRemoteTarget(ChildEXE));
481 // No child process name provided, use simulated remote execution.
482 Target.reset(RemoteTarget::createRemoteTarget());
485 // Give the memory manager a pointer to our remote target interface object.
486 MM->setRemoteTarget(Target.get());
488 // Create the remote target.
491 // Since we're executing in a (at least simulated) remote address space,
492 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
493 // grab the function address directly here and tell the remote target
494 // to execute the function.
496 // Our memory manager will map generated code into the remote address
497 // space as it is loaded and copy the bits over during the finalizeMemory
500 // FIXME: argv and envp handling.
501 uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
503 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
504 << format("%llx", Entry) << "\n");
506 if (Target->executeCode(Entry, Result))
507 errs() << "ERROR: " << Target->getErrorMsg() << "\n";
509 // Like static constructors, the remote target MCJIT support doesn't handle
510 // this yet. It could. FIXME.
512 // Stop the remote target