Use DataLayout from the module when easily available.
[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/ADT/SmallPtrSet.h"
17 #include "llvm/CodeGen/JITCodeEmitter.h"
18 #include "llvm/CodeGen/MachineCodeInfo.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/ExecutionEngine/GenericValue.h"
21 #include "llvm/ExecutionEngine/JITEventListener.h"
22 #include "llvm/ExecutionEngine/JITMemoryManager.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/DynamicLibrary.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/Target/TargetJITInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37
38 using namespace llvm;
39
40 #ifdef __APPLE__
41 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
42 // of atexit). It passes the address of linker generated symbol __dso_handle
43 // to the function.
44 // This configuration change happened at version 5330.
45 # include <AvailabilityMacros.h>
46 # if defined(MAC_OS_X_VERSION_10_4) && \
47      ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
48       (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
49        __APPLE_CC__ >= 5330))
50 #  ifndef HAVE___DSO_HANDLE
51 #   define HAVE___DSO_HANDLE 1
52 #  endif
53 # endif
54 #endif
55
56 #if HAVE___DSO_HANDLE
57 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
58 #endif
59
60 namespace {
61
62 static struct RegisterJIT {
63   RegisterJIT() { JIT::Register(); }
64 } JITRegistrator;
65
66 }
67
68 extern "C" void LLVMLinkInJIT() {
69 }
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.
74 ExecutionEngine *JIT::createJIT(Module *M,
75                                 std::string *ErrorStr,
76                                 JITMemoryManager *JMM,
77                                 bool GVsWithCode,
78                                 TargetMachine *TM) {
79   // Try to register the program as a source of symbols to resolve against.
80   //
81   // FIXME: Don't do this here.
82   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
83
84   // If the target supports JIT code generation, create the JIT.
85   if (TargetJITInfo *TJ = TM->getJITInfo()) {
86     return new JIT(M, *TM, *TJ, JMM, GVsWithCode);
87   } else {
88     if (ErrorStr)
89       *ErrorStr = "target does not support JIT code generation";
90     return 0;
91   }
92 }
93
94 namespace {
95 /// This class supports the global getPointerToNamedFunction(), which allows
96 /// bugpoint or gdb users to search for a function by name without any context.
97 class JitPool {
98   SmallPtrSet<JIT*, 1> JITs;  // Optimize for process containing just 1 JIT.
99   mutable sys::Mutex Lock;
100 public:
101   void Add(JIT *jit) {
102     MutexGuard guard(Lock);
103     JITs.insert(jit);
104   }
105   void Remove(JIT *jit) {
106     MutexGuard guard(Lock);
107     JITs.erase(jit);
108   }
109   void *getPointerToNamedFunction(const char *Name) const {
110     MutexGuard guard(Lock);
111     assert(JITs.size() != 0 && "No Jit registered");
112     //search function in every instance of JIT
113     for (SmallPtrSet<JIT*, 1>::const_iterator Jit = JITs.begin(),
114            end = JITs.end();
115          Jit != end; ++Jit) {
116       if (Function *F = (*Jit)->FindFunctionNamed(Name))
117         return (*Jit)->getPointerToFunction(F);
118     }
119     // The function is not available : fallback on the first created (will
120     // search in symbol of the current program/library)
121     return (*JITs.begin())->getPointerToNamedFunction(Name);
122   }
123 };
124 ManagedStatic<JitPool> AllJits;
125 }
126 extern "C" {
127   // getPointerToNamedFunction - This function is used as a global wrapper to
128   // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
129   // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
130   // need to resolve function(s) that are being mis-codegenerated, so we need to
131   // resolve their addresses at runtime, and this is the way to do it.
132   void *getPointerToNamedFunction(const char *Name) {
133     return AllJits->getPointerToNamedFunction(Name);
134   }
135 }
136
137 JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
138          JITMemoryManager *jmm, bool GVsWithCode)
139   : ExecutionEngine(M), TM(tm), TJI(tji),
140     JMM(jmm ? jmm : JITMemoryManager::CreateDefaultMemManager()),
141     AllocateGVsWithCode(GVsWithCode), isAlreadyCodeGenerating(false) {
142   setDataLayout(TM.getDataLayout());
143
144   jitstate = new JITState(M);
145
146   // Initialize JCE
147   JCE = createEmitter(*this, JMM, TM);
148
149   // Register in global list of all JITs.
150   AllJits->Add(this);
151
152   // Add target data
153   MutexGuard locked(lock);
154   FunctionPassManager &PM = jitstate->getPM(locked);
155   M->setDataLayout(TM.getDataLayout());
156   PM.add(new DataLayoutPass(M));
157
158   // Turn the machine code intermediate representation into bytes in memory that
159   // may be executed.
160   if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
161     report_fatal_error("Target does not support machine code emission!");
162   }
163
164   // Initialize passes.
165   PM.doInitialization();
166 }
167
168 JIT::~JIT() {
169   // Cleanup.
170   AllJits->Remove(this);
171   delete jitstate;
172   delete JCE;
173   // JMM is a ownership of JCE, so we no need delete JMM here.
174   delete &TM;
175 }
176
177 /// addModule - Add a new Module to the JIT.  If we previously removed the last
178 /// Module, we need re-initialize jitstate with a valid Module.
179 void JIT::addModule(Module *M) {
180   MutexGuard locked(lock);
181
182   if (Modules.empty()) {
183     assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
184
185     jitstate = new JITState(M);
186
187     FunctionPassManager &PM = jitstate->getPM(locked);
188     M->setDataLayout(TM.getDataLayout());
189     PM.add(new DataLayoutPass(M));
190
191     // Turn the machine code intermediate representation into bytes in memory
192     // that may be executed.
193     if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
194       report_fatal_error("Target does not support machine code emission!");
195     }
196
197     // Initialize passes.
198     PM.doInitialization();
199   }
200
201   ExecutionEngine::addModule(M);
202 }
203
204 /// removeModule - If we are removing the last Module, invalidate the jitstate
205 /// since the PassManager it contains references a released Module.
206 bool JIT::removeModule(Module *M) {
207   bool result = ExecutionEngine::removeModule(M);
208
209   MutexGuard locked(lock);
210
211   if (jitstate && jitstate->getModule() == M) {
212     delete jitstate;
213     jitstate = 0;
214   }
215
216   if (!jitstate && !Modules.empty()) {
217     jitstate = new JITState(Modules[0]);
218
219     FunctionPassManager &PM = jitstate->getPM(locked);
220     M->setDataLayout(TM.getDataLayout());
221     PM.add(new DataLayoutPass(M));
222
223     // Turn the machine code intermediate representation into bytes in memory
224     // that may be executed.
225     if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
226       report_fatal_error("Target does not support machine code emission!");
227     }
228
229     // Initialize passes.
230     PM.doInitialization();
231   }
232   return result;
233 }
234
235 /// run - Start execution with the specified function and arguments.
236 ///
237 GenericValue JIT::runFunction(Function *F,
238                               const std::vector<GenericValue> &ArgValues) {
239   assert(F && "Function *F was null at entry to run()");
240
241   void *FPtr = getPointerToFunction(F);
242   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
243   FunctionType *FTy = F->getFunctionType();
244   Type *RetTy = FTy->getReturnType();
245
246   assert((FTy->getNumParams() == ArgValues.size() ||
247           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
248          "Wrong number of arguments passed into function!");
249   assert(FTy->getNumParams() == ArgValues.size() &&
250          "This doesn't support passing arguments through varargs (yet)!");
251
252   // Handle some common cases first.  These cases correspond to common `main'
253   // prototypes.
254   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
255     switch (ArgValues.size()) {
256     case 3:
257       if (FTy->getParamType(0)->isIntegerTy(32) &&
258           FTy->getParamType(1)->isPointerTy() &&
259           FTy->getParamType(2)->isPointerTy()) {
260         int (*PF)(int, char **, const char **) =
261           (int(*)(int, char **, const char **))(intptr_t)FPtr;
262
263         // Call the function.
264         GenericValue rv;
265         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
266                                  (char **)GVTOP(ArgValues[1]),
267                                  (const char **)GVTOP(ArgValues[2])));
268         return rv;
269       }
270       break;
271     case 2:
272       if (FTy->getParamType(0)->isIntegerTy(32) &&
273           FTy->getParamType(1)->isPointerTy()) {
274         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
275
276         // Call the function.
277         GenericValue rv;
278         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
279                                  (char **)GVTOP(ArgValues[1])));
280         return rv;
281       }
282       break;
283     case 1:
284       if (FTy->getParamType(0)->isIntegerTy(32)) {
285         GenericValue rv;
286         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
287         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
288         return rv;
289       }
290       if (FTy->getParamType(0)->isPointerTy()) {
291         GenericValue rv;
292         int (*PF)(char *) = (int(*)(char *))(intptr_t)FPtr;
293         rv.IntVal = APInt(32, PF((char*)GVTOP(ArgValues[0])));
294         return rv;
295       }
296       break;
297     }
298   }
299
300   // Handle cases where no arguments are passed first.
301   if (ArgValues.empty()) {
302     GenericValue rv;
303     switch (RetTy->getTypeID()) {
304     default: llvm_unreachable("Unknown return type for function call!");
305     case Type::IntegerTyID: {
306       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
307       if (BitWidth == 1)
308         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
309       else if (BitWidth <= 8)
310         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
311       else if (BitWidth <= 16)
312         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
313       else if (BitWidth <= 32)
314         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
315       else if (BitWidth <= 64)
316         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
317       else
318         llvm_unreachable("Integer types > 64 bits not supported");
319       return rv;
320     }
321     case Type::VoidTyID:
322       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
323       return rv;
324     case Type::FloatTyID:
325       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
326       return rv;
327     case Type::DoubleTyID:
328       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
329       return rv;
330     case Type::X86_FP80TyID:
331     case Type::FP128TyID:
332     case Type::PPC_FP128TyID:
333       llvm_unreachable("long double not supported yet");
334     case Type::PointerTyID:
335       return PTOGV(((void*(*)())(intptr_t)FPtr)());
336     }
337   }
338
339   // Okay, this is not one of our quick and easy cases.  Because we don't have a
340   // full FFI, we have to codegen a nullary stub function that just calls the
341   // function we are interested in, passing in constants for all of the
342   // arguments.  Make this function and return.
343
344   // First, create the function.
345   FunctionType *STy=FunctionType::get(RetTy, false);
346   Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
347                                     F->getParent());
348
349   // Insert a basic block.
350   BasicBlock *StubBB = BasicBlock::Create(F->getContext(), "", Stub);
351
352   // Convert all of the GenericValue arguments over to constants.  Note that we
353   // currently don't support varargs.
354   SmallVector<Value*, 8> Args;
355   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
356     Constant *C = 0;
357     Type *ArgTy = FTy->getParamType(i);
358     const GenericValue &AV = ArgValues[i];
359     switch (ArgTy->getTypeID()) {
360     default: llvm_unreachable("Unknown argument type for function call!");
361     case Type::IntegerTyID:
362         C = ConstantInt::get(F->getContext(), AV.IntVal);
363         break;
364     case Type::FloatTyID:
365         C = ConstantFP::get(F->getContext(), APFloat(AV.FloatVal));
366         break;
367     case Type::DoubleTyID:
368         C = ConstantFP::get(F->getContext(), APFloat(AV.DoubleVal));
369         break;
370     case Type::PPC_FP128TyID:
371     case Type::X86_FP80TyID:
372     case Type::FP128TyID:
373         C = ConstantFP::get(F->getContext(), APFloat(ArgTy->getFltSemantics(),
374                                                      AV.IntVal));
375         break;
376     case Type::PointerTyID:
377       void *ArgPtr = GVTOP(AV);
378       if (sizeof(void*) == 4)
379         C = ConstantInt::get(Type::getInt32Ty(F->getContext()),
380                              (int)(intptr_t)ArgPtr);
381       else
382         C = ConstantInt::get(Type::getInt64Ty(F->getContext()),
383                              (intptr_t)ArgPtr);
384       // Cast the integer to pointer
385       C = ConstantExpr::getIntToPtr(C, ArgTy);
386       break;
387     }
388     Args.push_back(C);
389   }
390
391   CallInst *TheCall = CallInst::Create(F, Args, "", StubBB);
392   TheCall->setCallingConv(F->getCallingConv());
393   TheCall->setTailCall();
394   if (!TheCall->getType()->isVoidTy())
395     // Return result of the call.
396     ReturnInst::Create(F->getContext(), TheCall, StubBB);
397   else
398     ReturnInst::Create(F->getContext(), StubBB);           // Just return void.
399
400   // Finally, call our nullary stub function.
401   GenericValue Result = runFunction(Stub, std::vector<GenericValue>());
402   // Erase it, since no other function can have a reference to it.
403   Stub->eraseFromParent();
404   // And return the result.
405   return Result;
406 }
407
408 void JIT::RegisterJITEventListener(JITEventListener *L) {
409   if (L == NULL)
410     return;
411   MutexGuard locked(lock);
412   EventListeners.push_back(L);
413 }
414 void JIT::UnregisterJITEventListener(JITEventListener *L) {
415   if (L == NULL)
416     return;
417   MutexGuard locked(lock);
418   std::vector<JITEventListener*>::reverse_iterator I=
419       std::find(EventListeners.rbegin(), EventListeners.rend(), L);
420   if (I != EventListeners.rend()) {
421     std::swap(*I, EventListeners.back());
422     EventListeners.pop_back();
423   }
424 }
425 void JIT::NotifyFunctionEmitted(
426     const Function &F,
427     void *Code, size_t Size,
428     const JITEvent_EmittedFunctionDetails &Details) {
429   MutexGuard locked(lock);
430   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
431     EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
432   }
433 }
434
435 void JIT::NotifyFreeingMachineCode(void *OldPtr) {
436   MutexGuard locked(lock);
437   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
438     EventListeners[I]->NotifyFreeingMachineCode(OldPtr);
439   }
440 }
441
442 /// runJITOnFunction - Run the FunctionPassManager full of
443 /// just-in-time compilation passes on F, hopefully filling in
444 /// GlobalAddress[F] with the address of F's machine code.
445 ///
446 void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
447   MutexGuard locked(lock);
448
449   class MCIListener : public JITEventListener {
450     MachineCodeInfo *const MCI;
451    public:
452     MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
453     virtual void NotifyFunctionEmitted(const Function &,
454                                        void *Code, size_t Size,
455                                        const EmittedFunctionDetails &) {
456       MCI->setAddress(Code);
457       MCI->setSize(Size);
458     }
459   };
460   MCIListener MCIL(MCI);
461   if (MCI)
462     RegisterJITEventListener(&MCIL);
463
464   runJITOnFunctionUnlocked(F, locked);
465
466   if (MCI)
467     UnregisterJITEventListener(&MCIL);
468 }
469
470 void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
471   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
472
473   jitTheFunction(F, locked);
474
475   // If the function referred to another function that had not yet been
476   // read from bitcode, and we are jitting non-lazily, emit it now.
477   while (!jitstate->getPendingFunctions(locked).empty()) {
478     Function *PF = jitstate->getPendingFunctions(locked).back();
479     jitstate->getPendingFunctions(locked).pop_back();
480
481     assert(!PF->hasAvailableExternallyLinkage() &&
482            "Externally-defined function should not be in pending list.");
483
484     jitTheFunction(PF, locked);
485
486     // Now that the function has been jitted, ask the JITEmitter to rewrite
487     // the stub with real address of the function.
488     updateFunctionStub(PF);
489   }
490 }
491
492 void JIT::jitTheFunction(Function *F, const MutexGuard &locked) {
493   isAlreadyCodeGenerating = true;
494   jitstate->getPM(locked).run(*F);
495   isAlreadyCodeGenerating = false;
496
497   // clear basic block addresses after this function is done
498   getBasicBlockAddressMap(locked).clear();
499 }
500
501 /// getPointerToFunction - This method is used to get the address of the
502 /// specified function, compiling it if necessary.
503 ///
504 void *JIT::getPointerToFunction(Function *F) {
505
506   if (void *Addr = getPointerToGlobalIfAvailable(F))
507     return Addr;   // Check if function already code gen'd
508
509   MutexGuard locked(lock);
510
511   // Now that this thread owns the lock, make sure we read in the function if it
512   // exists in this Module.
513   std::string ErrorMsg;
514   if (F->Materialize(&ErrorMsg)) {
515     report_fatal_error("Error reading function '" + F->getName()+
516                       "' from bitcode file: " + ErrorMsg);
517   }
518
519   // ... and check if another thread has already code gen'd the function.
520   if (void *Addr = getPointerToGlobalIfAvailable(F))
521     return Addr;
522
523   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
524     bool AbortOnFailure = !F->hasExternalWeakLinkage();
525     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
526     addGlobalMapping(F, Addr);
527     return Addr;
528   }
529
530   runJITOnFunctionUnlocked(F, locked);
531
532   void *Addr = getPointerToGlobalIfAvailable(F);
533   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
534   return Addr;
535 }
536
537 void JIT::addPointerToBasicBlock(const BasicBlock *BB, void *Addr) {
538   MutexGuard locked(lock);
539
540   BasicBlockAddressMapTy::iterator I =
541     getBasicBlockAddressMap(locked).find(BB);
542   if (I == getBasicBlockAddressMap(locked).end()) {
543     getBasicBlockAddressMap(locked)[BB] = Addr;
544   } else {
545     // ignore repeats: some BBs can be split into few MBBs?
546   }
547 }
548
549 void JIT::clearPointerToBasicBlock(const BasicBlock *BB) {
550   MutexGuard locked(lock);
551   getBasicBlockAddressMap(locked).erase(BB);
552 }
553
554 void *JIT::getPointerToBasicBlock(BasicBlock *BB) {
555   // make sure it's function is compiled by JIT
556   (void)getPointerToFunction(BB->getParent());
557
558   // resolve basic block address
559   MutexGuard locked(lock);
560
561   BasicBlockAddressMapTy::iterator I =
562     getBasicBlockAddressMap(locked).find(BB);
563   if (I != getBasicBlockAddressMap(locked).end()) {
564     return I->second;
565   } else {
566     llvm_unreachable("JIT does not have BB address for address-of-label, was"
567                      " it eliminated by optimizer?");
568   }
569 }
570
571 void *JIT::getPointerToNamedFunction(const std::string &Name,
572                                      bool AbortOnFailure){
573   if (!isSymbolSearchingDisabled()) {
574     void *ptr = JMM->getPointerToNamedFunction(Name, false);
575     if (ptr)
576       return ptr;
577   }
578
579   /// If a LazyFunctionCreator is installed, use it to get/create the function.
580   if (LazyFunctionCreator)
581     if (void *RP = LazyFunctionCreator(Name))
582       return RP;
583
584   if (AbortOnFailure) {
585     report_fatal_error("Program used external function '"+Name+
586                       "' which could not be resolved!");
587   }
588   return 0;
589 }
590
591
592 /// getOrEmitGlobalVariable - Return the address of the specified global
593 /// variable, possibly emitting it to memory if needed.  This is used by the
594 /// Emitter.
595 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
596   MutexGuard locked(lock);
597
598   void *Ptr = getPointerToGlobalIfAvailable(GV);
599   if (Ptr) return Ptr;
600
601   // If the global is external, just remember the address.
602   if (GV->isDeclaration() || GV->hasAvailableExternallyLinkage()) {
603 #if HAVE___DSO_HANDLE
604     if (GV->getName() == "__dso_handle")
605       return (void*)&__dso_handle;
606 #endif
607     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName());
608     if (Ptr == 0) {
609       report_fatal_error("Could not resolve external global address: "
610                         +GV->getName());
611     }
612     addGlobalMapping(GV, Ptr);
613   } else {
614     // If the global hasn't been emitted to memory yet, allocate space and
615     // emit it into memory.
616     Ptr = getMemoryForGV(GV);
617     addGlobalMapping(GV, Ptr);
618     EmitGlobalVariable(GV);  // Initialize the variable.
619   }
620   return Ptr;
621 }
622
623 /// recompileAndRelinkFunction - This method is used to force a function
624 /// which has already been compiled, to be compiled again, possibly
625 /// after it has been modified. Then the entry to the old copy is overwritten
626 /// with a branch to the new copy. If there was no old copy, this acts
627 /// just like JIT::getPointerToFunction().
628 ///
629 void *JIT::recompileAndRelinkFunction(Function *F) {
630   void *OldAddr = getPointerToGlobalIfAvailable(F);
631
632   // If it's not already compiled there is no reason to patch it up.
633   if (OldAddr == 0) { return getPointerToFunction(F); }
634
635   // Delete the old function mapping.
636   addGlobalMapping(F, 0);
637
638   // Recodegen the function
639   runJITOnFunction(F);
640
641   // Update state, forward the old function to the new function.
642   void *Addr = getPointerToGlobalIfAvailable(F);
643   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
644   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
645   return Addr;
646 }
647
648 /// getMemoryForGV - This method abstracts memory allocation of global
649 /// variable so that the JIT can allocate thread local variables depending
650 /// on the target.
651 ///
652 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
653   char *Ptr;
654
655   // GlobalVariable's which are not "constant" will cause trouble in a server
656   // situation. It's returned in the same block of memory as code which may
657   // not be writable.
658   if (isGVCompilationDisabled() && !GV->isConstant()) {
659     report_fatal_error("Compilation of non-internal GlobalValue is disabled!");
660   }
661
662   // Some applications require globals and code to live together, so they may
663   // be allocated into the same buffer, but in general globals are allocated
664   // through the memory manager which puts them near the code but not in the
665   // same buffer.
666   Type *GlobalType = GV->getType()->getElementType();
667   size_t S = getDataLayout()->getTypeAllocSize(GlobalType);
668   size_t A = getDataLayout()->getPreferredAlignment(GV);
669   if (GV->isThreadLocal()) {
670     MutexGuard locked(lock);
671     Ptr = TJI.allocateThreadLocalMemory(S);
672   } else if (TJI.allocateSeparateGVMemory()) {
673     if (A <= 8) {
674       Ptr = (char*)malloc(S);
675     } else {
676       // Allocate S+A bytes of memory, then use an aligned pointer within that
677       // space.
678       Ptr = (char*)malloc(S+A);
679       unsigned MisAligned = ((intptr_t)Ptr & (A-1));
680       Ptr = Ptr + (MisAligned ? (A-MisAligned) : 0);
681     }
682   } else if (AllocateGVsWithCode) {
683     Ptr = (char*)JCE->allocateSpace(S, A);
684   } else {
685     Ptr = (char*)JCE->allocateGlobal(S, A);
686   }
687   return Ptr;
688 }
689
690 void JIT::addPendingFunction(Function *F) {
691   MutexGuard locked(lock);
692   jitstate->getPendingFunctions(locked).push_back(F);
693 }
694
695
696 JITEventListener::~JITEventListener() {}