1 //===-- MCJIT.h - Class definition for the MCJIT ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_H
11 #define LLVM_LIB_EXECUTIONENGINE_MCJIT_H
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ExecutionEngine/ObjectCache.h"
18 #include "llvm/ExecutionEngine/ObjectImage.h"
19 #include "llvm/ExecutionEngine/RuntimeDyld.h"
20 #include "llvm/IR/Module.h"
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
29 class LinkingMemoryManager : public RTDyldMemoryManager {
31 LinkingMemoryManager(MCJIT *Parent, RTDyldMemoryManager *MM)
32 : ParentEngine(Parent), ClientMM(MM) {}
34 virtual uint64_t getSymbolAddress(const std::string &Name);
36 // Functions deferred to client memory manager
37 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
38 unsigned SectionID, StringRef SectionName) {
39 return ClientMM->allocateCodeSection(Size, Alignment, SectionID, SectionName);
42 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
43 unsigned SectionID, StringRef SectionName,
45 return ClientMM->allocateDataSection(Size, Alignment,
46 SectionID, SectionName, IsReadOnly);
49 virtual void notifyObjectLoaded(ExecutionEngine *EE,
50 const ObjectImage *Obj) {
51 ClientMM->notifyObjectLoaded(EE, Obj);
54 virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {
55 ClientMM->registerEHFrames(Addr, LoadAddr, Size);
58 virtual void deregisterEHFrames(uint8_t *Addr,
61 ClientMM->deregisterEHFrames(Addr, LoadAddr, Size);
64 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
65 return ClientMM->finalizeMemory(ErrMsg);
70 OwningPtr<RTDyldMemoryManager> ClientMM;
73 // About Module states: added->loaded->finalized.
75 // The purpose of the "added" state is having modules in standby. (added=known
76 // but not compiled). The idea is that you can add a module to provide function
77 // definitions but if nothing in that module is referenced by a module in which
78 // a function is executed (note the wording here because it's not exactly the
79 // ideal case) then the module never gets compiled. This is sort of lazy
82 // The purpose of the "loaded" state (loaded=compiled and required sections
83 // copied into local memory but not yet ready for execution) is to have an
84 // intermediate state wherein clients can remap the addresses of sections, using
85 // MCJIT::mapSectionAddress, (in preparation for later copying to a new location
86 // or an external process) before relocations and page permissions are applied.
88 // It might not be obvious at first glance, but the "remote-mcjit" case in the
89 // lli tool does this. In that case, the intermediate action is taken by the
90 // RemoteMemoryManager in response to the notifyObjectLoaded function being
93 class MCJIT : public ExecutionEngine {
94 MCJIT(Module *M, TargetMachine *tm, RTDyldMemoryManager *MemMgr,
95 bool AllocateGVsWithCode);
97 typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;
99 class OwningModuleContainer {
101 OwningModuleContainer() {
103 ~OwningModuleContainer() {
104 freeModulePtrSet(AddedModules);
105 freeModulePtrSet(LoadedModules);
106 freeModulePtrSet(FinalizedModules);
109 ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
110 ModulePtrSet::iterator end_added() { return AddedModules.end(); }
112 ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
113 ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
115 ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
116 ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
118 void addModule(Module *M) {
119 AddedModules.insert(M);
122 bool removeModule(Module *M) {
123 return AddedModules.erase(M) || LoadedModules.erase(M) ||
124 FinalizedModules.erase(M);
127 bool hasModuleBeenAddedButNotLoaded(Module *M) {
128 return AddedModules.count(M) != 0;
131 bool hasModuleBeenLoaded(Module *M) {
132 // If the module is in either the "loaded" or "finalized" sections it
134 return (LoadedModules.count(M) != 0 ) || (FinalizedModules.count(M) != 0);
137 bool hasModuleBeenFinalized(Module *M) {
138 return FinalizedModules.count(M) != 0;
141 bool ownsModule(Module* M) {
142 return (AddedModules.count(M) != 0) || (LoadedModules.count(M) != 0) ||
143 (FinalizedModules.count(M) != 0);
146 void markModuleAsLoaded(Module *M) {
147 // This checks against logic errors in the MCJIT implementation.
148 // This function should never be called with either a Module that MCJIT
149 // does not own or a Module that has already been loaded and/or finalized.
150 assert(AddedModules.count(M) &&
151 "markModuleAsLoaded: Module not found in AddedModules");
153 // Remove the module from the "Added" set.
154 AddedModules.erase(M);
156 // Add the Module to the "Loaded" set.
157 LoadedModules.insert(M);
160 void markModuleAsFinalized(Module *M) {
161 // This checks against logic errors in the MCJIT implementation.
162 // This function should never be called with either a Module that MCJIT
163 // does not own, a Module that has not been loaded or a Module that has
164 // already been finalized.
165 assert(LoadedModules.count(M) &&
166 "markModuleAsFinalized: Module not found in LoadedModules");
168 // Remove the module from the "Loaded" section of the list.
169 LoadedModules.erase(M);
171 // Add the Module to the "Finalized" section of the list by inserting it
172 // before the 'end' iterator.
173 FinalizedModules.insert(M);
176 void markAllLoadedModulesAsFinalized() {
177 for (ModulePtrSet::iterator I = LoadedModules.begin(),
178 E = LoadedModules.end();
181 FinalizedModules.insert(M);
183 LoadedModules.clear();
187 ModulePtrSet AddedModules;
188 ModulePtrSet LoadedModules;
189 ModulePtrSet FinalizedModules;
191 void freeModulePtrSet(ModulePtrSet& MPS) {
192 // Go through the module set and delete everything.
193 for (ModulePtrSet::iterator I = MPS.begin(), E = MPS.end(); I != E; ++I) {
203 LinkingMemoryManager MemMgr;
205 SmallVector<JITEventListener*, 2> EventListeners;
207 OwningModuleContainer OwnedModules;
209 SmallVector<object::Archive*, 2> Archives;
211 typedef SmallVector<ObjectImage *, 2> LoadedObjectList;
212 LoadedObjectList LoadedObjects;
214 // An optional ObjectCache to be notified of compiled objects and used to
215 // perform lookup of pre-compiled code to avoid re-compilation.
216 ObjectCache *ObjCache;
218 Function *FindFunctionNamedInModulePtrSet(const char *FnName,
219 ModulePtrSet::iterator I,
220 ModulePtrSet::iterator E);
222 void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
223 ModulePtrSet::iterator I,
224 ModulePtrSet::iterator E);
229 /// @name ExecutionEngine interface implementation
231 virtual void addModule(Module *M);
232 virtual void addObjectFile(object::ObjectFile *O);
233 virtual void addArchive(object::Archive *O);
234 virtual bool removeModule(Module *M);
236 /// FindFunctionNamed - Search all of the active modules to find the one that
237 /// defines FnName. This is very slow operation and shouldn't be used for
239 virtual Function *FindFunctionNamed(const char *FnName);
241 /// Sets the object manager that MCJIT should use to avoid compilation.
242 virtual void setObjectCache(ObjectCache *manager);
244 virtual void generateCodeForModule(Module *M);
246 /// finalizeObject - ensure the module is fully processed and is usable.
248 /// It is the user-level function for completing the process of making the
249 /// object usable for execution. It should be called after sections within an
250 /// object have been relocated using mapSectionAddress. When this method is
251 /// called the MCJIT execution engine will reapply relocations for a loaded
253 /// Is it OK to finalize a set of modules, add modules and finalize again.
254 // FIXME: Do we really need both of these?
255 virtual void finalizeObject();
256 virtual void finalizeModule(Module *);
257 void finalizeLoadedModules();
259 /// runStaticConstructorsDestructors - This method is used to execute all of
260 /// the static constructors or destructors for a program.
262 /// \param isDtors - Run the destructors instead of constructors.
263 void runStaticConstructorsDestructors(bool isDtors);
265 virtual void *getPointerToBasicBlock(BasicBlock *BB);
267 virtual void *getPointerToFunction(Function *F);
269 virtual void *recompileAndRelinkFunction(Function *F);
271 virtual void freeMachineCodeForFunction(Function *F);
273 virtual GenericValue runFunction(Function *F,
274 const std::vector<GenericValue> &ArgValues);
276 /// getPointerToNamedFunction - This method returns the address of the
277 /// specified function by using the dlsym function call. As such it is only
278 /// useful for resolving library symbols, not code generated symbols.
280 /// If AbortOnFailure is false and no function with the given name is
281 /// found, this function silently returns a null pointer. Otherwise,
282 /// it prints a message to stderr and aborts.
284 virtual void *getPointerToNamedFunction(const std::string &Name,
285 bool AbortOnFailure = true);
287 /// mapSectionAddress - map a section to its target address space value.
288 /// Map the address of a JIT section as returned from the memory manager
289 /// to the address in the target process as the running code will see it.
290 /// This is the address which will be used for relocation resolution.
291 virtual void mapSectionAddress(const void *LocalAddress,
292 uint64_t TargetAddress) {
293 Dyld.mapSectionAddress(LocalAddress, TargetAddress);
295 virtual void RegisterJITEventListener(JITEventListener *L);
296 virtual void UnregisterJITEventListener(JITEventListener *L);
298 // If successful, these function will implicitly finalize all loaded objects.
299 // To get a function address within MCJIT without causing a finalize, use
301 virtual uint64_t getGlobalValueAddress(const std::string &Name);
302 virtual uint64_t getFunctionAddress(const std::string &Name);
304 virtual TargetMachine *getTargetMachine() { return TM; }
307 /// @name (Private) Registration Interfaces
310 static void Register() {
311 MCJITCtor = createJIT;
314 static ExecutionEngine *createJIT(Module *M,
315 std::string *ErrorStr,
316 RTDyldMemoryManager *MemMgr,
322 // This is not directly exposed via the ExecutionEngine API, but it is
323 // used by the LinkingMemoryManager.
324 uint64_t getSymbolAddress(const std::string &Name,
325 bool CheckFunctionsOnly);
328 /// emitObject -- Generate a JITed object in memory from the specified module
329 /// Currently, MCJIT only supports a single module and the module passed to
330 /// this function call is expected to be the contained module. The module
331 /// is passed as a parameter here to prepare for multiple module support in
333 ObjectBufferStream* emitObject(Module *M);
335 void NotifyObjectEmitted(const ObjectImage& Obj);
336 void NotifyFreeingObject(const ObjectImage& Obj);
338 uint64_t getExistingSymbolAddress(const std::string &Name);
339 Module *findModuleForSymbol(const std::string &Name,
340 bool CheckFunctionsOnly);
343 } // End llvm namespace