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