Simplify code a bit, print error message always instead of asserting.
[oota-llvm.git] / lib / ExecutionEngine / JIT / JIT.cpp
1 //===-- JIT.cpp - LLVM Just in Time 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 tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bytecode in an efficient manner.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "JIT.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetJITInfo.h"
25 #include "Support/DynamicLinker.h"
26 #include <iostream>
27
28 using namespace llvm;
29
30 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
31   : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
32   setTargetData(TM.getTargetData());
33
34   // Initialize MCE
35   MCE = createEmitter(*this);
36   
37   // Add target data
38   PM.add (new TargetData (TM.getTargetData ()));
39
40   // Compile LLVM Code down to machine code in the intermediate representation
41   TJI.addPassesToJITCompile(PM);
42
43   // Turn the machine code intermediate representation into bytes in memory that
44   // may be executed.
45   if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
46     std::cerr << "lli: target '" << TM.getName()
47               << "' doesn't support machine code emission!\n";
48     abort();
49   }
50 }
51
52 JIT::~JIT() {
53   delete MCE;
54   delete &TM;
55 }
56
57 /// run - Start execution with the specified function and arguments.
58 ///
59 GenericValue JIT::runFunction(Function *F,
60                               const std::vector<GenericValue> &ArgValues) {
61   assert(F && "Function *F was null at entry to run()");
62   GenericValue rv;
63
64   void *FPtr = getPointerToFunction(F);
65   assert(PFtr && "Pointer to fn's code was null after getPointerToFunction");
66
67   if (ArgValues.size() == 3) {
68     int (*PF)(int, char **, const char **) =
69       (int(*)(int, char **, const char **))FPtr;
70     
71     // Call the function.
72     rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
73                    (const char **)GVTOP(ArgValues[2]));
74     return rv;
75   } else if (ArgValues.size() == 1) {
76     int (*PF)(int) = (int(*)(int))FPtr;
77     rv.IntVal = PF(ArgValues[0].IntVal);
78     return rv;
79   }
80
81   // FIXME: This code should handle a couple of common cases efficiently, but
82   // it should also implement the general case by code-gening a new anonymous
83   // nullary function to call.
84   std::cerr << "Sorry, unimplemented feature in the LLVM JIT.  See LLVM"
85             << " PR#419\n for details.\n";
86   abort();
87   return rv;
88 }
89
90 /// runJITOnFunction - Run the FunctionPassManager full of
91 /// just-in-time compilation passes on F, hopefully filling in
92 /// GlobalAddress[F] with the address of F's machine code.
93 ///
94 void JIT::runJITOnFunction(Function *F) {
95   static bool isAlreadyCodeGenerating = false;
96   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
97
98   // JIT the function
99   isAlreadyCodeGenerating = true;
100   PM.run(*F);
101   isAlreadyCodeGenerating = false;
102
103   // If the function referred to a global variable that had not yet been
104   // emitted, it allocates memory for the global, but doesn't emit it yet.  Emit
105   // all of these globals now.
106   while (!PendingGlobals.empty()) {
107     const GlobalVariable *GV = PendingGlobals.back();
108     PendingGlobals.pop_back();
109     EmitGlobalVariable(GV);
110   }
111 }
112
113 /// getPointerToFunction - This method is used to get the address of the
114 /// specified function, compiling it if neccesary.
115 ///
116 void *JIT::getPointerToFunction(Function *F) {
117   if (void *Addr = getPointerToGlobalIfAvailable(F))
118     return Addr;   // Check if function already code gen'd
119
120   // Make sure we read in the function if it exists in this Module
121   try {
122     MP->materializeFunction(F);
123   } catch ( std::string& errmsg ) {
124     std::cerr << "Error reading bytecode file: " << errmsg << "\n";
125     abort();
126   } catch (...) {
127     std::cerr << "Error reading bytecode file!\n";
128     abort();
129   }
130
131   if (F->isExternal()) {
132     void *Addr = getPointerToNamedFunction(F->getName());
133     addGlobalMapping(F, Addr);
134     return Addr;
135   }
136
137   runJITOnFunction(F);
138
139   void *Addr = getPointerToGlobalIfAvailable(F);
140   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
141   return Addr;
142 }
143
144 // getPointerToFunctionOrStub - If the specified function has been
145 // code-gen'd, return a pointer to the function.  If not, compile it, or use
146 // a stub to implement lazy compilation if available.
147 //
148 void *JIT::getPointerToFunctionOrStub(Function *F) {
149   // If we have already code generated the function, just return the address.
150   if (void *Addr = getPointerToGlobalIfAvailable(F))
151     return Addr;
152
153   // If the target supports "stubs" for functions, get a stub now.
154   if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
155     return Ptr;
156
157   // Otherwise, if the target doesn't support it, just codegen the function.
158   return getPointerToFunction(F);
159 }
160
161 /// getOrEmitGlobalVariable - Return the address of the specified global
162 /// variable, possibly emitting it to memory if needed.  This is used by the
163 /// Emitter.
164 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
165   void *Ptr = getPointerToGlobalIfAvailable(GV);
166   if (Ptr) return Ptr;
167
168   // If the global is external, just remember the address.
169   if (GV->isExternal()) {
170     Ptr = GetAddressOfSymbol(GV->getName().c_str());
171     if (Ptr == 0) {
172       std::cerr << "Could not resolve external global address: "
173                 << GV->getName() << "\n";
174       abort();
175     }
176   } else {
177     // If the global hasn't been emitted to memory yet, allocate space.  We will
178     // actually initialize the global after current function has finished
179     // compilation.
180     Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
181     PendingGlobals.push_back(GV);
182   }
183   addGlobalMapping(GV, Ptr);
184   return Ptr;
185 }
186
187
188 /// recompileAndRelinkFunction - This method is used to force a function
189 /// which has already been compiled, to be compiled again, possibly
190 /// after it has been modified. Then the entry to the old copy is overwritten
191 /// with a branch to the new copy. If there was no old copy, this acts
192 /// just like JIT::getPointerToFunction().
193 ///
194 void *JIT::recompileAndRelinkFunction(Function *F) {
195   void *OldAddr = getPointerToGlobalIfAvailable(F);
196
197   // If it's not already compiled there is no reason to patch it up.
198   if (OldAddr == 0) { return getPointerToFunction(F); }
199
200   // Delete the old function mapping.
201   addGlobalMapping(F, 0);
202
203   // Recodegen the function
204   runJITOnFunction(F);
205
206   // Update state, forward the old function to the new function.
207   void *Addr = getPointerToGlobalIfAvailable(F);
208   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
209   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
210   return Addr;
211 }