Re-enabling MCJIT object caching with memory leak fixed
[oota-llvm.git] / lib / ExecutionEngine / MCJIT / MCJIT.cpp
1 //===-- MCJIT.cpp - MC-based 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 #include "MCJIT.h"
11 #include "llvm/ExecutionEngine/GenericValue.h"
12 #include "llvm/ExecutionEngine/JITEventListener.h"
13 #include "llvm/ExecutionEngine/JITMemoryManager.h"
14 #include "llvm/ExecutionEngine/MCJIT.h"
15 #include "llvm/ExecutionEngine/ObjectBuffer.h"
16 #include "llvm/ExecutionEngine/ObjectImage.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Support/DynamicLibrary.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/MutexGuard.h"
25
26 using namespace llvm;
27
28 namespace {
29
30 static struct RegisterJIT {
31   RegisterJIT() { MCJIT::Register(); }
32 } JITRegistrator;
33
34 }
35
36 extern "C" void LLVMLinkInMCJIT() {
37 }
38
39 ExecutionEngine *MCJIT::createJIT(Module *M,
40                                   std::string *ErrorStr,
41                                   JITMemoryManager *JMM,
42                                   bool GVsWithCode,
43                                   TargetMachine *TM) {
44   // Try to register the program as a source of symbols to resolve against.
45   //
46   // FIXME: Don't do this here.
47   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
48
49   return new MCJIT(M, TM, JMM, GVsWithCode);
50 }
51
52 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
53              bool AllocateGVsWithCode)
54   : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
55     IsLoaded(false), M(m), ObjCache(0)  {
56
57   setDataLayout(TM->getDataLayout());
58 }
59
60 MCJIT::~MCJIT() {
61   if (LoadedObject)
62     NotifyFreeingObject(*LoadedObject.get());
63   delete MemMgr;
64   delete TM;
65 }
66
67 void MCJIT::setObjectCache(ObjectCache* NewCache) {
68   ObjCache = NewCache;
69 }
70
71 ObjectBufferStream* MCJIT::emitObject(Module *m) {
72   /// Currently, MCJIT only supports a single module and the module passed to
73   /// this function call is expected to be the contained module.  The module
74   /// is passed as a parameter here to prepare for multiple module support in
75   /// the future.
76   assert(M == m);
77
78   // Get a thread lock to make sure we aren't trying to compile multiple times
79   MutexGuard locked(lock);
80
81   // FIXME: Track compilation state on a per-module basis when multiple modules
82   //        are supported.
83   // Re-compilation is not supported
84   assert(!IsLoaded);
85
86   PassManager PM;
87
88   PM.add(new DataLayout(*TM->getDataLayout()));
89
90   // The RuntimeDyld will take ownership of this shortly
91   OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
92
93   // Turn the machine code intermediate representation into bytes in memory
94   // that may be executed.
95   if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
96     report_fatal_error("Target does not support MC emission!");
97   }
98
99   // Initialize passes.
100   PM.run(*m);
101   // Flush the output buffer to get the generated code into memory
102   CompiledObject->flush();
103
104   // If we have an object cache, tell it about the new object.
105   // Note that we're using the compiled image, not the loaded image (as below).
106   if (ObjCache) {
107     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
108     // to create a temporary object here and delete it after the call.
109     OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
110     ObjCache->notifyObjectCompiled(m, MB.get());
111   }
112
113   return CompiledObject.take();
114 }
115
116 void MCJIT::loadObject(Module *M) {
117
118   // Get a thread lock to make sure we aren't trying to load multiple times
119   MutexGuard locked(lock);
120
121   // FIXME: Track compilation state on a per-module basis when multiple modules
122   //        are supported.
123   // Re-compilation is not supported
124   if (IsLoaded)
125     return;
126
127   OwningPtr<ObjectBuffer> ObjectToLoad;
128   // Try to load the pre-compiled object from cache if possible
129   if (0 != ObjCache) {
130     OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObjectCopy(M));
131     if (0 != PreCompiledObject.get())
132       ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
133   }
134
135   // If the cache did not contain a suitable object, compile the object
136   if (!ObjectToLoad) {
137     ObjectToLoad.reset(emitObject(M));
138     assert(ObjectToLoad.get() && "Compilation did not produce an object.");
139   }
140
141   // Load the object into the dynamic linker.
142   // handing off ownership of the buffer
143   LoadedObject.reset(Dyld.loadObject(ObjectToLoad.take()));
144   if (!LoadedObject)
145     report_fatal_error(Dyld.getErrorString());
146
147   // Resolve any relocations.
148   Dyld.resolveRelocations();
149
150   // FIXME: Make this optional, maybe even move it to a JIT event listener
151   LoadedObject->registerWithDebugger();
152
153   NotifyObjectEmitted(*LoadedObject);
154
155   // FIXME: Add support for per-module compilation state
156   IsLoaded = true;
157 }
158
159 // FIXME: Add a parameter to identify which object is being finalized when
160 // MCJIT supports multiple modules.
161 // FIXME: Provide a way to separate code emission, relocations and page 
162 // protection in the interface.
163 void MCJIT::finalizeObject() {
164   // If the module hasn't been compiled, just do that.
165   if (!IsLoaded) {
166     // If the call to Dyld.resolveRelocations() is removed from loadObject()
167     // we'll need to do that here.
168     loadObject(M);
169
170     // Set page permissions.
171     MemMgr->applyPermissions();
172
173     return;
174   }
175
176   // Resolve any relocations.
177   Dyld.resolveRelocations();
178
179   // Set page permissions.
180   MemMgr->applyPermissions();
181 }
182
183 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
184   report_fatal_error("not yet implemented");
185 }
186
187 void *MCJIT::getPointerToFunction(Function *F) {
188   // FIXME: This should really return a uint64_t since it's a pointer in the
189   // target address space, not our local address space. That's part of the
190   // ExecutionEngine interface, though. Fix that when the old JIT finally
191   // dies.
192
193   // FIXME: Add support for per-module compilation state
194   if (!IsLoaded)
195     loadObject(M);
196
197   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
198     bool AbortOnFailure = !F->hasExternalWeakLinkage();
199     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
200     addGlobalMapping(F, Addr);
201     return Addr;
202   }
203
204   // FIXME: Should the Dyld be retaining module information? Probably not.
205   // FIXME: Should we be using the mangler for this? Probably.
206   //
207   // This is the accessor for the target address, so make sure to check the
208   // load address of the symbol, not the local address.
209   StringRef BaseName = F->getName();
210   if (BaseName[0] == '\1')
211     return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
212   return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
213                                        + BaseName).str());
214 }
215
216 void *MCJIT::recompileAndRelinkFunction(Function *F) {
217   report_fatal_error("not yet implemented");
218 }
219
220 void MCJIT::freeMachineCodeForFunction(Function *F) {
221   report_fatal_error("not yet implemented");
222 }
223
224 GenericValue MCJIT::runFunction(Function *F,
225                                 const std::vector<GenericValue> &ArgValues) {
226   assert(F && "Function *F was null at entry to run()");
227
228   void *FPtr = getPointerToFunction(F);
229   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
230   FunctionType *FTy = F->getFunctionType();
231   Type *RetTy = FTy->getReturnType();
232
233   assert((FTy->getNumParams() == ArgValues.size() ||
234           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
235          "Wrong number of arguments passed into function!");
236   assert(FTy->getNumParams() == ArgValues.size() &&
237          "This doesn't support passing arguments through varargs (yet)!");
238
239   // Handle some common cases first.  These cases correspond to common `main'
240   // prototypes.
241   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
242     switch (ArgValues.size()) {
243     case 3:
244       if (FTy->getParamType(0)->isIntegerTy(32) &&
245           FTy->getParamType(1)->isPointerTy() &&
246           FTy->getParamType(2)->isPointerTy()) {
247         int (*PF)(int, char **, const char **) =
248           (int(*)(int, char **, const char **))(intptr_t)FPtr;
249
250         // Call the function.
251         GenericValue rv;
252         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
253                                  (char **)GVTOP(ArgValues[1]),
254                                  (const char **)GVTOP(ArgValues[2])));
255         return rv;
256       }
257       break;
258     case 2:
259       if (FTy->getParamType(0)->isIntegerTy(32) &&
260           FTy->getParamType(1)->isPointerTy()) {
261         int (*PF)(int, char **) = (int(*)(int, 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         return rv;
268       }
269       break;
270     case 1:
271       if (FTy->getNumParams() == 1 &&
272           FTy->getParamType(0)->isIntegerTy(32)) {
273         GenericValue rv;
274         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
275         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
276         return rv;
277       }
278       break;
279     }
280   }
281
282   // Handle cases where no arguments are passed first.
283   if (ArgValues.empty()) {
284     GenericValue rv;
285     switch (RetTy->getTypeID()) {
286     default: llvm_unreachable("Unknown return type for function call!");
287     case Type::IntegerTyID: {
288       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
289       if (BitWidth == 1)
290         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
291       else if (BitWidth <= 8)
292         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
293       else if (BitWidth <= 16)
294         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
295       else if (BitWidth <= 32)
296         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
297       else if (BitWidth <= 64)
298         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
299       else
300         llvm_unreachable("Integer types > 64 bits not supported");
301       return rv;
302     }
303     case Type::VoidTyID:
304       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
305       return rv;
306     case Type::FloatTyID:
307       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
308       return rv;
309     case Type::DoubleTyID:
310       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
311       return rv;
312     case Type::X86_FP80TyID:
313     case Type::FP128TyID:
314     case Type::PPC_FP128TyID:
315       llvm_unreachable("long double not supported yet");
316     case Type::PointerTyID:
317       return PTOGV(((void*(*)())(intptr_t)FPtr)());
318     }
319   }
320
321   llvm_unreachable("Full-featured argument passing not supported yet!");
322 }
323
324 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
325                                        bool AbortOnFailure) {
326   // FIXME: Add support for per-module compilation state
327   if (!IsLoaded)
328     loadObject(M);
329
330   if (!isSymbolSearchingDisabled() && MemMgr) {
331     void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
332     if (ptr)
333       return ptr;
334   }
335
336   /// If a LazyFunctionCreator is installed, use it to get/create the function.
337   if (LazyFunctionCreator)
338     if (void *RP = LazyFunctionCreator(Name))
339       return RP;
340
341   if (AbortOnFailure) {
342     report_fatal_error("Program used external function '"+Name+
343                        "' which could not be resolved!");
344   }
345   return 0;
346 }
347
348 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
349   if (L == NULL)
350     return;
351   MutexGuard locked(lock);
352   EventListeners.push_back(L);
353 }
354 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
355   if (L == NULL)
356     return;
357   MutexGuard locked(lock);
358   SmallVector<JITEventListener*, 2>::reverse_iterator I=
359       std::find(EventListeners.rbegin(), EventListeners.rend(), L);
360   if (I != EventListeners.rend()) {
361     std::swap(*I, EventListeners.back());
362     EventListeners.pop_back();
363   }
364 }
365 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
366   MutexGuard locked(lock);
367   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
368     EventListeners[I]->NotifyObjectEmitted(Obj);
369   }
370 }
371 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
372   MutexGuard locked(lock);
373   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
374     EventListeners[I]->NotifyFreeingObject(Obj);
375   }
376 }