Fixed some bugs.
[llvm/zpu.git] / tools / lli / lli.cpp
blobadc6e90eb99a9c02fd492da28c3be3a463f2990d
1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/Support/CommandLine.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/PluginLoader.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/System/Process.h"
33 #include "llvm/System/Signals.h"
34 #include "llvm/Target/TargetSelect.h"
35 #include <cerrno>
37 #ifdef __CYGWIN__
38 #include <cygwin/version.h>
39 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
40 #define DO_NOTHING_ATEXIT 1
41 #endif
42 #endif
44 using namespace llvm;
46 namespace {
47 cl::opt<std::string>
48 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
50 cl::list<std::string>
51 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
53 cl::opt<bool> ForceInterpreter("force-interpreter",
54 cl::desc("Force interpretation: disable JIT"),
55 cl::init(false));
57 // Determine optimization level.
58 cl::opt<char>
59 OptLevel("O",
60 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
61 "(default = '-O2')"),
62 cl::Prefix,
63 cl::ZeroOrMore,
64 cl::init(' '));
66 cl::opt<std::string>
67 TargetTriple("mtriple", cl::desc("Override target triple for module"));
69 cl::opt<std::string>
70 MArch("march",
71 cl::desc("Architecture to generate assembly for (see --version)"));
73 cl::opt<std::string>
74 MCPU("mcpu",
75 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
76 cl::value_desc("cpu-name"),
77 cl::init(""));
79 cl::list<std::string>
80 MAttrs("mattr",
81 cl::CommaSeparated,
82 cl::desc("Target specific attributes (-mattr=help for details)"),
83 cl::value_desc("a1,+a2,-a3,..."));
85 cl::opt<std::string>
86 EntryFunc("entry-function",
87 cl::desc("Specify the entry function (default = 'main') "
88 "of the executable"),
89 cl::value_desc("function"),
90 cl::init("main"));
92 cl::opt<std::string>
93 FakeArgv0("fake-argv0",
94 cl::desc("Override the 'argv[0]' value passed into the executing"
95 " program"), cl::value_desc("executable"));
97 cl::opt<bool>
98 DisableCoreFiles("disable-core-files", cl::Hidden,
99 cl::desc("Disable emission of core files if possible"));
101 cl::opt<bool>
102 NoLazyCompilation("disable-lazy-compilation",
103 cl::desc("Disable JIT lazy compilation"),
104 cl::init(false));
107 static ExecutionEngine *EE = 0;
109 static void do_shutdown() {
110 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
111 #ifndef DO_NOTHING_ATEXIT
112 delete EE;
113 llvm_shutdown();
114 #endif
117 //===----------------------------------------------------------------------===//
118 // main Driver function
120 int main(int argc, char **argv, char * const *envp) {
121 sys::PrintStackTraceOnErrorSignal();
122 PrettyStackTraceProgram X(argc, argv);
124 LLVMContext &Context = getGlobalContext();
125 atexit(do_shutdown); // Call llvm_shutdown() on exit.
127 // If we have a native target, initialize it to ensure it is linked in and
128 // usable by the JIT.
129 InitializeNativeTarget();
131 cl::ParseCommandLineOptions(argc, argv,
132 "llvm interpreter & dynamic compiler\n");
134 // If the user doesn't want core files, disable them.
135 if (DisableCoreFiles)
136 sys::Process::PreventCoreFiles();
138 // Load the bitcode...
139 std::string ErrorMsg;
140 Module *Mod = NULL;
141 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)){
142 Mod = getLazyBitcodeModule(Buffer, Context, &ErrorMsg);
143 if (!Mod) delete Buffer;
146 if (!Mod) {
147 errs() << argv[0] << ": error loading program '" << InputFile << "': "
148 << ErrorMsg << "\n";
149 exit(1);
152 // If not jitting lazily, load the whole bitcode file eagerly too.
153 if (NoLazyCompilation) {
154 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
155 errs() << argv[0] << ": bitcode didn't read correctly.\n";
156 errs() << "Reason: " << ErrorMsg << "\n";
157 exit(1);
161 EngineBuilder builder(Mod);
162 builder.setMArch(MArch);
163 builder.setMCPU(MCPU);
164 builder.setMAttrs(MAttrs);
165 builder.setErrorStr(&ErrorMsg);
166 builder.setEngineKind(ForceInterpreter
167 ? EngineKind::Interpreter
168 : EngineKind::JIT);
170 // If we are supposed to override the target triple, do so now.
171 if (!TargetTriple.empty())
172 Mod->setTargetTriple(Triple::normalize(TargetTriple));
174 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
175 switch (OptLevel) {
176 default:
177 errs() << argv[0] << ": invalid optimization level.\n";
178 return 1;
179 case ' ': break;
180 case '0': OLvl = CodeGenOpt::None; break;
181 case '1': OLvl = CodeGenOpt::Less; break;
182 case '2': OLvl = CodeGenOpt::Default; break;
183 case '3': OLvl = CodeGenOpt::Aggressive; break;
185 builder.setOptLevel(OLvl);
187 EE = builder.create();
188 if (!EE) {
189 if (!ErrorMsg.empty())
190 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
191 else
192 errs() << argv[0] << ": unknown error creating EE!\n";
193 exit(1);
196 EE->RegisterJITEventListener(createOProfileJITEventListener());
198 EE->DisableLazyCompilation(NoLazyCompilation);
200 // If the user specifically requested an argv[0] to pass into the program,
201 // do it now.
202 if (!FakeArgv0.empty()) {
203 InputFile = FakeArgv0;
204 } else {
205 // Otherwise, if there is a .bc suffix on the executable strip it off, it
206 // might confuse the program.
207 if (StringRef(InputFile).endswith(".bc"))
208 InputFile.erase(InputFile.length() - 3);
211 // Add the module's name to the start of the vector of arguments to main().
212 InputArgv.insert(InputArgv.begin(), InputFile);
214 // Call the main function from M as if its signature were:
215 // int main (int argc, char **argv, const char **envp)
216 // using the contents of Args to determine argc & argv, and the contents of
217 // EnvVars to determine envp.
219 Function *EntryFn = Mod->getFunction(EntryFunc);
220 if (!EntryFn) {
221 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
222 return -1;
225 // If the program doesn't explicitly call exit, we will need the Exit
226 // function later on to make an explicit call, so get the function now.
227 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
228 Type::getInt32Ty(Context),
229 NULL);
231 // Reset errno to zero on entry to main.
232 errno = 0;
234 // Run static constructors.
235 EE->runStaticConstructorsDestructors(false);
237 if (NoLazyCompilation) {
238 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
239 Function *Fn = &*I;
240 if (Fn != EntryFn && !Fn->isDeclaration())
241 EE->getPointerToFunction(Fn);
245 // Run main.
246 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
248 // Run static destructors.
249 EE->runStaticConstructorsDestructors(true);
251 // If the program didn't call exit explicitly, we should call it now.
252 // This ensures that any atexit handlers get called correctly.
253 if (Function *ExitF = dyn_cast<Function>(Exit)) {
254 std::vector<GenericValue> Args;
255 GenericValue ResultGV;
256 ResultGV.IntVal = APInt(32, Result);
257 Args.push_back(ResultGV);
258 EE->runFunction(ExitF, Args);
259 errs() << "ERROR: exit(" << Result << ") returned!\n";
260 abort();
261 } else {
262 errs() << "ERROR: exit defined with wrong prototype!\n";
263 abort();