Simplify code
[oota-llvm.git] / tools / lli / lli.cpp
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/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/ExecutionEngine/ExecutionEngine.h"
21 #include "llvm/ExecutionEngine/GenericValue.h"
22 #include "llvm/Target/TargetMachineImpls.h"
23 #include "llvm/Target/TargetData.h"
24 #include "Support/CommandLine.h"
25 #include "Support/Debug.h"
26 #include "Support/SystemUtils.h"
27
28 using namespace llvm;
29
30 namespace {
31   cl::opt<std::string>
32   InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));
33
34   cl::list<std::string>
35   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
36
37   cl::opt<bool> ForceInterpreter("force-interpreter",
38                                  cl::desc("Force interpretation: disable JIT"),
39                                  cl::init(false));
40
41   cl::opt<std::string>
42   FakeArgv0("fake-argv0",
43             cl::desc("Override the 'argv[0]' value passed into the executing"
44                      " program"), cl::value_desc("executable"));
45 }
46
47 static void *CreateArgv(ExecutionEngine *EE,
48                         const std::vector<std::string> &InputArgv) {
49   unsigned PtrSize = EE->getTargetData().getPointerSize();
50   char *Result = new char[(InputArgv.size()+1)*PtrSize];
51
52   DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
53   const Type *SBytePtr = PointerType::get(Type::SByteTy);
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*PtrSize),
65                            SBytePtr);
66   }
67
68   // Null terminate it
69   EE->StoreValueToMemory(PTOGV(0),
70                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
71                          SBytePtr);
72   return Result;
73 }
74
75 //===----------------------------------------------------------------------===//
76 // main Driver function
77 //
78 int main(int argc, char **argv, char * const *envp) {
79   cl::ParseCommandLineOptions(argc, argv,
80                               " llvm interpreter & dynamic compiler\n");
81
82   // Load the bytecode...
83   std::string ErrorMsg;
84   ModuleProvider *MP = 0;
85   try {
86     MP = getBytecodeModuleProvider(InputFile);
87   } catch (std::string &err) {
88     std::cerr << "Error loading program '" << InputFile << "': " << err << "\n";
89     exit(1);
90   }
91
92   ExecutionEngine *EE =
93     ExecutionEngine::create(MP, ForceInterpreter);
94   assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
95
96   // If the user specifically requested an argv[0] to pass into the program, do
97   // it now.
98   if (!FakeArgv0.empty()) {
99     InputFile = FakeArgv0;
100   } else {
101     // Otherwise, if there is a .bc suffix on the executable strip it off, it
102     // might confuse the program.
103     if (InputFile.rfind(".bc") == InputFile.length() - 3)
104       InputFile.erase(InputFile.length() - 3);
105   }
106
107   // Add the module's name to the start of the vector of arguments to main().
108   InputArgv.insert(InputArgv.begin(), InputFile);
109
110   // Call the main function from M as if its signature were:
111   //   int main (int argc, char **argv, const char **envp)
112   // using the contents of Args to determine argc & argv, and the contents of
113   // EnvVars to determine envp.
114   //
115   Function *Fn = MP->getModule()->getMainFunction();
116   if (!Fn) {
117     std::cerr << "'main' function not found in module.\n";
118     return -1;
119   }
120
121   std::vector<GenericValue> GVArgs;
122   GenericValue GVArgc;
123   GVArgc.IntVal = InputArgv.size();
124   GVArgs.push_back(GVArgc); // Arg #0 = argc.
125   GVArgs.push_back(PTOGV(CreateArgv(EE, InputArgv))); // Arg #1 = argv.
126   assert(((char **)GVTOP(GVArgs[1]))[0] && "argv[0] was null after CreateArgv");
127
128   std::vector<std::string> EnvVars;
129   for (unsigned i = 0; envp[i]; ++i)
130     EnvVars.push_back(envp[i]);
131   GVArgs.push_back(PTOGV(CreateArgv(EE, EnvVars))); // Arg #2 = envp.
132   GenericValue Result = EE->runFunction(Fn, GVArgs);
133
134   // If the program didn't explicitly call exit, call exit now, for the program.
135   // This ensures that any atexit handlers get called correctly.
136   Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy,
137                                                         Type::IntTy, 0);
138   
139   GVArgs.clear();
140   GVArgs.push_back(Result);
141   EE->runFunction(Exit, GVArgs);
142
143   std::cerr << "ERROR: exit(" << Result.IntVal << ") returned!\n";
144   abort();
145 }