MCJIT.h 13 KB

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