switch to using llvm/Target/TargetSelect.h
[oota-llvm.git] / tools / lli / lli.cpp
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 intepreter if no JIT is available for this platform.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/Type.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/ExecutionEngine/JIT.h"
22 #include "llvm/ExecutionEngine/Interpreter.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/PluginLoader.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/System/Process.h"
30 #include "llvm/System/Signals.h"
31 #include "llvm/Target/TargetSelect.h"
32 #include <iostream>
33 #include <cerrno>
34 using namespace llvm;
35
36 namespace {
37   cl::opt<std::string>
38   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
39
40   cl::list<std::string>
41   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
42
43   cl::opt<bool> ForceInterpreter("force-interpreter",
44                                  cl::desc("Force interpretation: disable JIT"),
45                                  cl::init(false));
46
47   // Determine optimization level.
48   cl::opt<char>
49   OptLevel("O",
50            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
51                     "(default = '-O2')"),
52            cl::Prefix,
53            cl::ZeroOrMore,
54            cl::init(' '));
55
56   cl::opt<std::string>
57   TargetTriple("mtriple", cl::desc("Override target triple for module"));
58
59   cl::opt<std::string>
60   EntryFunc("entry-function",
61             cl::desc("Specify the entry function (default = 'main') "
62                      "of the executable"),
63             cl::value_desc("function"),
64             cl::init("main"));
65   
66   cl::opt<std::string>
67   FakeArgv0("fake-argv0",
68             cl::desc("Override the 'argv[0]' value passed into the executing"
69                      " program"), cl::value_desc("executable"));
70   
71   cl::opt<bool>
72   DisableCoreFiles("disable-core-files", cl::Hidden,
73                    cl::desc("Disable emission of core files if possible"));
74
75   cl::opt<bool>
76   NoLazyCompilation("disable-lazy-compilation",
77                   cl::desc("Disable JIT lazy compilation"),
78                   cl::init(false));
79 }
80
81 static ExecutionEngine *EE = 0;
82
83 static void do_shutdown() {
84   delete EE;
85   llvm_shutdown();
86 }
87
88 //===----------------------------------------------------------------------===//
89 // main Driver function
90 //
91 int main(int argc, char **argv, char * const *envp) {
92   sys::PrintStackTraceOnErrorSignal();
93   PrettyStackTraceProgram X(argc, argv);
94   
95   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
96   cl::ParseCommandLineOptions(argc, argv,
97                               "llvm interpreter & dynamic compiler\n");
98
99   // If the user doesn't want core files, disable them.
100   if (DisableCoreFiles)
101     sys::Process::PreventCoreFiles();
102   
103   // Load the bitcode...
104   std::string ErrorMsg;
105   ModuleProvider *MP = NULL;
106   if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)) {
107     MP = getBitcodeModuleProvider(Buffer, &ErrorMsg);
108     if (!MP) delete Buffer;
109   }
110   
111   if (!MP) {
112     std::cerr << argv[0] << ": error loading program '" << InputFile << "': "
113               << ErrorMsg << "\n";
114     exit(1);
115   }
116
117   // Get the module as the MP could go away once EE takes over.
118   Module *Mod = NoLazyCompilation
119     ? MP->materializeModule(&ErrorMsg) : MP->getModule();
120   if (!Mod) {
121     std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
122     std::cerr << "Reason: " << ErrorMsg << "\n";
123     exit(1);
124   }
125
126   // If we are supposed to override the target triple, do so now.
127   if (!TargetTriple.empty())
128     Mod->setTargetTriple(TargetTriple);
129
130   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
131   switch (OptLevel) {
132   default:
133     std::cerr << argv[0] << ": invalid optimization level.\n";
134     return 1;
135   case ' ': break;
136   case '0': OLvl = CodeGenOpt::None; break;
137   case '1':
138   case '2': OLvl = CodeGenOpt::Default; break;
139   case '3': OLvl = CodeGenOpt::Aggressive; break;
140   }
141   
142   // If we have a native target, initialize it to ensure it is linked in and
143   // usable by the JIT.
144   InitializeNativeTarget();
145
146   EE = ExecutionEngine::create(MP, ForceInterpreter, &ErrorMsg, OLvl);
147   if (!EE && !ErrorMsg.empty()) {
148     std::cerr << argv[0] << ":error creating EE: " << ErrorMsg << "\n";
149     exit(1);
150   }
151
152   if (NoLazyCompilation)
153     EE->DisableLazyCompilation();
154
155   // If the user specifically requested an argv[0] to pass into the program,
156   // do it now.
157   if (!FakeArgv0.empty()) {
158     InputFile = FakeArgv0;
159   } else {
160     // Otherwise, if there is a .bc suffix on the executable strip it off, it
161     // might confuse the program.
162     if (InputFile.rfind(".bc") == InputFile.length() - 3)
163       InputFile.erase(InputFile.length() - 3);
164   }
165
166   // Add the module's name to the start of the vector of arguments to main().
167   InputArgv.insert(InputArgv.begin(), InputFile);
168
169   // Call the main function from M as if its signature were:
170   //   int main (int argc, char **argv, const char **envp)
171   // using the contents of Args to determine argc & argv, and the contents of
172   // EnvVars to determine envp.
173   //
174   Function *EntryFn = Mod->getFunction(EntryFunc);
175   if (!EntryFn) {
176     std::cerr << '\'' << EntryFunc << "\' function not found in module.\n";
177     return -1;
178   }
179
180   // If the program doesn't explicitly call exit, we will need the Exit 
181   // function later on to make an explicit call, so get the function now. 
182   Constant *Exit = Mod->getOrInsertFunction("exit", Type::VoidTy,
183                                                         Type::Int32Ty, NULL);
184   
185   // Reset errno to zero on entry to main.
186   errno = 0;
187  
188   // Run static constructors.
189   EE->runStaticConstructorsDestructors(false);
190
191   if (NoLazyCompilation) {
192     for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
193       Function *Fn = &*I;
194       if (Fn != EntryFn && !Fn->isDeclaration())
195         EE->getPointerToFunction(Fn);
196     }
197   }
198
199   // Run main.
200   int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
201
202   // Run static destructors.
203   EE->runStaticConstructorsDestructors(true);
204   
205   // If the program didn't call exit explicitly, we should call it now. 
206   // This ensures that any atexit handlers get called correctly.
207   if (Function *ExitF = dyn_cast<Function>(Exit)) {
208     std::vector<GenericValue> Args;
209     GenericValue ResultGV;
210     ResultGV.IntVal = APInt(32, Result);
211     Args.push_back(ResultGV);
212     EE->runFunction(ExitF, Args);
213     std::cerr << "ERROR: exit(" << Result << ") returned!\n";
214     abort();
215   } else {
216     std::cerr << "ERROR: exit defined with wrong prototype!\n";
217     abort();
218   }
219 }