MCJIT.h 13 KB

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