lli.cpp revision 43f249adb711b7f05f16c8be1549323ccff21a50
1//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/Bytecode/Reader.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/PluginLoader.h"
26#include "llvm/System/Process.h"
27#include "llvm/System/Signals.h"
28#include <iostream>
29
30using namespace llvm;
31
32namespace {
33  cl::opt<std::string>
34  InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));
35
36  cl::list<std::string>
37  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
38
39  cl::opt<bool> ForceInterpreter("force-interpreter",
40                                 cl::desc("Force interpretation: disable JIT"),
41                                 cl::init(false));
42  cl::opt<std::string>
43  TargetTriple("mtriple", cl::desc("Override target triple for module"));
44
45  cl::opt<std::string>
46  FakeArgv0("fake-argv0",
47            cl::desc("Override the 'argv[0]' value passed into the executing"
48                     " program"), cl::value_desc("executable"));
49
50  cl::opt<bool>
51  DisableCoreFiles("disable-core-files", cl::Hidden,
52                   cl::desc("Disable emission of core files if possible"));
53}
54
55//===----------------------------------------------------------------------===//
56// main Driver function
57//
58int main(int argc, char **argv, char * const *envp) {
59  try {
60    cl::ParseCommandLineOptions(argc, argv,
61                                " llvm interpreter & dynamic compiler\n");
62    sys::PrintStackTraceOnErrorSignal();
63
64    // If the user doesn't want core files, disable them.
65    if (DisableCoreFiles)
66      sys::Process::PreventCoreFiles();
67
68    // Load the bytecode...
69    std::string ErrorMsg;
70    ModuleProvider *MP = 0;
71    MP = getBytecodeModuleProvider(InputFile, &ErrorMsg);
72    if (!MP) {
73      std::cerr << "Error loading program '" << InputFile << "': "
74                << ErrorMsg << "\n";
75      exit(1);
76    }
77
78    // If we are supposed to override the target triple, do so now.
79    if (!TargetTriple.empty())
80      MP->getModule()->setTargetTriple(TargetTriple);
81
82    ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter);
83    assert(EE &&"Couldn't create an ExecutionEngine, not even an interpreter?");
84
85    // If the user specifically requested an argv[0] to pass into the program,
86    // do it now.
87    if (!FakeArgv0.empty()) {
88      InputFile = FakeArgv0;
89    } else {
90      // Otherwise, if there is a .bc suffix on the executable strip it off, it
91      // might confuse the program.
92      if (InputFile.rfind(".bc") == InputFile.length() - 3)
93        InputFile.erase(InputFile.length() - 3);
94    }
95
96    // Add the module's name to the start of the vector of arguments to main().
97    InputArgv.insert(InputArgv.begin(), InputFile);
98
99    // Call the main function from M as if its signature were:
100    //   int main (int argc, char **argv, const char **envp)
101    // using the contents of Args to determine argc & argv, and the contents of
102    // EnvVars to determine envp.
103    //
104    Function *Fn = MP->getModule()->getMainFunction();
105    if (!Fn) {
106      std::cerr << "'main' function not found in module.\n";
107      return -1;
108    }
109
110    // Run static constructors.
111    EE->runStaticConstructorsDestructors(false);
112
113    // Run main.
114    int Result = EE->runFunctionAsMain(Fn, InputArgv, envp);
115
116    // Run static destructors.
117    EE->runStaticConstructorsDestructors(true);
118
119    // If the program didn't explicitly call exit, call exit now, for the
120    // program. This ensures that any atexit handlers get called correctly.
121    Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy,
122                                                          Type::IntTy,
123                                                          (Type *)0);
124
125    std::vector<GenericValue> Args;
126    GenericValue ResultGV;
127    ResultGV.IntVal = Result;
128    Args.push_back(ResultGV);
129    EE->runFunction(Exit, Args);
130
131    std::cerr << "ERROR: exit(" << Result << ") returned!\n";
132    abort();
133  } catch (const std::string& msg) {
134    std::cerr << argv[0] << ": " << msg << "\n";
135  } catch (...) {
136    std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
137  }
138  abort();
139}
140