lli.cpp revision 212793
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.
13//
14//===----------------------------------------------------------------------===//
15
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>
36using namespace llvm;
37
38namespace {
39  cl::opt<std::string>
40  InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
41
42  cl::list<std::string>
43  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
44
45  cl::opt<bool> ForceInterpreter("force-interpreter",
46                                 cl::desc("Force interpretation: disable JIT"),
47                                 cl::init(false));
48
49  // Determine optimization level.
50  cl::opt<char>
51  OptLevel("O",
52           cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
53                    "(default = '-O2')"),
54           cl::Prefix,
55           cl::ZeroOrMore,
56           cl::init(' '));
57
58  cl::opt<std::string>
59  TargetTriple("mtriple", cl::desc("Override target triple for module"));
60
61  cl::opt<std::string>
62  MArch("march",
63        cl::desc("Architecture to generate assembly for (see --version)"));
64
65  cl::opt<std::string>
66  MCPU("mcpu",
67       cl::desc("Target a specific cpu type (-mcpu=help for details)"),
68       cl::value_desc("cpu-name"),
69       cl::init(""));
70
71  cl::list<std::string>
72  MAttrs("mattr",
73         cl::CommaSeparated,
74         cl::desc("Target specific attributes (-mattr=help for details)"),
75         cl::value_desc("a1,+a2,-a3,..."));
76
77  cl::opt<std::string>
78  EntryFunc("entry-function",
79            cl::desc("Specify the entry function (default = 'main') "
80                     "of the executable"),
81            cl::value_desc("function"),
82            cl::init("main"));
83
84  cl::opt<std::string>
85  FakeArgv0("fake-argv0",
86            cl::desc("Override the 'argv[0]' value passed into the executing"
87                     " program"), cl::value_desc("executable"));
88
89  cl::opt<bool>
90  DisableCoreFiles("disable-core-files", cl::Hidden,
91                   cl::desc("Disable emission of core files if possible"));
92
93  cl::opt<bool>
94  NoLazyCompilation("disable-lazy-compilation",
95                  cl::desc("Disable JIT lazy compilation"),
96                  cl::init(false));
97}
98
99static ExecutionEngine *EE = 0;
100
101static void do_shutdown() {
102  delete EE;
103  llvm_shutdown();
104}
105
106//===----------------------------------------------------------------------===//
107// main Driver function
108//
109int main(int argc, char **argv, char * const *envp) {
110  sys::PrintStackTraceOnErrorSignal();
111  PrettyStackTraceProgram X(argc, argv);
112
113  LLVMContext &Context = getGlobalContext();
114  atexit(do_shutdown);  // Call llvm_shutdown() on exit.
115
116  // If we have a native target, initialize it to ensure it is linked in and
117  // usable by the JIT.
118  InitializeNativeTarget();
119
120  cl::ParseCommandLineOptions(argc, argv,
121                              "llvm interpreter & dynamic compiler\n");
122
123  // If the user doesn't want core files, disable them.
124  if (DisableCoreFiles)
125    sys::Process::PreventCoreFiles();
126
127  // Load the bitcode...
128  std::string ErrorMsg;
129  Module *Mod = NULL;
130  if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)){
131    Mod = getLazyBitcodeModule(Buffer, Context, &ErrorMsg);
132    if (!Mod) delete Buffer;
133  }
134
135  if (!Mod) {
136    errs() << argv[0] << ": error loading program '" << InputFile << "': "
137           << ErrorMsg << "\n";
138    exit(1);
139  }
140
141  // If not jitting lazily, load the whole bitcode file eagerly too.
142  if (NoLazyCompilation) {
143    if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
144      errs() << argv[0] << ": bitcode didn't read correctly.\n";
145      errs() << "Reason: " << ErrorMsg << "\n";
146      exit(1);
147    }
148  }
149
150  EngineBuilder builder(Mod);
151  builder.setMArch(MArch);
152  builder.setMCPU(MCPU);
153  builder.setMAttrs(MAttrs);
154  builder.setErrorStr(&ErrorMsg);
155  builder.setEngineKind(ForceInterpreter
156                        ? EngineKind::Interpreter
157                        : EngineKind::JIT);
158
159  // If we are supposed to override the target triple, do so now.
160  if (!TargetTriple.empty())
161    Mod->setTargetTriple(Triple::normalize(TargetTriple));
162
163  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
164  switch (OptLevel) {
165  default:
166    errs() << argv[0] << ": invalid optimization level.\n";
167    return 1;
168  case ' ': break;
169  case '0': OLvl = CodeGenOpt::None; break;
170  case '1': OLvl = CodeGenOpt::Less; break;
171  case '2': OLvl = CodeGenOpt::Default; break;
172  case '3': OLvl = CodeGenOpt::Aggressive; break;
173  }
174  builder.setOptLevel(OLvl);
175
176  EE = builder.create();
177  if (!EE) {
178    if (!ErrorMsg.empty())
179      errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
180    else
181      errs() << argv[0] << ": unknown error creating EE!\n";
182    exit(1);
183  }
184
185  EE->RegisterJITEventListener(createOProfileJITEventListener());
186
187  EE->DisableLazyCompilation(NoLazyCompilation);
188
189  // If the user specifically requested an argv[0] to pass into the program,
190  // do it now.
191  if (!FakeArgv0.empty()) {
192    InputFile = FakeArgv0;
193  } else {
194    // Otherwise, if there is a .bc suffix on the executable strip it off, it
195    // might confuse the program.
196    if (StringRef(InputFile).endswith(".bc"))
197      InputFile.erase(InputFile.length() - 3);
198  }
199
200  // Add the module's name to the start of the vector of arguments to main().
201  InputArgv.insert(InputArgv.begin(), InputFile);
202
203  // Call the main function from M as if its signature were:
204  //   int main (int argc, char **argv, const char **envp)
205  // using the contents of Args to determine argc & argv, and the contents of
206  // EnvVars to determine envp.
207  //
208  Function *EntryFn = Mod->getFunction(EntryFunc);
209  if (!EntryFn) {
210    errs() << '\'' << EntryFunc << "\' function not found in module.\n";
211    return -1;
212  }
213
214  // If the program doesn't explicitly call exit, we will need the Exit
215  // function later on to make an explicit call, so get the function now.
216  Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
217                                                    Type::getInt32Ty(Context),
218                                                    NULL);
219
220  // Reset errno to zero on entry to main.
221  errno = 0;
222
223  // Run static constructors.
224  EE->runStaticConstructorsDestructors(false);
225
226  if (NoLazyCompilation) {
227    for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
228      Function *Fn = &*I;
229      if (Fn != EntryFn && !Fn->isDeclaration())
230        EE->getPointerToFunction(Fn);
231    }
232  }
233
234  // Run main.
235  int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
236
237  // Run static destructors.
238  EE->runStaticConstructorsDestructors(true);
239
240  // If the program didn't call exit explicitly, we should call it now.
241  // This ensures that any atexit handlers get called correctly.
242  if (Function *ExitF = dyn_cast<Function>(Exit)) {
243    std::vector<GenericValue> Args;
244    GenericValue ResultGV;
245    ResultGV.IntVal = APInt(32, Result);
246    Args.push_back(ResultGV);
247    EE->runFunction(ExitF, Args);
248    errs() << "ERROR: exit(" << Result << ") returned!\n";
249    abort();
250  } else {
251    errs() << "ERROR: exit defined with wrong prototype!\n";
252    abort();
253  }
254}
255