4b888ef018ce42c121557d1d1985d8b00eeb3d22
[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 is distributed under the University of Illinois Open Source
6 // 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 bitcode 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/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetJITInfo.h"
30
31 #include "llvm/Config/config.h"
32
33 using namespace llvm;
34
35 #ifdef __APPLE__ 
36 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
37 // of atexit). It passes the address of linker generated symbol __dso_handle
38 // to the function.
39 // This configuration change happened at version 5330.
40 # include <AvailabilityMacros.h>
41 # if defined(MAC_OS_X_VERSION_10_4) && \
42      ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
43       (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
44        __APPLE_CC__ >= 5330))
45 #  ifndef HAVE___DSO_HANDLE
46 #   define HAVE___DSO_HANDLE 1
47 #  endif
48 # endif
49 #endif
50
51 #if HAVE___DSO_HANDLE
52 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
53 #endif
54
55 namespace {
56
57 static struct RegisterJIT {
58   RegisterJIT() { JIT::Register(); }
59 } JITRegistrator;
60
61 }
62
63 namespace llvm {
64   void LinkInJIT() {
65   }
66 }
67
68 #if defined (__GNUC__)
69 extern "C" void __register_frame(void*);
70 #endif
71
72 /// createJIT - This is the factory method for creating a JIT for the current
73 /// machine, it does not fall back to the interpreter.  This takes ownership
74 /// of the module provider.
75 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
76                                             std::string *ErrorStr,
77                                             JITMemoryManager *JMM) {
78   ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
79   if (!EE) return 0;
80   
81   // Register routine for informing unwinding runtime about new EH frames
82 #if defined(__GNUC__)
83   EE->InstallExceptionTableRegister(__register_frame);
84 #endif
85
86   // Make sure we can resolve symbols in the program as well. The zero arg
87   // to the function tells DynamicLibrary to load the program, not a library.
88   sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
89   return EE;
90 }
91
92 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
93          JITMemoryManager *JMM)
94   : ExecutionEngine(MP), TM(tm), TJI(tji), jitstate(MP) {
95   setTargetData(TM.getTargetData());
96
97   // Initialize MCE
98   MCE = createEmitter(*this, JMM);
99
100   // Add target data
101   MutexGuard locked(lock);
102   FunctionPassManager &PM = jitstate.getPM(locked);
103   PM.add(new TargetData(*TM.getTargetData()));
104
105   // Turn the machine code intermediate representation into bytes in memory that
106   // may be executed.
107   if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
108     cerr << "Target does not support machine code emission!\n";
109     abort();
110   }
111   
112   // Initialize passes.
113   PM.doInitialization();
114 }
115
116 JIT::~JIT() {
117   delete MCE;
118   delete &TM;
119 }
120
121 /// run - Start execution with the specified function and arguments.
122 ///
123 GenericValue JIT::runFunction(Function *F,
124                               const std::vector<GenericValue> &ArgValues) {
125   assert(F && "Function *F was null at entry to run()");
126
127   void *FPtr = getPointerToFunction(F);
128   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
129   const FunctionType *FTy = F->getFunctionType();
130   const Type *RetTy = FTy->getReturnType();
131
132   assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
133          "Too many arguments passed into function!");
134   assert(FTy->getNumParams() == ArgValues.size() &&
135          "This doesn't support passing arguments through varargs (yet)!");
136
137   // Handle some common cases first.  These cases correspond to common `main'
138   // prototypes.
139   if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
140     switch (ArgValues.size()) {
141     case 3:
142       if (FTy->getParamType(0) == Type::Int32Ty &&
143           isa<PointerType>(FTy->getParamType(1)) &&
144           isa<PointerType>(FTy->getParamType(2))) {
145         int (*PF)(int, char **, const char **) =
146           (int(*)(int, char **, const char **))(intptr_t)FPtr;
147
148         // Call the function.
149         GenericValue rv;
150         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), 
151                                  (char **)GVTOP(ArgValues[1]),
152                                  (const char **)GVTOP(ArgValues[2])));
153         return rv;
154       }
155       break;
156     case 2:
157       if (FTy->getParamType(0) == Type::Int32Ty &&
158           isa<PointerType>(FTy->getParamType(1))) {
159         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
160
161         // Call the function.
162         GenericValue rv;
163         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), 
164                                  (char **)GVTOP(ArgValues[1])));
165         return rv;
166       }
167       break;
168     case 1:
169       if (FTy->getNumParams() == 1 &&
170           FTy->getParamType(0) == Type::Int32Ty) {
171         GenericValue rv;
172         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
173         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
174         return rv;
175       }
176       break;
177     }
178   }
179
180   // Handle cases where no arguments are passed first.
181   if (ArgValues.empty()) {
182     GenericValue rv;
183     switch (RetTy->getTypeID()) {
184     default: assert(0 && "Unknown return type for function call!");
185     case Type::IntegerTyID: {
186       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
187       if (BitWidth == 1)
188         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
189       else if (BitWidth <= 8)
190         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
191       else if (BitWidth <= 16)
192         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
193       else if (BitWidth <= 32)
194         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
195       else if (BitWidth <= 64)
196         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
197       else 
198         assert(0 && "Integer types > 64 bits not supported");
199       return rv;
200     }
201     case Type::VoidTyID:
202       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
203       return rv;
204     case Type::FloatTyID:
205       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
206       return rv;
207     case Type::DoubleTyID:
208       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
209       return rv;
210     case Type::X86_FP80TyID:
211     case Type::FP128TyID:
212     case Type::PPC_FP128TyID:
213       assert(0 && "long double not supported yet");
214       return rv;
215     case Type::PointerTyID:
216       return PTOGV(((void*(*)())(intptr_t)FPtr)());
217     }
218   }
219
220   // Okay, this is not one of our quick and easy cases.  Because we don't have a
221   // full FFI, we have to codegen a nullary stub function that just calls the
222   // function we are interested in, passing in constants for all of the
223   // arguments.  Make this function and return.
224
225   // First, create the function.
226   FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
227   Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
228                                     F->getParent());
229
230   // Insert a basic block.
231   BasicBlock *StubBB = BasicBlock::Create("", Stub);
232
233   // Convert all of the GenericValue arguments over to constants.  Note that we
234   // currently don't support varargs.
235   SmallVector<Value*, 8> Args;
236   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
237     Constant *C = 0;
238     const Type *ArgTy = FTy->getParamType(i);
239     const GenericValue &AV = ArgValues[i];
240     switch (ArgTy->getTypeID()) {
241     default: assert(0 && "Unknown argument type for function call!");
242     case Type::IntegerTyID:
243         C = ConstantInt::get(AV.IntVal);
244         break;
245     case Type::FloatTyID:
246         C = ConstantFP::get(APFloat(AV.FloatVal));
247         break;
248     case Type::DoubleTyID:
249         C = ConstantFP::get(APFloat(AV.DoubleVal));
250         break;
251     case Type::PPC_FP128TyID:
252     case Type::X86_FP80TyID:
253     case Type::FP128TyID:
254         C = ConstantFP::get(APFloat(AV.IntVal));
255         break;
256     case Type::PointerTyID:
257       void *ArgPtr = GVTOP(AV);
258       if (sizeof(void*) == 4)
259         C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
260       else
261         C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
262       C = ConstantExpr::getIntToPtr(C, ArgTy);  // Cast the integer to pointer
263       break;
264     }
265     Args.push_back(C);
266   }
267
268   CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
269                                        "", StubBB);
270   TheCall->setTailCall();
271   if (TheCall->getType() != Type::VoidTy)
272     ReturnInst::Create(TheCall, StubBB);    // Return result of the call.
273   else
274     ReturnInst::Create(StubBB);             // Just return void.
275
276   // Finally, return the value returned by our nullary stub function.
277   return runFunction(Stub, std::vector<GenericValue>());
278 }
279
280 /// runJITOnFunction - Run the FunctionPassManager full of
281 /// just-in-time compilation passes on F, hopefully filling in
282 /// GlobalAddress[F] with the address of F's machine code.
283 ///
284 void JIT::runJITOnFunction(Function *F) {
285   static bool isAlreadyCodeGenerating = false;
286
287   MutexGuard locked(lock);
288   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
289
290   // JIT the function
291   isAlreadyCodeGenerating = true;
292   jitstate.getPM(locked).run(*F);
293   isAlreadyCodeGenerating = false;
294
295   // If the function referred to a global variable that had not yet been
296   // emitted, it allocates memory for the global, but doesn't emit it yet.  Emit
297   // all of these globals now.
298   while (!jitstate.getPendingGlobals(locked).empty()) {
299     const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
300     jitstate.getPendingGlobals(locked).pop_back();
301     EmitGlobalVariable(GV);
302   }
303 }
304
305 /// getPointerToFunction - This method is used to get the address of the
306 /// specified function, compiling it if neccesary.
307 ///
308 void *JIT::getPointerToFunction(Function *F) {
309
310   if (void *Addr = getPointerToGlobalIfAvailable(F))
311     return Addr;   // Check if function already code gen'd
312
313   // Make sure we read in the function if it exists in this Module.
314   if (F->hasNotBeenReadFromBitcode()) {
315     // Determine the module provider this function is provided by.
316     Module *M = F->getParent();
317     ModuleProvider *MP = 0;
318     for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
319       if (Modules[i]->getModule() == M) {
320         MP = Modules[i];
321         break;
322       }
323     }
324     assert(MP && "Function isn't in a module we know about!");
325     
326     std::string ErrorMsg;
327     if (MP->materializeFunction(F, &ErrorMsg)) {
328       cerr << "Error reading function '" << F->getName()
329            << "' from bitcode file: " << ErrorMsg << "\n";
330       abort();
331     }
332   }
333   
334   if (void *Addr = getPointerToGlobalIfAvailable(F)) {
335     return Addr;
336   }
337
338   MutexGuard locked(lock);
339   
340   if (F->isDeclaration()) {
341     void *Addr = getPointerToNamedFunction(F->getName());
342     addGlobalMapping(F, Addr);
343     return Addr;
344   }
345
346   runJITOnFunction(F);
347
348   void *Addr = getPointerToGlobalIfAvailable(F);
349   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
350   return Addr;
351 }
352
353 /// getOrEmitGlobalVariable - Return the address of the specified global
354 /// variable, possibly emitting it to memory if needed.  This is used by the
355 /// Emitter.
356 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
357   MutexGuard locked(lock);
358
359   void *Ptr = getPointerToGlobalIfAvailable(GV);
360   if (Ptr) return Ptr;
361
362   // If the global is external, just remember the address.
363   if (GV->isDeclaration()) {
364 #if HAVE___DSO_HANDLE
365     if (GV->getName() == "__dso_handle")
366       return (void*)&__dso_handle;
367 #endif
368     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
369     if (Ptr == 0) {
370       cerr << "Could not resolve external global address: "
371            << GV->getName() << "\n";
372       abort();
373     }
374   } else {
375     // If the global hasn't been emitted to memory yet, allocate space.  We will
376     // actually initialize the global after current function has finished
377     // compilation.
378     const Type *GlobalType = GV->getType()->getElementType();
379     size_t S = getTargetData()->getABITypeSize(GlobalType);
380     size_t A = getTargetData()->getPreferredAlignment(GV);
381     if (A <= 8) {
382       Ptr = malloc(S);
383     } else {
384       // Allocate S+A bytes of memory, then use an aligned pointer within that
385       // space.
386       Ptr = malloc(S+A);
387       unsigned MisAligned = ((intptr_t)Ptr & (A-1));
388       Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
389     }
390     jitstate.getPendingGlobals(locked).push_back(GV);
391   }
392   addGlobalMapping(GV, Ptr);
393   return Ptr;
394 }
395
396
397 /// recompileAndRelinkFunction - This method is used to force a function
398 /// which has already been compiled, to be compiled again, possibly
399 /// after it has been modified. Then the entry to the old copy is overwritten
400 /// with a branch to the new copy. If there was no old copy, this acts
401 /// just like JIT::getPointerToFunction().
402 ///
403 void *JIT::recompileAndRelinkFunction(Function *F) {
404   void *OldAddr = getPointerToGlobalIfAvailable(F);
405
406   // If it's not already compiled there is no reason to patch it up.
407   if (OldAddr == 0) { return getPointerToFunction(F); }
408
409   // Delete the old function mapping.
410   addGlobalMapping(F, 0);
411
412   // Recodegen the function
413   runJITOnFunction(F);
414
415   // Update state, forward the old function to the new function.
416   void *Addr = getPointerToGlobalIfAvailable(F);
417   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
418   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
419   return Addr;
420 }
421