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/JITMemoryManager.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/Process.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/TargetSelect.h"
41 #include <cygwin/version.h>
42 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
43 #define DO_NOTHING_ATEXIT 1
51 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
54 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
56 cl::opt<bool> ForceInterpreter("force-interpreter",
57 cl::desc("Force interpretation: disable JIT"),
60 cl::opt<bool> UseMCJIT(
61 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
64 // Determine optimization level.
67 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
74 TargetTriple("mtriple", cl::desc("Override target triple for module"));
78 cl::desc("Architecture to generate assembly for (see --version)"));
82 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
83 cl::value_desc("cpu-name"),
89 cl::desc("Target specific attributes (-mattr=help for details)"),
90 cl::value_desc("a1,+a2,-a3,..."));
93 EntryFunc("entry-function",
94 cl::desc("Specify the entry function (default = 'main') "
96 cl::value_desc("function"),
100 FakeArgv0("fake-argv0",
101 cl::desc("Override the 'argv[0]' value passed into the executing"
102 " program"), cl::value_desc("executable"));
105 DisableCoreFiles("disable-core-files", cl::Hidden,
106 cl::desc("Disable emission of core files if possible"));
109 NoLazyCompilation("disable-lazy-compilation",
110 cl::desc("Disable JIT lazy compilation"),
113 cl::opt<Reloc::Model>
114 RelocModel("relocation-model",
115 cl::desc("Choose relocation model"),
116 cl::init(Reloc::Default),
118 clEnumValN(Reloc::Default, "default",
119 "Target default relocation model"),
120 clEnumValN(Reloc::Static, "static",
121 "Non-relocatable code"),
122 clEnumValN(Reloc::PIC_, "pic",
123 "Fully relocatable, position independent code"),
124 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
125 "Relocatable external references, non-relocatable code"),
128 cl::opt<llvm::CodeModel::Model>
129 CMModel("code-model",
130 cl::desc("Choose code model"),
131 cl::init(CodeModel::JITDefault),
132 cl::values(clEnumValN(CodeModel::JITDefault, "default",
133 "Target default JIT code model"),
134 clEnumValN(CodeModel::Small, "small",
136 clEnumValN(CodeModel::Kernel, "kernel",
137 "Kernel code model"),
138 clEnumValN(CodeModel::Medium, "medium",
139 "Medium code model"),
140 clEnumValN(CodeModel::Large, "large",
146 static ExecutionEngine *EE = 0;
148 static void do_shutdown() {
149 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
150 #ifndef DO_NOTHING_ATEXIT
156 //===----------------------------------------------------------------------===//
157 // main Driver function
159 int main(int argc, char **argv, char * const *envp) {
160 sys::PrintStackTraceOnErrorSignal();
161 PrettyStackTraceProgram X(argc, argv);
163 LLVMContext &Context = getGlobalContext();
164 atexit(do_shutdown); // Call llvm_shutdown() on exit.
166 // If we have a native target, initialize it to ensure it is linked in and
167 // usable by the JIT.
168 InitializeNativeTarget();
169 InitializeNativeTargetAsmPrinter();
171 cl::ParseCommandLineOptions(argc, argv,
172 "llvm interpreter & dynamic compiler\n");
174 // If the user doesn't want core files, disable them.
175 if (DisableCoreFiles)
176 sys::Process::PreventCoreFiles();
178 // Load the bitcode...
180 Module *Mod = ParseIRFile(InputFile, Err, Context);
182 Err.print(argv[0], errs());
186 // If not jitting lazily, load the whole bitcode file eagerly too.
187 std::string ErrorMsg;
188 if (NoLazyCompilation) {
189 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
190 errs() << argv[0] << ": bitcode didn't read correctly.\n";
191 errs() << "Reason: " << ErrorMsg << "\n";
196 EngineBuilder builder(Mod);
197 builder.setMArch(MArch);
198 builder.setMCPU(MCPU);
199 builder.setMAttrs(MAttrs);
200 builder.setRelocationModel(RelocModel);
201 builder.setCodeModel(CMModel);
202 builder.setErrorStr(&ErrorMsg);
203 builder.setJITMemoryManager(ForceInterpreter ? 0 :
204 JITMemoryManager::CreateDefaultMemManager());
205 builder.setEngineKind(ForceInterpreter
206 ? EngineKind::Interpreter
209 // If we are supposed to override the target triple, do so now.
210 if (!TargetTriple.empty())
211 Mod->setTargetTriple(Triple::normalize(TargetTriple));
213 // Enable MCJIT if desired.
214 if (UseMCJIT && !ForceInterpreter) {
215 builder.setUseMCJIT(true);
216 builder.setJITMemoryManager(JITMemoryManager::CreateDefaultMemManager());
219 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
222 errs() << argv[0] << ": invalid optimization level.\n";
225 case '0': OLvl = CodeGenOpt::None; break;
226 case '1': OLvl = CodeGenOpt::Less; break;
227 case '2': OLvl = CodeGenOpt::Default; break;
228 case '3': OLvl = CodeGenOpt::Aggressive; break;
230 builder.setOptLevel(OLvl);
232 EE = builder.create();
234 if (!ErrorMsg.empty())
235 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
237 errs() << argv[0] << ": unknown error creating EE!\n";
241 EE->RegisterJITEventListener(createOProfileJITEventListener());
243 EE->DisableLazyCompilation(NoLazyCompilation);
245 // If the user specifically requested an argv[0] to pass into the program,
247 if (!FakeArgv0.empty()) {
248 InputFile = FakeArgv0;
250 // Otherwise, if there is a .bc suffix on the executable strip it off, it
251 // might confuse the program.
252 if (StringRef(InputFile).endswith(".bc"))
253 InputFile.erase(InputFile.length() - 3);
256 // Add the module's name to the start of the vector of arguments to main().
257 InputArgv.insert(InputArgv.begin(), InputFile);
259 // Call the main function from M as if its signature were:
260 // int main (int argc, char **argv, const char **envp)
261 // using the contents of Args to determine argc & argv, and the contents of
262 // EnvVars to determine envp.
264 Function *EntryFn = Mod->getFunction(EntryFunc);
266 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
270 // If the program doesn't explicitly call exit, we will need the Exit
271 // function later on to make an explicit call, so get the function now.
272 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
273 Type::getInt32Ty(Context),
276 // Reset errno to zero on entry to main.
279 // Run static constructors.
280 EE->runStaticConstructorsDestructors(false);
282 if (NoLazyCompilation) {
283 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
285 if (Fn != EntryFn && !Fn->isDeclaration())
286 EE->getPointerToFunction(Fn);
291 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
293 // Run static destructors.
294 EE->runStaticConstructorsDestructors(true);
296 // If the program didn't call exit explicitly, we should call it now.
297 // This ensures that any atexit handlers get called correctly.
298 if (Function *ExitF = dyn_cast<Function>(Exit)) {
299 std::vector<GenericValue> Args;
300 GenericValue ResultGV;
301 ResultGV.IntVal = APInt(32, Result);
302 Args.push_back(ResultGV);
303 EE->runFunction(ExitF, Args);
304 errs() << "ERROR: exit(" << Result << ") returned!\n";
307 errs() << "ERROR: exit defined with wrong prototype!\n";