Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h
35266 views
//===-- MCJIT.h - Class definition for the MCJIT ----------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H9#define LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H1011#include "llvm/ADT/SmallPtrSet.h"12#include "llvm/ADT/SmallVector.h"13#include "llvm/ExecutionEngine/ExecutionEngine.h"14#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"15#include "llvm/ExecutionEngine/RuntimeDyld.h"1617namespace llvm {18class MCJIT;19class Module;20class ObjectCache;2122// This is a helper class that the MCJIT execution engine uses for linking23// functions across modules that it owns. It aggregates the memory manager24// that is passed in to the MCJIT constructor and defers most functionality25// to that object.26class LinkingSymbolResolver : public LegacyJITSymbolResolver {27public:28LinkingSymbolResolver(MCJIT &Parent,29std::shared_ptr<LegacyJITSymbolResolver> Resolver)30: ParentEngine(Parent), ClientResolver(std::move(Resolver)) {}3132JITSymbol findSymbol(const std::string &Name) override;3334// MCJIT doesn't support logical dylibs.35JITSymbol findSymbolInLogicalDylib(const std::string &Name) override {36return nullptr;37}3839private:40MCJIT &ParentEngine;41std::shared_ptr<LegacyJITSymbolResolver> ClientResolver;42void anchor() override;43};4445// About Module states: added->loaded->finalized.46//47// The purpose of the "added" state is having modules in standby. (added=known48// but not compiled). The idea is that you can add a module to provide function49// definitions but if nothing in that module is referenced by a module in which50// a function is executed (note the wording here because it's not exactly the51// ideal case) then the module never gets compiled. This is sort of lazy52// compilation.53//54// The purpose of the "loaded" state (loaded=compiled and required sections55// copied into local memory but not yet ready for execution) is to have an56// intermediate state wherein clients can remap the addresses of sections, using57// MCJIT::mapSectionAddress, (in preparation for later copying to a new location58// or an external process) before relocations and page permissions are applied.59//60// It might not be obvious at first glance, but the "remote-mcjit" case in the61// lli tool does this. In that case, the intermediate action is taken by the62// RemoteMemoryManager in response to the notifyObjectLoaded function being63// called.6465class MCJIT : public ExecutionEngine {66MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,67std::shared_ptr<MCJITMemoryManager> MemMgr,68std::shared_ptr<LegacyJITSymbolResolver> Resolver);6970typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;7172class OwningModuleContainer {73public:74OwningModuleContainer() = default;75~OwningModuleContainer() {76freeModulePtrSet(AddedModules);77freeModulePtrSet(LoadedModules);78freeModulePtrSet(FinalizedModules);79}8081ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }82ModulePtrSet::iterator end_added() { return AddedModules.end(); }83iterator_range<ModulePtrSet::iterator> added() {84return make_range(begin_added(), end_added());85}8687ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }88ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }8990ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }91ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }9293void addModule(std::unique_ptr<Module> M) {94AddedModules.insert(M.release());95}9697bool removeModule(Module *M) {98return AddedModules.erase(M) || LoadedModules.erase(M) ||99FinalizedModules.erase(M);100}101102bool hasModuleBeenAddedButNotLoaded(Module *M) {103return AddedModules.contains(M);104}105106bool hasModuleBeenLoaded(Module *M) {107// If the module is in either the "loaded" or "finalized" sections it108// has been loaded.109return LoadedModules.contains(M) || FinalizedModules.contains(M);110}111112bool hasModuleBeenFinalized(Module *M) {113return FinalizedModules.contains(M);114}115116bool ownsModule(Module* M) {117return AddedModules.contains(M) || LoadedModules.contains(M) ||118FinalizedModules.contains(M);119}120121void markModuleAsLoaded(Module *M) {122// This checks against logic errors in the MCJIT implementation.123// This function should never be called with either a Module that MCJIT124// does not own or a Module that has already been loaded and/or finalized.125assert(AddedModules.count(M) &&126"markModuleAsLoaded: Module not found in AddedModules");127128// Remove the module from the "Added" set.129AddedModules.erase(M);130131// Add the Module to the "Loaded" set.132LoadedModules.insert(M);133}134135void markModuleAsFinalized(Module *M) {136// This checks against logic errors in the MCJIT implementation.137// This function should never be called with either a Module that MCJIT138// does not own, a Module that has not been loaded or a Module that has139// already been finalized.140assert(LoadedModules.count(M) &&141"markModuleAsFinalized: Module not found in LoadedModules");142143// Remove the module from the "Loaded" section of the list.144LoadedModules.erase(M);145146// Add the Module to the "Finalized" section of the list by inserting it147// before the 'end' iterator.148FinalizedModules.insert(M);149}150151void markAllLoadedModulesAsFinalized() {152for (Module *M : LoadedModules)153FinalizedModules.insert(M);154LoadedModules.clear();155}156157private:158ModulePtrSet AddedModules;159ModulePtrSet LoadedModules;160ModulePtrSet FinalizedModules;161162void freeModulePtrSet(ModulePtrSet& MPS) {163// Go through the module set and delete everything.164for (Module *M : MPS)165delete M;166MPS.clear();167}168};169170std::unique_ptr<TargetMachine> TM;171MCContext *Ctx;172std::shared_ptr<MCJITMemoryManager> MemMgr;173LinkingSymbolResolver Resolver;174RuntimeDyld Dyld;175std::vector<JITEventListener*> EventListeners;176177OwningModuleContainer OwnedModules;178179SmallVector<object::OwningBinary<object::Archive>, 2> Archives;180SmallVector<std::unique_ptr<MemoryBuffer>, 2> Buffers;181182SmallVector<std::unique_ptr<object::ObjectFile>, 2> LoadedObjects;183184// An optional ObjectCache to be notified of compiled objects and used to185// perform lookup of pre-compiled code to avoid re-compilation.186ObjectCache *ObjCache;187188Function *FindFunctionNamedInModulePtrSet(StringRef FnName,189ModulePtrSet::iterator I,190ModulePtrSet::iterator E);191192GlobalVariable *FindGlobalVariableNamedInModulePtrSet(StringRef Name,193bool AllowInternal,194ModulePtrSet::iterator I,195ModulePtrSet::iterator E);196197void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,198ModulePtrSet::iterator I,199ModulePtrSet::iterator E);200201public:202~MCJIT() override;203204/// @name ExecutionEngine interface implementation205/// @{206void addModule(std::unique_ptr<Module> M) override;207void addObjectFile(std::unique_ptr<object::ObjectFile> O) override;208void addObjectFile(object::OwningBinary<object::ObjectFile> O) override;209void addArchive(object::OwningBinary<object::Archive> O) override;210bool removeModule(Module *M) override;211212/// FindFunctionNamed - Search all of the active modules to find the function that213/// defines FnName. This is very slow operation and shouldn't be used for214/// general code.215Function *FindFunctionNamed(StringRef FnName) override;216217/// FindGlobalVariableNamed - Search all of the active modules to find the218/// global variable that defines Name. This is very slow operation and219/// shouldn't be used for general code.220GlobalVariable *FindGlobalVariableNamed(StringRef Name,221bool AllowInternal = false) override;222223/// Sets the object manager that MCJIT should use to avoid compilation.224void setObjectCache(ObjectCache *manager) override;225226void setProcessAllSections(bool ProcessAllSections) override {227Dyld.setProcessAllSections(ProcessAllSections);228}229230void generateCodeForModule(Module *M) override;231232/// finalizeObject - ensure the module is fully processed and is usable.233///234/// It is the user-level function for completing the process of making the235/// object usable for execution. It should be called after sections within an236/// object have been relocated using mapSectionAddress. When this method is237/// called the MCJIT execution engine will reapply relocations for a loaded238/// object.239/// Is it OK to finalize a set of modules, add modules and finalize again.240// FIXME: Do we really need both of these?241void finalizeObject() override;242virtual void finalizeModule(Module *);243void finalizeLoadedModules();244245/// runStaticConstructorsDestructors - This method is used to execute all of246/// the static constructors or destructors for a program.247///248/// \param isDtors - Run the destructors instead of constructors.249void runStaticConstructorsDestructors(bool isDtors) override;250251void *getPointerToFunction(Function *F) override;252253GenericValue runFunction(Function *F,254ArrayRef<GenericValue> ArgValues) override;255256/// getPointerToNamedFunction - This method returns the address of the257/// specified function by using the dlsym function call. As such it is only258/// useful for resolving library symbols, not code generated symbols.259///260/// If AbortOnFailure is false and no function with the given name is261/// found, this function silently returns a null pointer. Otherwise,262/// it prints a message to stderr and aborts.263///264void *getPointerToNamedFunction(StringRef Name,265bool AbortOnFailure = true) override;266267/// mapSectionAddress - map a section to its target address space value.268/// Map the address of a JIT section as returned from the memory manager269/// to the address in the target process as the running code will see it.270/// This is the address which will be used for relocation resolution.271void mapSectionAddress(const void *LocalAddress,272uint64_t TargetAddress) override {273Dyld.mapSectionAddress(LocalAddress, TargetAddress);274}275void RegisterJITEventListener(JITEventListener *L) override;276void UnregisterJITEventListener(JITEventListener *L) override;277278// If successful, these function will implicitly finalize all loaded objects.279// To get a function address within MCJIT without causing a finalize, use280// getSymbolAddress.281uint64_t getGlobalValueAddress(const std::string &Name) override;282uint64_t getFunctionAddress(const std::string &Name) override;283284TargetMachine *getTargetMachine() override { return TM.get(); }285286/// @}287/// @name (Private) Registration Interfaces288/// @{289290static void Register() {291MCJITCtor = createJIT;292}293294static ExecutionEngine *295createJIT(std::unique_ptr<Module> M, std::string *ErrorStr,296std::shared_ptr<MCJITMemoryManager> MemMgr,297std::shared_ptr<LegacyJITSymbolResolver> Resolver,298std::unique_ptr<TargetMachine> TM);299300// @}301302// Takes a mangled name and returns the corresponding JITSymbol (if a303// definition of that mangled name has been added to the JIT).304JITSymbol findSymbol(const std::string &Name, bool CheckFunctionsOnly);305306// DEPRECATED - Please use findSymbol instead.307//308// This is not directly exposed via the ExecutionEngine API, but it is309// used by the LinkingMemoryManager.310//311// getSymbolAddress takes an unmangled name and returns the corresponding312// JITSymbol if a definition of the name has been added to the JIT.313uint64_t getSymbolAddress(const std::string &Name,314bool CheckFunctionsOnly);315316protected:317/// emitObject -- Generate a JITed object in memory from the specified module318/// Currently, MCJIT only supports a single module and the module passed to319/// this function call is expected to be the contained module. The module320/// is passed as a parameter here to prepare for multiple module support in321/// the future.322std::unique_ptr<MemoryBuffer> emitObject(Module *M);323324void notifyObjectLoaded(const object::ObjectFile &Obj,325const RuntimeDyld::LoadedObjectInfo &L);326void notifyFreeingObject(const object::ObjectFile &Obj);327328JITSymbol findExistingSymbol(const std::string &Name);329Module *findModuleForSymbol(const std::string &Name, bool CheckFunctionsOnly);330};331332} // end llvm namespace333334#endif // LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H335336337