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/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/Type.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/ExecutionEngine/Interpreter.h"
24 #include "llvm/ExecutionEngine/JIT.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/ExecutionEngine/MCJIT.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/IRReader.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/Process.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Target/TargetSelect.h"
40 #include <cygwin/version.h>
41 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
42 #define DO_NOTHING_ATEXIT 1
50 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
53 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
55 cl::opt<bool> ForceInterpreter("force-interpreter",
56 cl::desc("Force interpretation: disable JIT"),
59 cl::opt<bool> UseMCJIT(
60 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
63 // Determine optimization level.
66 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
73 TargetTriple("mtriple", cl::desc("Override target triple for module"));
77 cl::desc("Architecture to generate assembly for (see --version)"));
81 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
82 cl::value_desc("cpu-name"),
88 cl::desc("Target specific attributes (-mattr=help for details)"),
89 cl::value_desc("a1,+a2,-a3,..."));
92 EntryFunc("entry-function",
93 cl::desc("Specify the entry function (default = 'main') "
95 cl::value_desc("function"),
99 FakeArgv0("fake-argv0",
100 cl::desc("Override the 'argv[0]' value passed into the executing"
101 " program"), cl::value_desc("executable"));
104 DisableCoreFiles("disable-core-files", cl::Hidden,
105 cl::desc("Disable emission of core files if possible"));
108 NoLazyCompilation("disable-lazy-compilation",
109 cl::desc("Disable JIT lazy compilation"),
112 cl::opt<Reloc::Model>
113 RelocModel("relocation-model",
114 cl::desc("Choose relocation model"),
115 cl::init(Reloc::Default),
117 clEnumValN(Reloc::Default, "default",
118 "Target default relocation model"),
119 clEnumValN(Reloc::Static, "static",
120 "Non-relocatable code"),
121 clEnumValN(Reloc::PIC_, "pic",
122 "Fully relocatable, position independent code"),
123 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
124 "Relocatable external references, non-relocatable code"),
127 cl::opt<llvm::CodeModel::Model>
128 CMModel("code-model",
129 cl::desc("Choose code model"),
130 cl::init(CodeModel::JITDefault),
131 cl::values(clEnumValN(CodeModel::JITDefault, "default",
132 "Target default JIT code model"),
133 clEnumValN(CodeModel::Small, "small",
135 clEnumValN(CodeModel::Kernel, "kernel",
136 "Kernel code model"),
137 clEnumValN(CodeModel::Medium, "medium",
138 "Medium code model"),
139 clEnumValN(CodeModel::Large, "large",
145 static ExecutionEngine *EE = 0;
147 static void do_shutdown() {
148 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
149 #ifndef DO_NOTHING_ATEXIT
155 //===----------------------------------------------------------------------===//
156 // main Driver function
158 int main(int argc, char **argv, char * const *envp) {
159 sys::PrintStackTraceOnErrorSignal();
160 PrettyStackTraceProgram X(argc, argv);
162 LLVMContext &Context = getGlobalContext();
163 atexit(do_shutdown); // Call llvm_shutdown() on exit.
165 // If we have a native target, initialize it to ensure it is linked in and
166 // usable by the JIT.
167 InitializeNativeTarget();
168 InitializeNativeTargetAsmPrinter();
170 cl::ParseCommandLineOptions(argc, argv,
171 "llvm interpreter & dynamic compiler\n");
173 // If the user doesn't want core files, disable them.
174 if (DisableCoreFiles)
175 sys::Process::PreventCoreFiles();
177 // Load the bitcode...
179 Module *Mod = ParseIRFile(InputFile, Err, Context);
181 Err.Print(argv[0], errs());
185 // If not jitting lazily, load the whole bitcode file eagerly too.
186 std::string ErrorMsg;
187 if (NoLazyCompilation) {
188 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
189 errs() << argv[0] << ": bitcode didn't read correctly.\n";
190 errs() << "Reason: " << ErrorMsg << "\n";
195 EngineBuilder builder(Mod);
196 builder.setMArch(MArch);
197 builder.setMCPU(MCPU);
198 builder.setMAttrs(MAttrs);
199 builder.setRelocationModel(RelocModel);
200 builder.setCodeModel(CMModel);
201 builder.setErrorStr(&ErrorMsg);
202 builder.setEngineKind(ForceInterpreter
203 ? EngineKind::Interpreter
206 // If we are supposed to override the target triple, do so now.
207 if (!TargetTriple.empty())
208 Mod->setTargetTriple(Triple::normalize(TargetTriple));
210 // Enable MCJIT, if desired.
212 builder.setUseMCJIT(true);
214 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
217 errs() << argv[0] << ": invalid optimization level.\n";
220 case '0': OLvl = CodeGenOpt::None; break;
221 case '1': OLvl = CodeGenOpt::Less; break;
222 case '2': OLvl = CodeGenOpt::Default; break;
223 case '3': OLvl = CodeGenOpt::Aggressive; break;
225 builder.setOptLevel(OLvl);
227 EE = builder.create();
229 if (!ErrorMsg.empty())
230 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
232 errs() << argv[0] << ": unknown error creating EE!\n";
236 EE->RegisterJITEventListener(createOProfileJITEventListener());
238 EE->DisableLazyCompilation(NoLazyCompilation);
240 // If the user specifically requested an argv[0] to pass into the program,
242 if (!FakeArgv0.empty()) {
243 InputFile = FakeArgv0;
245 // Otherwise, if there is a .bc suffix on the executable strip it off, it
246 // might confuse the program.
247 if (StringRef(InputFile).endswith(".bc"))
248 InputFile.erase(InputFile.length() - 3);
251 // Add the module's name to the start of the vector of arguments to main().
252 InputArgv.insert(InputArgv.begin(), InputFile);
254 // Call the main function from M as if its signature were:
255 // int main (int argc, char **argv, const char **envp)
256 // using the contents of Args to determine argc & argv, and the contents of
257 // EnvVars to determine envp.
259 Function *EntryFn = Mod->getFunction(EntryFunc);
261 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
265 // If the program doesn't explicitly call exit, we will need the Exit
266 // function later on to make an explicit call, so get the function now.
267 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
268 Type::getInt32Ty(Context),
271 // Reset errno to zero on entry to main.
274 // Run static constructors.
275 EE->runStaticConstructorsDestructors(false);
277 if (NoLazyCompilation) {
278 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
280 if (Fn != EntryFn && !Fn->isDeclaration())
281 EE->getPointerToFunction(Fn);
286 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
288 // Run static destructors.
289 EE->runStaticConstructorsDestructors(true);
291 // If the program didn't call exit explicitly, we should call it now.
292 // This ensures that any atexit handlers get called correctly.
293 if (Function *ExitF = dyn_cast<Function>(Exit)) {
294 std::vector<GenericValue> Args;
295 GenericValue ResultGV;
296 ResultGV.IntVal = APInt(32, Result);
297 Args.push_back(ResultGV);
298 EE->runFunction(ExitF, Args);
299 errs() << "ERROR: exit(" << Result << ") returned!\n";
302 errs() << "ERROR: exit defined with wrong prototype!\n";