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