clang 23.0.0git
ModuleManager.h
Go to the documentation of this file.
1//===- ModuleManager.cpp - Module Manager -----------------------*- 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//
9// This file defines the ModuleManager class, which manages a set of loaded
10// modules for the ASTReader.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
15#define LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
16
17#include "clang/Basic/LLVM.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include <cstdint>
29#include <ctime>
30#include <memory>
31#include <string>
32#include <utility>
33
34namespace clang {
35
36class FileEntry;
37class FileManager;
39class HeaderSearch;
40class ModuleCache;
42
43namespace serialization {
44
45/// The result of attempting to add a new module.
47public:
48 enum Kind {
49 /// State at construction.
51 /// The module file had already been loaded.
53 /// The module file was just loaded in response to this call.
55 /// The module file is missing.
57 /// The module file is out-of-date.
59 };
60
61 Kind getKind() const { return K; };
62
63 ModuleFile *getModule() const { return Module; }
64
65 StringRef getBufferError() const {
66 assert(K == Missing && !Module);
67 return BufferError;
68 }
69
71 assert(K == OutOfDate && !Module);
72 return Changes;
73 }
74
76 assert(K == OutOfDate && !Module);
77 return ValidationStatus;
78 }
79
80 StringRef getSignatureError() const {
81 assert(K == OutOfDate && !Module);
82 return SignatureError;
83 }
84
86 K = OutOfDate;
87 ValidationStatus = Status;
88 }
89
90private:
91 friend class ModuleManager;
92
93 Kind K = None;
94 ModuleFile *Module = nullptr;
97 std::string BufferError;
98 std::string SignatureError;
99};
100
101/// Manages the set of modules loaded by an AST reader.
103 /// The chain of AST files, in the order in which we started to load
104 /// them.
106
107 /// The chain of non-module PCH files. The first entry is the one named
108 /// by the user, the last one is the one that doesn't depend on anything
109 /// further.
111
112 // The roots of the dependency DAG of AST files. This is used
113 // to implement short-circuiting logic when running DFS over the dependencies.
115
116 /// All loaded modules.
117 llvm::DenseMap<ModuleFileKey, ModuleFile *> Modules;
118
119 /// FileManager that handles translating between filenames and
120 /// FileEntry *.
121 FileManager &FileMgr;
122
123 /// Cache of PCM files.
124 ModuleCache &ModCache;
125
126 /// Knows how to unwrap module containers.
127 const PCHContainerReader &PCHContainerRdr;
128
129 /// Preprocessor's HeaderSearchInfo containing the module map.
130 const HeaderSearch &HeaderSearchInfo;
131
132 /// The visitation order.
134
135 /// The list of module files that both we and the global module index
136 /// know about.
137 ///
138 /// Either the global index or the module manager may have modules that the
139 /// other does not know about, because the global index can be out-of-date
140 /// (in which case the module manager could have modules it does not) and
141 /// this particular translation unit might not have loaded all of the modules
142 /// known to the global index.
143 SmallVector<ModuleFile *, 4> ModulesInCommonWithGlobalIndex;
144
145 /// The global module index, if one is attached.
146 ///
147 /// The global module index will actually be owned by the ASTReader; this is
148 /// just an non-owning pointer.
149 GlobalModuleIndex *GlobalIndex = nullptr;
150
151 bool isModuleFileOutOfDate(off_t Size, time_t ModTime, off_t ExpectedSize,
152 time_t ExpectedModTime, AddModuleResult &Result);
153
154 bool checkSignature(ASTFileSignature Signature,
155 ASTFileSignature ExpectedSignature,
157
158 /// State used by the "visit" operation to avoid malloc traffic in
159 /// calls to visit().
160 struct VisitState {
161 explicit VisitState(unsigned N) : VisitNumber(N, 0) {
162 Stack.reserve(N);
163 }
164
165 /// The stack used when marking the imports of a particular module
166 /// as not-to-be-visited.
168
169 /// The visit number of each module file, which indicates when
170 /// this module file was last visited.
171 SmallVector<unsigned, 4> VisitNumber;
172
173 /// The next visit number to use to mark visited module files.
174 unsigned NextVisitNumber = 1;
175
176 /// The next visit state.
177 std::unique_ptr<VisitState> NextState;
178 };
179
180 /// The first visit() state in the chain.
181 std::unique_ptr<VisitState> FirstVisitState;
182
183 std::unique_ptr<VisitState> allocateVisitState();
184 void returnVisitState(std::unique_ptr<VisitState> State);
185
186public:
187 using ModuleIterator = llvm::pointee_iterator<
189 using ModuleConstIterator = llvm::pointee_iterator<
191 using ModuleReverseIterator = llvm::pointee_iterator<
193 using ModuleOffset = std::pair<uint32_t, StringRef>;
194
195 ModuleManager(FileManager &FileMgr, ModuleCache &ModCache,
196 const PCHContainerReader &PCHContainerRdr,
197 const HeaderSearch &HeaderSearchInfo);
198
199 /// Forward iterator to traverse all loaded modules.
200 ModuleIterator begin() { return Chain.begin(); }
201
202 /// Forward iterator end-point to traverse all loaded modules
203 ModuleIterator end() { return Chain.end(); }
204
205 /// Const forward iterator to traverse all loaded modules.
206 ModuleConstIterator begin() const { return Chain.begin(); }
207
208 /// Const forward iterator end-point to traverse all loaded modules
209 ModuleConstIterator end() const { return Chain.end(); }
210
211 /// Reverse iterator to traverse all loaded modules.
212 ModuleReverseIterator rbegin() { return Chain.rbegin(); }
213
214 /// Reverse iterator end-point to traverse all loaded modules.
215 ModuleReverseIterator rend() { return Chain.rend(); }
216
217 /// A range covering the PCH and preamble module files loaded.
218 llvm::iterator_range<SmallVectorImpl<ModuleFile *>::const_iterator>
219 pch_modules() const {
220 return llvm::make_range(PCHChain.begin(), PCHChain.end());
221 }
222
223 /// Returns the primary module associated with the manager, that is,
224 /// the first module loaded
225 ModuleFile &getPrimaryModule() { return *Chain[0]; }
226
227 /// Returns the primary module associated with the manager, that is,
228 /// the first module loaded.
229 ModuleFile &getPrimaryModule() const { return *Chain[0]; }
230
231 /// Returns the module associated with the given index
232 ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; }
233
234 /// Returns the module associated with the given module name.
235 ModuleFile *lookupByModuleName(StringRef ModName) const;
236
237 /// Returns the module associated with the given module file name.
239
240 /// Returns the module associated with the given module file key.
241 ModuleFile *lookup(ModuleFileKey Key) const;
242
243 /// Number of modules loaded
244 unsigned size() const { return Chain.size(); }
245
247
248 /// Attempts to create a new module and add it to the list of known
249 /// modules.
250 ///
251 /// \param FileName The file name of the module to be loaded.
252 ///
253 /// \param Type The kind of module being loaded.
254 ///
255 /// \param ImportLoc The location at which the module is imported.
256 ///
257 /// \param ImportedBy The module that is importing this module, or NULL if
258 /// this module is imported directly by the user.
259 ///
260 /// \param Generation The generation in which this module was loaded.
261 ///
262 /// \param ExpectedSize The expected size of the module file, used for
263 /// validation. This will be zero if unknown.
264 ///
265 /// \param ExpectedModTime The expected modification time of the module
266 /// file, used for validation. This will be zero if unknown.
267 ///
268 /// \param ExpectedSignature The expected signature of the module file, used
269 /// for validation. This will be zero if unknown.
270 ///
271 /// \param ReadSignature Reads the signature from an AST file without actually
272 /// loading it.
273 ///
274 /// \return The result of attempting to add the module, including a pointer
275 /// to the module file if successfully loaded.
277 SourceLocation ImportLoc, ModuleFile *ImportedBy,
278 unsigned Generation, off_t ExpectedSize,
279 time_t ExpectedModTime,
280 ASTFileSignature ExpectedSignature,
281 ASTFileSignatureReader ReadSignature);
282
283 /// Remove the modules starting from First (to the end).
285
286 /// Set the global module index.
288
289 /// Notification from the AST reader that the given module file
290 /// has been "accepted", and will not (can not) be unloaded.
292
293 /// Visit each of the modules.
294 ///
295 /// This routine visits each of the modules, starting with the
296 /// "root" modules that no other loaded modules depend on, and
297 /// proceeding to the leaf modules, visiting each module only once
298 /// during the traversal.
299 ///
300 /// This traversal is intended to support various "lookup"
301 /// operations that can find data in any of the loaded modules.
302 ///
303 /// \param Visitor A visitor function that will be invoked with each
304 /// module. The return value must be convertible to bool; when false, the
305 /// visitation continues to modules that the current module depends on. When
306 /// true, the visitation skips any modules that the current module depends on.
307 ///
308 /// \param ModuleFilesHit If non-NULL, contains the set of module files
309 /// that we know we need to visit because the global module index told us to.
310 /// Any module that is known to both the global module index and the module
311 /// manager that is *not* in this set can be skipped.
312 void visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
313 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit = nullptr);
314
315 /// View the graphviz representation of the module graph.
316 void viewGraph();
317
318 /// Creates the deduplication key for use in \c ModuleManager.
319 /// Returns an empty optional if:
320 /// * the module cache does not exist for an implicit module name,
321 /// * the module file does not exist for an explicit module name.
322 std::optional<ModuleFileKey> makeKey(const ModuleFileName &Name) const;
323
324 ModuleCache &getModuleCache() const { return ModCache; }
325};
326
327} // namespace serialization
328
329} // namespace clang
330
331#endif // LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::SourceLocation class and associated facilities.
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:54
A global index for a set of module files, providing information about the identifiers within those mo...
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:37
Deduplication key for a loaded module file in ModuleManager.
Definition Module.h:79
Identifies a module file to be loaded.
Definition Module.h:109
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
Encodes a location in the source.
The base class of the type hierarchy.
Definition TypeBase.h:1875
The result of attempting to add a new module.
InputFilesValidation getValidationStatus() const
const SmallVector< Change, 2 > & getChanges() const
void setOutOfDate(InputFilesValidation Status)
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:158
AddModuleResult addModule(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, unsigned Generation, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, ASTFileSignatureReader ReadSignature)
Attempts to create a new module and add it to the list of known modules.
ModuleFile * lookup(ModuleFileKey Key) const
Returns the module associated with the given module file key.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::iterator > ModuleIterator
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::const_iterator > ModuleConstIterator
ModuleFile & getPrimaryModule() const
Returns the primary module associated with the manager, that is, the first module loaded.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
void moduleFileAccepted(ModuleFile *MF)
Notification from the AST reader that the given module file has been "accepted", and will not (can no...
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
ModuleManager(FileManager &FileMgr, ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, const HeaderSearch &HeaderSearchInfo)
std::pair< uint32_t, StringRef > ModuleOffset
void viewGraph()
View the graphviz representation of the module graph.
ModuleConstIterator begin() const
Const forward iterator to traverse all loaded modules.
ModuleCache & getModuleCache() const
ModuleFile & operator[](unsigned Index) const
Returns the module associated with the given index.
ModuleIterator begin()
Forward iterator to traverse all loaded modules.
std::optional< ModuleFileKey > makeKey(const ModuleFileName &Name) const
Creates the deduplication key for use in ModuleManager.
void setGlobalIndex(GlobalModuleIndex *Index)
Set the global module index.
void removeModules(ModuleIterator First)
Remove the modules starting from First (to the end).
ModuleConstIterator end() const
Const forward iterator end-point to traverse all loaded modules.
ModuleIterator end()
Forward iterator end-point to traverse all loaded modules.
ModuleReverseIterator rend()
Reverse iterator end-point to traverse all loaded modules.
void visit(llvm::function_ref< bool(ModuleFile &M)> Visitor, llvm::SmallPtrSetImpl< ModuleFile * > *ModuleFilesHit=nullptr)
Visit each of the modules.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::reverse_iterator > ModuleReverseIterator
unsigned size() const
Number of modules loaded.
ModuleFile * lookupByFileName(ModuleFileName FileName) const
Returns the module associated with the given module file name.
ASTFileSignature(*)(StringRef) ASTFileSignatureReader
ModuleFile * lookupByModuleName(StringRef ModName) const
Returns the module associated with the given module name.
InputFilesValidation
Specifies the high-level result of validating input files.
Definition ModuleFile.h:137
@ NotStarted
Initial value, before the validation has been performed.
Definition ModuleFile.h:139
ModuleKind
Specifies the kind of module that has been loaded.
Definition ModuleFile.h:44
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
The signature of a module, which is a hash of the AST content.
Definition Module.h:198