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 "RecordingMemoryManager.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/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Instrumentation.h"
52 #include <cygwin/version.h>
53 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
54 #define DO_NOTHING_ATEXIT 1
62 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
65 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
67 cl::opt<bool> ForceInterpreter("force-interpreter",
68 cl::desc("Force interpretation: disable JIT"),
71 cl::opt<bool> UseMCJIT(
72 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
75 cl::opt<bool> DebugIR(
76 "debug-ir", cl::desc("Generate debug information to allow debugging IR."),
79 // The MCJIT supports building for a target address space separate from
80 // the JIT compilation process. Use a forked process and a copying
81 // memory manager with IPC to execute using this functionality.
82 cl::opt<bool> RemoteMCJIT("remote-mcjit",
83 cl::desc("Execute MCJIT'ed code in a separate process."),
86 // Determine optimization level.
89 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
96 TargetTriple("mtriple", cl::desc("Override target triple for module"));
100 cl::desc("Architecture to generate assembly for (see --version)"));
104 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
105 cl::value_desc("cpu-name"),
108 cl::list<std::string>
111 cl::desc("Target specific attributes (-mattr=help for details)"),
112 cl::value_desc("a1,+a2,-a3,..."));
115 EntryFunc("entry-function",
116 cl::desc("Specify the entry function (default = 'main') "
117 "of the executable"),
118 cl::value_desc("function"),
122 FakeArgv0("fake-argv0",
123 cl::desc("Override the 'argv[0]' value passed into the executing"
124 " program"), cl::value_desc("executable"));
127 DisableCoreFiles("disable-core-files", cl::Hidden,
128 cl::desc("Disable emission of core files if possible"));
131 NoLazyCompilation("disable-lazy-compilation",
132 cl::desc("Disable JIT lazy compilation"),
135 cl::opt<Reloc::Model>
136 RelocModel("relocation-model",
137 cl::desc("Choose relocation model"),
138 cl::init(Reloc::Default),
140 clEnumValN(Reloc::Default, "default",
141 "Target default relocation model"),
142 clEnumValN(Reloc::Static, "static",
143 "Non-relocatable code"),
144 clEnumValN(Reloc::PIC_, "pic",
145 "Fully relocatable, position independent code"),
146 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
147 "Relocatable external references, non-relocatable code"),
150 cl::opt<llvm::CodeModel::Model>
151 CMModel("code-model",
152 cl::desc("Choose code model"),
153 cl::init(CodeModel::JITDefault),
154 cl::values(clEnumValN(CodeModel::JITDefault, "default",
155 "Target default JIT code model"),
156 clEnumValN(CodeModel::Small, "small",
158 clEnumValN(CodeModel::Kernel, "kernel",
159 "Kernel code model"),
160 clEnumValN(CodeModel::Medium, "medium",
161 "Medium code model"),
162 clEnumValN(CodeModel::Large, "large",
167 GenerateSoftFloatCalls("soft-float",
168 cl::desc("Generate software floating point library calls"),
171 cl::opt<llvm::FloatABI::ABIType>
172 FloatABIForCalls("float-abi",
173 cl::desc("Choose float ABI type"),
174 cl::init(FloatABI::Default),
176 clEnumValN(FloatABI::Default, "default",
177 "Target default float ABI type"),
178 clEnumValN(FloatABI::Soft, "soft",
179 "Soft float ABI (implied by -soft-float)"),
180 clEnumValN(FloatABI::Hard, "hard",
181 "Hard float ABI (uses FP registers)"),
184 // In debug builds, make this default to true.
186 #define EMIT_DEBUG false
188 #define EMIT_DEBUG true
190 EmitJitDebugInfo("jit-emit-debug",
191 cl::desc("Emit debug information to debugger"),
192 cl::init(EMIT_DEBUG));
196 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
198 cl::desc("Emit debug info objfiles to disk"),
202 static ExecutionEngine *EE = 0;
204 static void do_shutdown() {
205 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
206 #ifndef DO_NOTHING_ATEXIT
212 void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
213 // Lay out our sections in order, with all the code sections first, then
214 // all the data sections.
215 uint64_t CurOffset = 0;
216 unsigned MaxAlign = T->getPageAlignment();
217 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
218 SmallVector<unsigned, 16> Sizes;
219 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
222 DEBUG(dbgs() << "code region: size " << I->first.size()
223 << ", alignment " << I->second << "\n");
224 // Align the current offset up to whatever is needed for the next
226 unsigned Align = I->second;
227 CurOffset = (CurOffset + Align - 1) / Align * Align;
228 // Save off the address of the new section and allocate its space.
229 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
230 Sizes.push_back(I->first.size());
231 CurOffset += I->first.size();
233 // Adjust to keep code and data aligned on seperate pages.
234 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
235 unsigned FirstDataIndex = Offsets.size();
236 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
239 DEBUG(dbgs() << "data region: size " << I->first.size()
240 << ", alignment " << I->second << "\n");
241 // Align the current offset up to whatever is needed for the next
243 unsigned Align = I->second;
244 CurOffset = (CurOffset + Align - 1) / Align * Align;
245 // Save off the address of the new section and allocate its space.
246 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
247 Sizes.push_back(I->first.size());
248 CurOffset += I->first.size();
251 // Allocate space in the remote target.
253 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
254 report_fatal_error(T->getErrorMsg());
255 // Map the section addresses so relocations will get updated in the local
256 // copies of the sections.
257 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
258 uint64_t Addr = RemoteAddr + Offsets[i].second;
259 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
261 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
262 << " to remote: 0x" << format("%llx", Addr) << "\n");
266 // Trigger application of relocations
267 EE->finalizeObject();
269 // Now load it all to the target.
270 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
271 uint64_t Addr = RemoteAddr + Offsets[i].second;
273 if (i < FirstDataIndex) {
274 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
276 DEBUG(dbgs() << " loading code: " << Offsets[i].first
277 << " to remote: 0x" << format("%llx", Addr) << "\n");
279 T->loadData(Addr, Offsets[i].first, Sizes[i]);
281 DEBUG(dbgs() << " loading data: " << Offsets[i].first
282 << " to remote: 0x" << format("%llx", Addr) << "\n");
288 //===----------------------------------------------------------------------===//
289 // main Driver function
291 int main(int argc, char **argv, char * const *envp) {
292 sys::PrintStackTraceOnErrorSignal();
293 PrettyStackTraceProgram X(argc, argv);
295 LLVMContext &Context = getGlobalContext();
296 atexit(do_shutdown); // Call llvm_shutdown() on exit.
298 // If we have a native target, initialize it to ensure it is linked in and
299 // usable by the JIT.
300 InitializeNativeTarget();
301 InitializeNativeTargetAsmPrinter();
302 InitializeNativeTargetAsmParser();
304 cl::ParseCommandLineOptions(argc, argv,
305 "llvm interpreter & dynamic compiler\n");
307 // If the user doesn't want core files, disable them.
308 if (DisableCoreFiles)
309 sys::Process::PreventCoreFiles();
311 // Load the bitcode...
313 Module *Mod = ParseIRFile(InputFile, Err, Context);
315 Err.print(argv[0], errs());
319 // If not jitting lazily, load the whole bitcode file eagerly too.
320 std::string ErrorMsg;
321 if (NoLazyCompilation) {
322 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
323 errs() << argv[0] << ": bitcode didn't read correctly.\n";
324 errs() << "Reason: " << ErrorMsg << "\n";
331 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug"
332 << " information will be emitted by the non-MC JIT engine. To see full"
333 << " source debug information, enable the flag '-use-mcjit'.\n";
336 ModulePass *DebugIRPass = createDebugIRPass();
337 DebugIRPass->runOnModule(*Mod);
340 EngineBuilder builder(Mod);
341 builder.setMArch(MArch);
342 builder.setMCPU(MCPU);
343 builder.setMAttrs(MAttrs);
344 builder.setRelocationModel(RelocModel);
345 builder.setCodeModel(CMModel);
346 builder.setErrorStr(&ErrorMsg);
347 builder.setEngineKind(ForceInterpreter
348 ? EngineKind::Interpreter
351 // If we are supposed to override the target triple, do so now.
352 if (!TargetTriple.empty())
353 Mod->setTargetTriple(Triple::normalize(TargetTriple));
355 // Enable MCJIT if desired.
356 RTDyldMemoryManager *RTDyldMM = 0;
357 if (UseMCJIT && !ForceInterpreter) {
358 builder.setUseMCJIT(true);
360 RTDyldMM = new RecordingMemoryManager();
362 RTDyldMM = new SectionMemoryManager();
363 builder.setMCJITMemoryManager(RTDyldMM);
366 errs() << "error: Remote process execution requires -use-mcjit\n";
369 builder.setJITMemoryManager(ForceInterpreter ? 0 :
370 JITMemoryManager::CreateDefaultMemManager());
373 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
376 errs() << argv[0] << ": invalid optimization level.\n";
379 case '0': OLvl = CodeGenOpt::None; break;
380 case '1': OLvl = CodeGenOpt::Less; break;
381 case '2': OLvl = CodeGenOpt::Default; break;
382 case '3': OLvl = CodeGenOpt::Aggressive; break;
384 builder.setOptLevel(OLvl);
386 TargetOptions Options;
387 Options.UseSoftFloat = GenerateSoftFloatCalls;
388 if (FloatABIForCalls != FloatABI::Default)
389 Options.FloatABIType = FloatABIForCalls;
390 if (GenerateSoftFloatCalls)
391 FloatABIForCalls = FloatABI::Soft;
393 // Remote target execution doesn't handle EH or debug registration.
395 Options.JITEmitDebugInfo = EmitJitDebugInfo;
396 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
399 builder.setTargetOptions(Options);
401 EE = builder.create();
403 if (!ErrorMsg.empty())
404 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
406 errs() << argv[0] << ": unknown error creating EE!\n";
410 // The following functions have no effect if their respective profiling
411 // support wasn't enabled in the build configuration.
412 EE->RegisterJITEventListener(
413 JITEventListener::createOProfileJITEventListener());
414 EE->RegisterJITEventListener(
415 JITEventListener::createIntelJITEventListener());
417 if (!NoLazyCompilation && RemoteMCJIT) {
418 errs() << "warning: remote mcjit does not support lazy compilation\n";
419 NoLazyCompilation = true;
421 EE->DisableLazyCompilation(NoLazyCompilation);
423 // If the user specifically requested an argv[0] to pass into the program,
425 if (!FakeArgv0.empty()) {
426 InputFile = FakeArgv0;
428 // Otherwise, if there is a .bc suffix on the executable strip it off, it
429 // might confuse the program.
430 if (StringRef(InputFile).endswith(".bc"))
431 InputFile.erase(InputFile.length() - 3);
434 // Add the module's name to the start of the vector of arguments to main().
435 InputArgv.insert(InputArgv.begin(), InputFile);
437 // Call the main function from M as if its signature were:
438 // int main (int argc, char **argv, const char **envp)
439 // using the contents of Args to determine argc & argv, and the contents of
440 // EnvVars to determine envp.
442 Function *EntryFn = Mod->getFunction(EntryFunc);
444 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
448 // If the program doesn't explicitly call exit, we will need the Exit
449 // function later on to make an explicit call, so get the function now.
450 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
451 Type::getInt32Ty(Context),
454 // Reset errno to zero on entry to main.
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 // Run static constructors.
463 if (UseMCJIT && !ForceInterpreter) {
464 // Give MCJIT a chance to apply relocations and set page permissions.
465 EE->finalizeObject();
467 EE->runStaticConstructorsDestructors(false);
470 if (NoLazyCompilation) {
471 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
473 if (Fn != EntryFn && !Fn->isDeclaration())
474 EE->getPointerToFunction(Fn);
480 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(RTDyldMM);
481 // Everything is prepared now, so lay out our program for the target
482 // address space, assign the section addresses to resolve any relocations,
483 // and send it to the target.
487 // Ask for a pointer to the entry function. This triggers the actual
489 (void)EE->getPointerToFunction(EntryFn);
491 // Enough has been compiled to execute the entry function now, so
492 // layout the target memory.
493 layoutRemoteTargetMemory(&Target, MM);
495 // Since we're executing in a (at least simulated) remote address space,
496 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
497 // grab the function address directly here and tell the remote target
498 // to execute the function.
499 // FIXME: argv and envp handling.
500 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
502 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
503 << format("%llx", Entry) << "\n");
505 if (Target.executeCode(Entry, Result))
506 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
510 // Trigger compilation separately so code regions that need to be
511 // invalidated will be known.
512 (void)EE->getPointerToFunction(EntryFn);
513 // Clear instruction cache before code will be executed.
515 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
518 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
521 // Like static constructors, the remote target MCJIT support doesn't handle
522 // this yet. It could. FIXME.
524 // Run static destructors.
525 EE->runStaticConstructorsDestructors(true);
527 // If the program didn't call exit explicitly, we should call it now.
528 // This ensures that any atexit handlers get called correctly.
529 if (Function *ExitF = dyn_cast<Function>(Exit)) {
530 std::vector<GenericValue> Args;
531 GenericValue ResultGV;
532 ResultGV.IntVal = APInt(32, Result);
533 Args.push_back(ResultGV);
534 EE->runFunction(ExitF, Args);
535 errs() << "ERROR: exit(" << Result << ") returned!\n";
538 errs() << "ERROR: exit defined with wrong prototype!\n";