6f92e51b64c8ba9bf374c23fe22ce5461cf8d095
[oota-llvm.git] / lib / ExecutionEngine / MCJIT / MCJIT.h
1 //===-- MCJIT.h - Class definition for the MCJIT ----------------*- C++ -*-===//
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 #ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
11 #define LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
12
13 #include "ObjectBuffer.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ExecutionEngine/ExecutionEngine.h"
18 #include "llvm/ExecutionEngine/ObjectCache.h"
19 #include "llvm/ExecutionEngine/RuntimeDyld.h"
20 #include "llvm/IR/Module.h"
21
22 namespace llvm {
23 class MCJIT;
24
25 // This is a helper class that the MCJIT execution engine uses for linking
26 // functions across modules that it owns.  It aggregates the memory manager
27 // that is passed in to the MCJIT constructor and defers most functionality
28 // to that object.
29 class LinkingMemoryManager : public RTDyldMemoryManager {
30 public:
31   LinkingMemoryManager(MCJIT *Parent, RTDyldMemoryManager *MM)
32     : ParentEngine(Parent), ClientMM(MM) {}
33
34   uint64_t getSymbolAddress(const std::string &Name) override;
35
36   // Functions deferred to client memory manager
37   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
38                                unsigned SectionID,
39                                StringRef SectionName) override {
40     return ClientMM->allocateCodeSection(Size, Alignment, SectionID, SectionName);
41   }
42
43   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
44                                unsigned SectionID, StringRef SectionName,
45                                bool IsReadOnly) override {
46     return ClientMM->allocateDataSection(Size, Alignment,
47                                          SectionID, SectionName, IsReadOnly);
48   }
49
50   void reserveAllocationSpace(uintptr_t CodeSize, uintptr_t DataSizeRO,
51                               uintptr_t DataSizeRW) override {
52     return ClientMM->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
53   }
54
55   bool needsToReserveAllocationSpace() override {
56     return ClientMM->needsToReserveAllocationSpace();
57   }
58
59   void notifyObjectLoaded(ExecutionEngine *EE,
60                           const object::ObjectFile &Obj) override {
61     ClientMM->notifyObjectLoaded(EE, Obj);
62   }
63
64   void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
65                         size_t Size) override {
66     ClientMM->registerEHFrames(Addr, LoadAddr, Size);
67   }
68
69   void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
70                           size_t Size) override {
71     ClientMM->deregisterEHFrames(Addr, LoadAddr, Size);
72   }
73
74   bool finalizeMemory(std::string *ErrMsg = nullptr) override {
75     return ClientMM->finalizeMemory(ErrMsg);
76   }
77
78 private:
79   MCJIT *ParentEngine;
80   std::unique_ptr<RTDyldMemoryManager> ClientMM;
81 };
82
83 // About Module states: added->loaded->finalized.
84 //
85 // The purpose of the "added" state is having modules in standby. (added=known
86 // but not compiled). The idea is that you can add a module to provide function
87 // definitions but if nothing in that module is referenced by a module in which
88 // a function is executed (note the wording here because it's not exactly the
89 // ideal case) then the module never gets compiled. This is sort of lazy
90 // compilation.
91 //
92 // The purpose of the "loaded" state (loaded=compiled and required sections
93 // copied into local memory but not yet ready for execution) is to have an
94 // intermediate state wherein clients can remap the addresses of sections, using
95 // MCJIT::mapSectionAddress, (in preparation for later copying to a new location
96 // or an external process) before relocations and page permissions are applied.
97 //
98 // It might not be obvious at first glance, but the "remote-mcjit" case in the
99 // lli tool does this.  In that case, the intermediate action is taken by the
100 // RemoteMemoryManager in response to the notifyObjectLoaded function being
101 // called.
102
103 class MCJIT : public ExecutionEngine {
104   MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
105         RTDyldMemoryManager *MemMgr);
106
107   typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;
108
109   class OwningModuleContainer {
110   public:
111     OwningModuleContainer() {
112     }
113     ~OwningModuleContainer() {
114       freeModulePtrSet(AddedModules);
115       freeModulePtrSet(LoadedModules);
116       freeModulePtrSet(FinalizedModules);
117     }
118
119     ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
120     ModulePtrSet::iterator end_added() { return AddedModules.end(); }
121     iterator_range<ModulePtrSet::iterator> added() {
122       return iterator_range<ModulePtrSet::iterator>(begin_added(), end_added());
123     }
124
125     ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
126     ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
127
128     ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
129     ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
130
131     void addModule(std::unique_ptr<Module> M) {
132       AddedModules.insert(M.release());
133     }
134
135     bool removeModule(Module *M) {
136       return AddedModules.erase(M) || LoadedModules.erase(M) ||
137              FinalizedModules.erase(M);
138     }
139
140     bool hasModuleBeenAddedButNotLoaded(Module *M) {
141       return AddedModules.count(M) != 0;
142     }
143
144     bool hasModuleBeenLoaded(Module *M) {
145       // If the module is in either the "loaded" or "finalized" sections it
146       // has been loaded.
147       return (LoadedModules.count(M) != 0 ) || (FinalizedModules.count(M) != 0);
148     }
149
150     bool hasModuleBeenFinalized(Module *M) {
151       return FinalizedModules.count(M) != 0;
152     }
153
154     bool ownsModule(Module* M) {
155       return (AddedModules.count(M) != 0) || (LoadedModules.count(M) != 0) ||
156              (FinalizedModules.count(M) != 0);
157     }
158
159     void markModuleAsLoaded(Module *M) {
160       // This checks against logic errors in the MCJIT implementation.
161       // This function should never be called with either a Module that MCJIT
162       // does not own or a Module that has already been loaded and/or finalized.
163       assert(AddedModules.count(M) &&
164              "markModuleAsLoaded: Module not found in AddedModules");
165
166       // Remove the module from the "Added" set.
167       AddedModules.erase(M);
168
169       // Add the Module to the "Loaded" set.
170       LoadedModules.insert(M);
171     }
172
173     void markModuleAsFinalized(Module *M) {
174       // This checks against logic errors in the MCJIT implementation.
175       // This function should never be called with either a Module that MCJIT
176       // does not own, a Module that has not been loaded or a Module that has
177       // already been finalized.
178       assert(LoadedModules.count(M) &&
179              "markModuleAsFinalized: Module not found in LoadedModules");
180
181       // Remove the module from the "Loaded" section of the list.
182       LoadedModules.erase(M);
183
184       // Add the Module to the "Finalized" section of the list by inserting it
185       // before the 'end' iterator.
186       FinalizedModules.insert(M);
187     }
188
189     void markAllLoadedModulesAsFinalized() {
190       for (ModulePtrSet::iterator I = LoadedModules.begin(),
191                                   E = LoadedModules.end();
192            I != E; ++I) {
193         Module *M = *I;
194         FinalizedModules.insert(M);
195       }
196       LoadedModules.clear();
197     }
198
199   private:
200     ModulePtrSet AddedModules;
201     ModulePtrSet LoadedModules;
202     ModulePtrSet FinalizedModules;
203
204     void freeModulePtrSet(ModulePtrSet& MPS) {
205       // Go through the module set and delete everything.
206       for (ModulePtrSet::iterator I = MPS.begin(), E = MPS.end(); I != E; ++I) {
207         Module *M = *I;
208         delete M;
209       }
210       MPS.clear();
211     }
212   };
213
214   std::unique_ptr<TargetMachine> TM;
215   MCContext *Ctx;
216   LinkingMemoryManager MemMgr;
217   RuntimeDyld Dyld;
218   std::vector<JITEventListener*> EventListeners;
219
220   OwningModuleContainer OwnedModules;
221
222   SmallVector<object::OwningBinary<object::Archive>, 2> Archives;
223   SmallVector<std::unique_ptr<MemoryBuffer>, 2> Buffers;
224
225   SmallVector<std::unique_ptr<object::ObjectFile>, 2> LoadedObjects;
226
227   // An optional ObjectCache to be notified of compiled objects and used to
228   // perform lookup of pre-compiled code to avoid re-compilation.
229   ObjectCache *ObjCache;
230
231   Function *FindFunctionNamedInModulePtrSet(const char *FnName,
232                                             ModulePtrSet::iterator I,
233                                             ModulePtrSet::iterator E);
234
235   void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
236                                                       ModulePtrSet::iterator I,
237                                                       ModulePtrSet::iterator E);
238
239 public:
240   ~MCJIT();
241
242   /// @name ExecutionEngine interface implementation
243   /// @{
244   void addModule(std::unique_ptr<Module> M) override;
245   void addObjectFile(std::unique_ptr<object::ObjectFile> O) override;
246   void addObjectFile(object::OwningBinary<object::ObjectFile> O) override;
247   void addArchive(object::OwningBinary<object::Archive> O) override;
248   bool removeModule(Module *M) override;
249
250   /// FindFunctionNamed - Search all of the active modules to find the one that
251   /// defines FnName.  This is very slow operation and shouldn't be used for
252   /// general code.
253   Function *FindFunctionNamed(const char *FnName) override;
254
255   /// Sets the object manager that MCJIT should use to avoid compilation.
256   void setObjectCache(ObjectCache *manager) override;
257
258   void setProcessAllSections(bool ProcessAllSections) override {
259     Dyld.setProcessAllSections(ProcessAllSections);
260   }
261
262   void generateCodeForModule(Module *M) override;
263
264   /// finalizeObject - ensure the module is fully processed and is usable.
265   ///
266   /// It is the user-level function for completing the process of making the
267   /// object usable for execution. It should be called after sections within an
268   /// object have been relocated using mapSectionAddress.  When this method is
269   /// called the MCJIT execution engine will reapply relocations for a loaded
270   /// object.
271   /// Is it OK to finalize a set of modules, add modules and finalize again.
272   // FIXME: Do we really need both of these?
273   void finalizeObject() override;
274   virtual void finalizeModule(Module *);
275   void finalizeLoadedModules();
276
277   /// runStaticConstructorsDestructors - This method is used to execute all of
278   /// the static constructors or destructors for a program.
279   ///
280   /// \param isDtors - Run the destructors instead of constructors.
281   void runStaticConstructorsDestructors(bool isDtors) override;
282
283   void *getPointerToFunction(Function *F) override;
284
285   GenericValue runFunction(Function *F,
286                            const std::vector<GenericValue> &ArgValues) override;
287
288   /// getPointerToNamedFunction - This method returns the address of the
289   /// specified function by using the dlsym function call.  As such it is only
290   /// useful for resolving library symbols, not code generated symbols.
291   ///
292   /// If AbortOnFailure is false and no function with the given name is
293   /// found, this function silently returns a null pointer. Otherwise,
294   /// it prints a message to stderr and aborts.
295   ///
296   void *getPointerToNamedFunction(StringRef Name,
297                                   bool AbortOnFailure = true) override;
298
299   /// mapSectionAddress - map a section to its target address space value.
300   /// Map the address of a JIT section as returned from the memory manager
301   /// to the address in the target process as the running code will see it.
302   /// This is the address which will be used for relocation resolution.
303   void mapSectionAddress(const void *LocalAddress,
304                          uint64_t TargetAddress) override {
305     Dyld.mapSectionAddress(LocalAddress, TargetAddress);
306   }
307   void RegisterJITEventListener(JITEventListener *L) override;
308   void UnregisterJITEventListener(JITEventListener *L) override;
309
310   // If successful, these function will implicitly finalize all loaded objects.
311   // To get a function address within MCJIT without causing a finalize, use
312   // getSymbolAddress.
313   uint64_t getGlobalValueAddress(const std::string &Name) override;
314   uint64_t getFunctionAddress(const std::string &Name) override;
315
316   TargetMachine *getTargetMachine() override { return TM.get(); }
317
318   /// @}
319   /// @name (Private) Registration Interfaces
320   /// @{
321
322   static void Register() {
323     MCJITCtor = createJIT;
324   }
325
326   static ExecutionEngine *createJIT(std::unique_ptr<Module> M,
327                                     std::string *ErrorStr,
328                                     RTDyldMemoryManager *MemMgr,
329                                     std::unique_ptr<TargetMachine> TM);
330
331   // @}
332
333   // This is not directly exposed via the ExecutionEngine API, but it is
334   // used by the LinkingMemoryManager.
335   uint64_t getSymbolAddress(const std::string &Name,
336                           bool CheckFunctionsOnly);
337
338 protected:
339   /// emitObject -- Generate a JITed object in memory from the specified module
340   /// Currently, MCJIT only supports a single module and the module passed to
341   /// this function call is expected to be the contained module.  The module
342   /// is passed as a parameter here to prepare for multiple module support in
343   /// the future.
344   std::unique_ptr<MemoryBuffer> emitObject(Module *M);
345
346   void NotifyObjectEmitted(const object::ObjectFile& Obj,
347                            const RuntimeDyld::LoadedObjectInfo &L);
348   void NotifyFreeingObject(const object::ObjectFile& Obj);
349
350   uint64_t getExistingSymbolAddress(const std::string &Name);
351   Module *findModuleForSymbol(const std::string &Name,
352                               bool CheckFunctionsOnly);
353 };
354
355 } // End llvm namespace
356
357 #endif