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