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