lli.cpp revision c4fb6fdd8677530d9b1db34b6254edb0094b78ed
1//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2//
3// This utility provides a way to execute LLVM bytecode without static
4// compilation.  This consists of a very simple and slow (but portable)
5// interpreter, along with capability for system specific dynamic compilers.  At
6// runtime, the fastest (stable) execution engine is selected to run the
7// program.  This means the JIT compiler for the current platform if it's
8// available.
9//
10//===----------------------------------------------------------------------===//
11
12#include "llvm/DerivedTypes.h"
13#include "llvm/Module.h"
14#include "llvm/ModuleProvider.h"
15#include "llvm/Bytecode/Reader.h"
16#include "llvm/ExecutionEngine/ExecutionEngine.h"
17#include "llvm/ExecutionEngine/GenericValue.h"
18#include "llvm/Target/TargetMachineImpls.h"
19#include "llvm/Target/TargetData.h"
20#include "Support/CommandLine.h"
21#include "Support/Debug.h"
22#include "Support/SystemUtils.h"
23
24namespace {
25  cl::opt<std::string>
26  InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));
27
28  cl::list<std::string>
29  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
30
31  cl::opt<std::string>
32  MainFunction("f", cl::desc("Function to execute"), cl::init("main"),
33               cl::value_desc("function name"));
34
35  cl::opt<bool> TraceMode("trace", cl::desc("Enable Tracing"));
36
37  cl::opt<bool> ForceInterpreter("force-interpreter",
38                                 cl::desc("Force interpretation: disable JIT"),
39                                 cl::init(false));
40}
41
42static std::vector<std::string> makeStringVector(char * const *envp) {
43  std::vector<std::string> rv;
44  for (unsigned i = 0; envp[i]; ++i)
45    rv.push_back(envp[i]);
46  return rv;
47}
48
49static void *CreateArgv(ExecutionEngine *EE,
50                        const std::vector<std::string> &InputArgv) {
51  if (EE->getTargetData().getPointerSize() == 8) {   // 64 bit target?
52    PointerTy *Result = new PointerTy[InputArgv.size()+1];
53    DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
54
55    for (unsigned i = 0; i < InputArgv.size(); ++i) {
56      unsigned Size = InputArgv[i].size()+1;
57      char *Dest = new char[Size];
58      DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
59
60      std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
61      Dest[Size-1] = 0;
62
63      // Endian safe: Result[i] = (PointerTy)Dest;
64      EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i),
65                             Type::LongTy);
66    }
67    Result[InputArgv.size()] = 0;
68    return Result;
69  } else {                                      // 32 bit target?
70    int *Result = new int[InputArgv.size()+1];
71    DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
72
73    for (unsigned i = 0; i < InputArgv.size(); ++i) {
74      unsigned Size = InputArgv[i].size()+1;
75      char *Dest = new char[Size];
76      DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
77
78      std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
79      Dest[Size-1] = 0;
80
81      // Endian safe: Result[i] = (PointerTy)Dest;
82      EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i),
83                             Type::IntTy);
84    }
85    Result[InputArgv.size()] = 0;  // null terminate it
86    return Result;
87  }
88}
89
90/// callAsMain - Call the function named FnName from M as if its
91/// signature were int main (int argc, char **argv, const char
92/// **envp), using the contents of Args to determine argc & argv, and
93/// the contents of EnvVars to determine envp.  Returns the result
94/// from calling FnName, or -1 and prints an error msg. if the named
95/// function cannot be found.
96///
97int callAsMain(ExecutionEngine *EE, ModuleProvider *MP,
98               const std::string &FnName,
99               const std::vector<std::string> &Args,
100               const std::vector<std::string> &EnvVars) {
101  Function *Fn = MP->getModule()->getNamedFunction(FnName);
102  if (!Fn) {
103    std::cerr << "Function '" << FnName << "' not found in module.\n";
104    return -1;
105  }
106  std::vector<GenericValue> GVArgs;
107  GenericValue GVArgc;
108  GVArgc.IntVal = Args.size();
109  GVArgs.push_back(GVArgc); // Arg #0 = argc.
110  GVArgs.push_back(PTOGV(CreateArgv(EE, Args))); // Arg #1 = argv.
111  GVArgs.push_back(PTOGV(CreateArgv(EE, EnvVars))); // Arg #2 = envp.
112  return EE->run(Fn, GVArgs).IntVal;
113}
114
115//===----------------------------------------------------------------------===//
116// main Driver function
117//
118int main(int argc, char **argv, char * const *envp) {
119  cl::ParseCommandLineOptions(argc, argv,
120                              " llvm interpreter & dynamic compiler\n");
121
122  // Load the bytecode...
123  std::string ErrorMsg;
124  ModuleProvider *MP = 0;
125  try {
126    MP = getBytecodeModuleProvider(InputFile);
127  } catch (std::string &err) {
128    std::cerr << "Error parsing '" << InputFile << "': " << err << "\n";
129    exit(1);
130  }
131
132  ExecutionEngine *EE =
133    ExecutionEngine::create(MP, ForceInterpreter, TraceMode);
134  assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
135
136  // Add the module's name to the start of the vector of arguments to main().
137  // But delete .bc first, since programs (and users) might not expect to
138  // see it.
139  const std::string ByteCodeFileSuffix(".bc");
140  if (InputFile.rfind(ByteCodeFileSuffix) ==
141      InputFile.length() - ByteCodeFileSuffix.length()) {
142    InputFile.erase (InputFile.length() - ByteCodeFileSuffix.length());
143  }
144  InputArgv.insert(InputArgv.begin(), InputFile);
145
146  // Run the main function!
147  int ExitCode = callAsMain(EE, MP, MainFunction, InputArgv,
148                            makeStringVector(envp));
149
150  // Now that we are done executing the program, shut down the execution engine
151  delete EE;
152  return ExitCode;
153}
154