Eliminate all remaining tabs and trailing spaces.
[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/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/CodeGen/MachineCodeEmitter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include <iostream>
29
30 using namespace llvm;
31
32 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
33   : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
34   setTargetData(TM.getTargetData());
35
36   // Initialize MCE
37   MCE = createEmitter(*this);
38
39   // Add target data
40   MutexGuard locked(lock);
41   FunctionPassManager& PM = state.getPM(locked);
42   PM.add(new TargetData(TM.getTargetData()));
43
44   // Compile LLVM Code down to machine code in the intermediate representation
45   TJI.addPassesToJITCompile(PM);
46
47   // Turn the machine code intermediate representation into bytes in memory that
48   // may be executed.
49   if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
50     std::cerr << "Target '" << TM.getName()
51               << "' doesn't support machine code emission!\n";
52     abort();
53   }
54 }
55
56 JIT::~JIT() {
57   delete MCE;
58   delete &TM;
59 }
60
61 /// run - Start execution with the specified function and arguments.
62 ///
63 GenericValue JIT::runFunction(Function *F,
64                               const std::vector<GenericValue> &ArgValues) {
65   assert(F && "Function *F was null at entry to run()");
66
67   void *FPtr = getPointerToFunction(F);
68   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
69   const FunctionType *FTy = F->getFunctionType();
70   const Type *RetTy = FTy->getReturnType();
71
72   assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
73          "Too many arguments passed into function!");
74   assert(FTy->getNumParams() == ArgValues.size() &&
75          "This doesn't support passing arguments through varargs (yet)!");
76
77   // Handle some common cases first.  These cases correspond to common `main'
78   // prototypes.
79   if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
80     switch (ArgValues.size()) {
81     case 3:
82       if ((FTy->getParamType(0) == Type::IntTy ||
83            FTy->getParamType(0) == Type::UIntTy) &&
84           isa<PointerType>(FTy->getParamType(1)) &&
85           isa<PointerType>(FTy->getParamType(2))) {
86         int (*PF)(int, char **, const char **) =
87           (int(*)(int, char **, const char **))FPtr;
88
89         // Call the function.
90         GenericValue rv;
91         rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
92                        (const char **)GVTOP(ArgValues[2]));
93         return rv;
94       }
95       break;
96     case 2:
97       if ((FTy->getParamType(0) == Type::IntTy ||
98            FTy->getParamType(0) == Type::UIntTy) &&
99           isa<PointerType>(FTy->getParamType(1))) {
100         int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
101
102         // Call the function.
103         GenericValue rv;
104         rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
105         return rv;
106       }
107       break;
108     case 1:
109       if (FTy->getNumParams() == 1 &&
110           (FTy->getParamType(0) == Type::IntTy ||
111            FTy->getParamType(0) == Type::UIntTy)) {
112         GenericValue rv;
113         int (*PF)(int) = (int(*)(int))FPtr;
114         rv.IntVal = PF(ArgValues[0].IntVal);
115         return rv;
116       }
117       break;
118     }
119   }
120
121   // Handle cases where no arguments are passed first.
122   if (ArgValues.empty()) {
123     GenericValue rv;
124     switch (RetTy->getTypeID()) {
125     default: assert(0 && "Unknown return type for function call!");
126     case Type::BoolTyID:
127       rv.BoolVal = ((bool(*)())FPtr)();
128       return rv;
129     case Type::SByteTyID:
130     case Type::UByteTyID:
131       rv.SByteVal = ((char(*)())FPtr)();
132       return rv;
133     case Type::ShortTyID:
134     case Type::UShortTyID:
135       rv.ShortVal = ((short(*)())FPtr)();
136       return rv;
137     case Type::VoidTyID:
138     case Type::IntTyID:
139     case Type::UIntTyID:
140       rv.IntVal = ((int(*)())FPtr)();
141       return rv;
142     case Type::LongTyID:
143     case Type::ULongTyID:
144       rv.LongVal = ((int64_t(*)())FPtr)();
145       return rv;
146     case Type::FloatTyID:
147       rv.FloatVal = ((float(*)())FPtr)();
148       return rv;
149     case Type::DoubleTyID:
150       rv.DoubleVal = ((double(*)())FPtr)();
151       return rv;
152     case Type::PointerTyID:
153       return PTOGV(((void*(*)())FPtr)());
154     }
155   }
156
157   // Okay, this is not one of our quick and easy cases.  Because we don't have a
158   // full FFI, we have to codegen a nullary stub function that just calls the
159   // function we are interested in, passing in constants for all of the
160   // arguments.  Make this function and return.
161
162   // First, create the function.
163   FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
164   Function *Stub = new Function(STy, Function::InternalLinkage, "",
165                                 F->getParent());
166
167   // Insert a basic block.
168   BasicBlock *StubBB = new BasicBlock("", Stub);
169
170   // Convert all of the GenericValue arguments over to constants.  Note that we
171   // currently don't support varargs.
172   std::vector<Value*> Args;
173   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
174     Constant *C = 0;
175     const Type *ArgTy = FTy->getParamType(i);
176     const GenericValue &AV = ArgValues[i];
177     switch (ArgTy->getTypeID()) {
178     default: assert(0 && "Unknown argument type for function call!");
179     case Type::BoolTyID:   C = ConstantBool::get(AV.BoolVal); break;
180     case Type::SByteTyID:  C = ConstantSInt::get(ArgTy, AV.SByteVal);  break;
181     case Type::UByteTyID:  C = ConstantUInt::get(ArgTy, AV.UByteVal);  break;
182     case Type::ShortTyID:  C = ConstantSInt::get(ArgTy, AV.ShortVal);  break;
183     case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
184     case Type::IntTyID:    C = ConstantSInt::get(ArgTy, AV.IntVal);    break;
185     case Type::UIntTyID:   C = ConstantUInt::get(ArgTy, AV.UIntVal);   break;
186     case Type::LongTyID:   C = ConstantSInt::get(ArgTy, AV.LongVal);   break;
187     case Type::ULongTyID:  C = ConstantUInt::get(ArgTy, AV.ULongVal);  break;
188     case Type::FloatTyID:  C = ConstantFP  ::get(ArgTy, AV.FloatVal);  break;
189     case Type::DoubleTyID: C = ConstantFP  ::get(ArgTy, AV.DoubleVal); break;
190     case Type::PointerTyID:
191       void *ArgPtr = GVTOP(AV);
192       if (sizeof(void*) == 4) {
193         C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
194       } else {
195         C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
196       }
197       C = ConstantExpr::getCast(C, ArgTy);  // Cast the integer to pointer
198       break;
199     }
200     Args.push_back(C);
201   }
202
203   CallInst *TheCall = new CallInst(F, Args, "", StubBB);
204   TheCall->setTailCall();
205   if (TheCall->getType() != Type::VoidTy)
206     new ReturnInst(TheCall, StubBB);             // Return result of the call.
207   else
208     new ReturnInst(StubBB);                      // Just return void.
209
210   // Finally, return the value returned by our nullary stub function.
211   return runFunction(Stub, std::vector<GenericValue>());
212 }
213
214 /// runJITOnFunction - Run the FunctionPassManager full of
215 /// just-in-time compilation passes on F, hopefully filling in
216 /// GlobalAddress[F] with the address of F's machine code.
217 ///
218 void JIT::runJITOnFunction(Function *F) {
219   static bool isAlreadyCodeGenerating = false;
220   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
221
222   MutexGuard locked(lock);
223
224   // JIT the function
225   isAlreadyCodeGenerating = true;
226   state.getPM(locked).run(*F);
227   isAlreadyCodeGenerating = false;
228
229   // If the function referred to a global variable that had not yet been
230   // emitted, it allocates memory for the global, but doesn't emit it yet.  Emit
231   // all of these globals now.
232   while (!state.getPendingGlobals(locked).empty()) {
233     const GlobalVariable *GV = state.getPendingGlobals(locked).back();
234     state.getPendingGlobals(locked).pop_back();
235     EmitGlobalVariable(GV);
236   }
237 }
238
239 /// getPointerToFunction - This method is used to get the address of the
240 /// specified function, compiling it if neccesary.
241 ///
242 void *JIT::getPointerToFunction(Function *F) {
243   MutexGuard locked(lock);
244
245   if (void *Addr = getPointerToGlobalIfAvailable(F))
246     return Addr;   // Check if function already code gen'd
247
248   // Make sure we read in the function if it exists in this Module
249   if (F->hasNotBeenReadFromBytecode())
250     try {
251       MP->materializeFunction(F);
252     } catch ( std::string& errmsg ) {
253       std::cerr << "Error reading function '" << F->getName()
254                 << "' from bytecode file: " << errmsg << "\n";
255       abort();
256     } catch (...) {
257       std::cerr << "Error reading function '" << F->getName()
258                 << "from bytecode file!\n";
259       abort();
260     }
261
262   if (F->isExternal()) {
263     void *Addr = getPointerToNamedFunction(F->getName());
264     addGlobalMapping(F, Addr);
265     return Addr;
266   }
267
268   runJITOnFunction(F);
269
270   void *Addr = getPointerToGlobalIfAvailable(F);
271   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
272   return Addr;
273 }
274
275 /// getOrEmitGlobalVariable - Return the address of the specified global
276 /// variable, possibly emitting it to memory if needed.  This is used by the
277 /// Emitter.
278 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
279   MutexGuard locked(lock);
280
281   void *Ptr = getPointerToGlobalIfAvailable(GV);
282   if (Ptr) return Ptr;
283
284   // If the global is external, just remember the address.
285   if (GV->isExternal()) {
286     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
287     if (Ptr == 0) {
288       std::cerr << "Could not resolve external global address: "
289                 << GV->getName() << "\n";
290       abort();
291     }
292   } else {
293     // If the global hasn't been emitted to memory yet, allocate space.  We will
294     // actually initialize the global after current function has finished
295     // compilation.
296     uint64_t S = getTargetData().getTypeSize(GV->getType()->getElementType());
297     Ptr = new char[(size_t)S];
298     state.getPendingGlobals(locked).push_back(GV);
299   }
300   addGlobalMapping(GV, Ptr);
301   return Ptr;
302 }
303
304
305 /// recompileAndRelinkFunction - This method is used to force a function
306 /// which has already been compiled, to be compiled again, possibly
307 /// after it has been modified. Then the entry to the old copy is overwritten
308 /// with a branch to the new copy. If there was no old copy, this acts
309 /// just like JIT::getPointerToFunction().
310 ///
311 void *JIT::recompileAndRelinkFunction(Function *F) {
312   void *OldAddr = getPointerToGlobalIfAvailable(F);
313
314   // If it's not already compiled there is no reason to patch it up.
315   if (OldAddr == 0) { return getPointerToFunction(F); }
316
317   // Delete the old function mapping.
318   addGlobalMapping(F, 0);
319
320   // Recodegen the function
321   runJITOnFunction(F);
322
323   // Update state, forward the old function to the new function.
324   void *Addr = getPointerToGlobalIfAvailable(F);
325   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
326   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
327   return Addr;
328 }
329
330 /// freeMachineCodeForFunction - release machine code memory for given Function
331 ///
332 void JIT::freeMachineCodeForFunction(Function *F) {
333   // currently a no-op
334 }