Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:37:06

0001 //===- ModuleManager.cpp - Module Manager -----------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 //  This file defines the ModuleManager class, which manages a set of loaded
0010 //  modules for the ASTReader.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
0015 #define LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
0016 
0017 #include "clang/Basic/LLVM.h"
0018 #include "clang/Basic/SourceLocation.h"
0019 #include "clang/Serialization/ModuleFile.h"
0020 #include "llvm/ADT/DenseMap.h"
0021 #include "llvm/ADT/IntrusiveRefCntPtr.h"
0022 #include "llvm/ADT/STLExtras.h"
0023 #include "llvm/ADT/SmallPtrSet.h"
0024 #include "llvm/ADT/SmallVector.h"
0025 #include "llvm/ADT/StringRef.h"
0026 #include "llvm/ADT/iterator.h"
0027 #include "llvm/ADT/iterator_range.h"
0028 #include <cstdint>
0029 #include <ctime>
0030 #include <memory>
0031 #include <string>
0032 #include <utility>
0033 
0034 namespace clang {
0035 
0036 class FileEntry;
0037 class FileManager;
0038 class GlobalModuleIndex;
0039 class HeaderSearch;
0040 class InMemoryModuleCache;
0041 class PCHContainerReader;
0042 
0043 namespace serialization {
0044 
0045 /// Manages the set of modules loaded by an AST reader.
0046 class ModuleManager {
0047   /// The chain of AST files, in the order in which we started to load
0048   /// them.
0049   SmallVector<std::unique_ptr<ModuleFile>, 2> Chain;
0050 
0051   /// The chain of non-module PCH files. The first entry is the one named
0052   /// by the user, the last one is the one that doesn't depend on anything
0053   /// further.
0054   SmallVector<ModuleFile *, 2> PCHChain;
0055 
0056   // The roots of the dependency DAG of AST files. This is used
0057   // to implement short-circuiting logic when running DFS over the dependencies.
0058   SmallVector<ModuleFile *, 2> Roots;
0059 
0060   /// All loaded modules, indexed by name.
0061   llvm::DenseMap<const FileEntry *, ModuleFile *> Modules;
0062 
0063   /// FileManager that handles translating between filenames and
0064   /// FileEntry *.
0065   FileManager &FileMgr;
0066 
0067   /// Cache of PCM files.
0068   IntrusiveRefCntPtr<InMemoryModuleCache> ModuleCache;
0069 
0070   /// Knows how to unwrap module containers.
0071   const PCHContainerReader &PCHContainerRdr;
0072 
0073   /// Preprocessor's HeaderSearchInfo containing the module map.
0074   const HeaderSearch &HeaderSearchInfo;
0075 
0076   /// A lookup of in-memory (virtual file) buffers
0077   llvm::DenseMap<const FileEntry *, std::unique_ptr<llvm::MemoryBuffer>>
0078       InMemoryBuffers;
0079 
0080   /// The visitation order.
0081   SmallVector<ModuleFile *, 4> VisitOrder;
0082 
0083   /// The list of module files that both we and the global module index
0084   /// know about.
0085   ///
0086   /// Either the global index or the module manager may have modules that the
0087   /// other does not know about, because the global index can be out-of-date
0088   /// (in which case the module manager could have modules it does not) and
0089   /// this particular translation unit might not have loaded all of the modules
0090   /// known to the global index.
0091   SmallVector<ModuleFile *, 4> ModulesInCommonWithGlobalIndex;
0092 
0093   /// The global module index, if one is attached.
0094   ///
0095   /// The global module index will actually be owned by the ASTReader; this is
0096   /// just an non-owning pointer.
0097   GlobalModuleIndex *GlobalIndex = nullptr;
0098 
0099   /// State used by the "visit" operation to avoid malloc traffic in
0100   /// calls to visit().
0101   struct VisitState {
0102     explicit VisitState(unsigned N) : VisitNumber(N, 0) {
0103       Stack.reserve(N);
0104     }
0105 
0106     /// The stack used when marking the imports of a particular module
0107     /// as not-to-be-visited.
0108     SmallVector<ModuleFile *, 4> Stack;
0109 
0110     /// The visit number of each module file, which indicates when
0111     /// this module file was last visited.
0112     SmallVector<unsigned, 4> VisitNumber;
0113 
0114     /// The next visit number to use to mark visited module files.
0115     unsigned NextVisitNumber = 1;
0116 
0117     /// The next visit state.
0118     std::unique_ptr<VisitState> NextState;
0119   };
0120 
0121   /// The first visit() state in the chain.
0122   std::unique_ptr<VisitState> FirstVisitState;
0123 
0124   std::unique_ptr<VisitState> allocateVisitState();
0125   void returnVisitState(std::unique_ptr<VisitState> State);
0126 
0127 public:
0128   using ModuleIterator = llvm::pointee_iterator<
0129       SmallVectorImpl<std::unique_ptr<ModuleFile>>::iterator>;
0130   using ModuleConstIterator = llvm::pointee_iterator<
0131       SmallVectorImpl<std::unique_ptr<ModuleFile>>::const_iterator>;
0132   using ModuleReverseIterator = llvm::pointee_iterator<
0133       SmallVectorImpl<std::unique_ptr<ModuleFile>>::reverse_iterator>;
0134   using ModuleOffset = std::pair<uint32_t, StringRef>;
0135 
0136   explicit ModuleManager(FileManager &FileMgr, InMemoryModuleCache &ModuleCache,
0137                          const PCHContainerReader &PCHContainerRdr,
0138                          const HeaderSearch &HeaderSearchInfo);
0139 
0140   /// Forward iterator to traverse all loaded modules.
0141   ModuleIterator begin() { return Chain.begin(); }
0142 
0143   /// Forward iterator end-point to traverse all loaded modules
0144   ModuleIterator end() { return Chain.end(); }
0145 
0146   /// Const forward iterator to traverse all loaded modules.
0147   ModuleConstIterator begin() const { return Chain.begin(); }
0148 
0149   /// Const forward iterator end-point to traverse all loaded modules
0150   ModuleConstIterator end() const { return Chain.end(); }
0151 
0152   /// Reverse iterator to traverse all loaded modules.
0153   ModuleReverseIterator rbegin() { return Chain.rbegin(); }
0154 
0155   /// Reverse iterator end-point to traverse all loaded modules.
0156   ModuleReverseIterator rend() { return Chain.rend(); }
0157 
0158   /// A range covering the PCH and preamble module files loaded.
0159   llvm::iterator_range<SmallVectorImpl<ModuleFile *>::const_iterator>
0160   pch_modules() const {
0161     return llvm::make_range(PCHChain.begin(), PCHChain.end());
0162   }
0163 
0164   /// Returns the primary module associated with the manager, that is,
0165   /// the first module loaded
0166   ModuleFile &getPrimaryModule() { return *Chain[0]; }
0167 
0168   /// Returns the primary module associated with the manager, that is,
0169   /// the first module loaded.
0170   ModuleFile &getPrimaryModule() const { return *Chain[0]; }
0171 
0172   /// Returns the module associated with the given index
0173   ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; }
0174 
0175   /// Returns the module associated with the given file name.
0176   ModuleFile *lookupByFileName(StringRef FileName) const;
0177 
0178   /// Returns the module associated with the given module name.
0179   ModuleFile *lookupByModuleName(StringRef ModName) const;
0180 
0181   /// Returns the module associated with the given module file.
0182   ModuleFile *lookup(const FileEntry *File) const;
0183 
0184   /// Returns the in-memory (virtual file) buffer with the given name
0185   std::unique_ptr<llvm::MemoryBuffer> lookupBuffer(StringRef Name);
0186 
0187   /// Number of modules loaded
0188   unsigned size() const { return Chain.size(); }
0189 
0190   /// The result of attempting to add a new module.
0191   enum AddModuleResult {
0192     /// The module file had already been loaded.
0193     AlreadyLoaded,
0194 
0195     /// The module file was just loaded in response to this call.
0196     NewlyLoaded,
0197 
0198     /// The module file is missing.
0199     Missing,
0200 
0201     /// The module file is out-of-date.
0202     OutOfDate
0203   };
0204 
0205   using ASTFileSignatureReader = ASTFileSignature (*)(StringRef);
0206 
0207   /// Attempts to create a new module and add it to the list of known
0208   /// modules.
0209   ///
0210   /// \param FileName The file name of the module to be loaded.
0211   ///
0212   /// \param Type The kind of module being loaded.
0213   ///
0214   /// \param ImportLoc The location at which the module is imported.
0215   ///
0216   /// \param ImportedBy The module that is importing this module, or NULL if
0217   /// this module is imported directly by the user.
0218   ///
0219   /// \param Generation The generation in which this module was loaded.
0220   ///
0221   /// \param ExpectedSize The expected size of the module file, used for
0222   /// validation. This will be zero if unknown.
0223   ///
0224   /// \param ExpectedModTime The expected modification time of the module
0225   /// file, used for validation. This will be zero if unknown.
0226   ///
0227   /// \param ExpectedSignature The expected signature of the module file, used
0228   /// for validation. This will be zero if unknown.
0229   ///
0230   /// \param ReadSignature Reads the signature from an AST file without actually
0231   /// loading it.
0232   ///
0233   /// \param Module A pointer to the module file if the module was successfully
0234   /// loaded.
0235   ///
0236   /// \param ErrorStr Will be set to a non-empty string if any errors occurred
0237   /// while trying to load the module.
0238   ///
0239   /// \return A pointer to the module that corresponds to this file name,
0240   /// and a value indicating whether the module was loaded.
0241   AddModuleResult addModule(StringRef FileName, ModuleKind Type,
0242                             SourceLocation ImportLoc,
0243                             ModuleFile *ImportedBy, unsigned Generation,
0244                             off_t ExpectedSize, time_t ExpectedModTime,
0245                             ASTFileSignature ExpectedSignature,
0246                             ASTFileSignatureReader ReadSignature,
0247                             ModuleFile *&Module,
0248                             std::string &ErrorStr);
0249 
0250   /// Remove the modules starting from First (to the end).
0251   void removeModules(ModuleIterator First);
0252 
0253   /// Add an in-memory buffer the list of known buffers
0254   void addInMemoryBuffer(StringRef FileName,
0255                          std::unique_ptr<llvm::MemoryBuffer> Buffer);
0256 
0257   /// Set the global module index.
0258   void setGlobalIndex(GlobalModuleIndex *Index);
0259 
0260   /// Notification from the AST reader that the given module file
0261   /// has been "accepted", and will not (can not) be unloaded.
0262   void moduleFileAccepted(ModuleFile *MF);
0263 
0264   /// Visit each of the modules.
0265   ///
0266   /// This routine visits each of the modules, starting with the
0267   /// "root" modules that no other loaded modules depend on, and
0268   /// proceeding to the leaf modules, visiting each module only once
0269   /// during the traversal.
0270   ///
0271   /// This traversal is intended to support various "lookup"
0272   /// operations that can find data in any of the loaded modules.
0273   ///
0274   /// \param Visitor A visitor function that will be invoked with each
0275   /// module. The return value must be convertible to bool; when false, the
0276   /// visitation continues to modules that the current module depends on. When
0277   /// true, the visitation skips any modules that the current module depends on.
0278   ///
0279   /// \param ModuleFilesHit If non-NULL, contains the set of module files
0280   /// that we know we need to visit because the global module index told us to.
0281   /// Any module that is known to both the global module index and the module
0282   /// manager that is *not* in this set can be skipped.
0283   void visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
0284              llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit = nullptr);
0285 
0286   /// Attempt to resolve the given module file name to a file entry.
0287   ///
0288   /// \param FileName The name of the module file.
0289   ///
0290   /// \param ExpectedSize The size that the module file is expected to have.
0291   /// If the actual size differs, the resolver should return \c true.
0292   ///
0293   /// \param ExpectedModTime The modification time that the module file is
0294   /// expected to have. If the actual modification time differs, the resolver
0295   /// should return \c true.
0296   ///
0297   /// \param File Will be set to the file if there is one, or null
0298   /// otherwise.
0299   ///
0300   /// \returns True if a file exists but does not meet the size/
0301   /// modification time criteria, false if the file is either available and
0302   /// suitable, or is missing.
0303   bool lookupModuleFile(StringRef FileName, off_t ExpectedSize,
0304                         time_t ExpectedModTime, OptionalFileEntryRef &File);
0305 
0306   /// View the graphviz representation of the module graph.
0307   void viewGraph();
0308 
0309   InMemoryModuleCache &getModuleCache() const { return *ModuleCache; }
0310 };
0311 
0312 } // namespace serialization
0313 
0314 } // namespace clang
0315 
0316 #endif // LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H