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 /// A lookup of in-memory (virtual file) buffers.
133 // FIXME: No need to key this by `FileEntry`.
134 llvm::DenseMap<const FileEntry *, std::unique_ptr<llvm::MemoryBuffer>>
135 InMemoryBuffers;
136
137 /// The visitation order.
139
140 /// The list of module files that both we and the global module index
141 /// know about.
142 ///
143 /// Either the global index or the module manager may have modules that the
144 /// other does not know about, because the global index can be out-of-date
145 /// (in which case the module manager could have modules it does not) and
146 /// this particular translation unit might not have loaded all of the modules
147 /// known to the global index.
148 SmallVector<ModuleFile *, 4> ModulesInCommonWithGlobalIndex;
149
150 /// The global module index, if one is attached.
151 ///
152 /// The global module index will actually be owned by the ASTReader; this is
153 /// just an non-owning pointer.
154 GlobalModuleIndex *GlobalIndex = nullptr;
155
156 bool isModuleFileOutOfDate(off_t Size, time_t ModTime, off_t ExpectedSize,
157 time_t ExpectedModTime, AddModuleResult &Result);
158
159 bool checkSignature(ASTFileSignature Signature,
160 ASTFileSignature ExpectedSignature,
162
163 /// State used by the "visit" operation to avoid malloc traffic in
164 /// calls to visit().
165 struct VisitState {
166 explicit VisitState(unsigned N) : VisitNumber(N, 0) {
167 Stack.reserve(N);
168 }
169
170 /// The stack used when marking the imports of a particular module
171 /// as not-to-be-visited.
173
174 /// The visit number of each module file, which indicates when
175 /// this module file was last visited.
176 SmallVector<unsigned, 4> VisitNumber;
177
178 /// The next visit number to use to mark visited module files.
179 unsigned NextVisitNumber = 1;
180
181 /// The next visit state.
182 std::unique_ptr<VisitState> NextState;
183 };
184
185 /// The first visit() state in the chain.
186 std::unique_ptr<VisitState> FirstVisitState;
187
188 std::unique_ptr<VisitState> allocateVisitState();
189 void returnVisitState(std::unique_ptr<VisitState> State);
190
191public:
192 using ModuleIterator = llvm::pointee_iterator<
194 using ModuleConstIterator = llvm::pointee_iterator<
196 using ModuleReverseIterator = llvm::pointee_iterator<
198 using ModuleOffset = std::pair<uint32_t, StringRef>;
199
200 ModuleManager(FileManager &FileMgr, ModuleCache &ModCache,
201 const PCHContainerReader &PCHContainerRdr,
202 const HeaderSearch &HeaderSearchInfo);
203
204 /// Forward iterator to traverse all loaded modules.
205 ModuleIterator begin() { return Chain.begin(); }
206
207 /// Forward iterator end-point to traverse all loaded modules
208 ModuleIterator end() { return Chain.end(); }
209
210 /// Const forward iterator to traverse all loaded modules.
211 ModuleConstIterator begin() const { return Chain.begin(); }
212
213 /// Const forward iterator end-point to traverse all loaded modules
214 ModuleConstIterator end() const { return Chain.end(); }
215
216 /// Reverse iterator to traverse all loaded modules.
217 ModuleReverseIterator rbegin() { return Chain.rbegin(); }
218
219 /// Reverse iterator end-point to traverse all loaded modules.
220 ModuleReverseIterator rend() { return Chain.rend(); }
221
222 /// A range covering the PCH and preamble module files loaded.
223 llvm::iterator_range<SmallVectorImpl<ModuleFile *>::const_iterator>
224 pch_modules() const {
225 return llvm::make_range(PCHChain.begin(), PCHChain.end());
226 }
227
228 /// Returns the primary module associated with the manager, that is,
229 /// the first module loaded
230 ModuleFile &getPrimaryModule() { return *Chain[0]; }
231
232 /// Returns the primary module associated with the manager, that is,
233 /// the first module loaded.
234 ModuleFile &getPrimaryModule() const { return *Chain[0]; }
235
236 /// Returns the module associated with the given index
237 ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; }
238
239 /// Returns the module associated with the given module name.
240 ModuleFile *lookupByModuleName(StringRef ModName) const;
241
242 /// Returns the module associated with the given module file name.
244
245 /// Returns the module associated with the given module file key.
246 ModuleFile *lookup(ModuleFileKey Key) const;
247
248 /// Returns the in-memory (virtual file) buffer with the given name
249 std::unique_ptr<llvm::MemoryBuffer> lookupBuffer(StringRef Name, off_t &Size,
250 time_t &ModTime);
251
252 /// Number of modules loaded
253 unsigned size() const { return Chain.size(); }
254
256
257 /// Attempts to create a new module and add it to the list of known
258 /// modules.
259 ///
260 /// \param FileName The file name of the module to be loaded.
261 ///
262 /// \param Type The kind of module being loaded.
263 ///
264 /// \param ImportLoc The location at which the module is imported.
265 ///
266 /// \param ImportedBy The module that is importing this module, or NULL if
267 /// this module is imported directly by the user.
268 ///
269 /// \param Generation The generation in which this module was loaded.
270 ///
271 /// \param ExpectedSize The expected size of the module file, used for
272 /// validation. This will be zero if unknown.
273 ///
274 /// \param ExpectedModTime The expected modification time of the module
275 /// file, used for validation. This will be zero if unknown.
276 ///
277 /// \param ExpectedSignature The expected signature of the module file, used
278 /// for validation. This will be zero if unknown.
279 ///
280 /// \param ReadSignature Reads the signature from an AST file without actually
281 /// loading it.
282 ///
283 /// \return The result of attempting to add the module, including a pointer
284 /// to the module file if successfully loaded.
286 SourceLocation ImportLoc, ModuleFile *ImportedBy,
287 unsigned Generation, off_t ExpectedSize,
288 time_t ExpectedModTime,
289 ASTFileSignature ExpectedSignature,
290 ASTFileSignatureReader ReadSignature);
291
292 /// Remove the modules starting from First (to the end).
294
295 /// Add an in-memory buffer the list of known buffers
296 void addInMemoryBuffer(StringRef FileName,
297 std::unique_ptr<llvm::MemoryBuffer> Buffer);
298
299 /// Set the global module index.
301
302 /// Notification from the AST reader that the given module file
303 /// has been "accepted", and will not (can not) be unloaded.
305
306 /// Visit each of the modules.
307 ///
308 /// This routine visits each of the modules, starting with the
309 /// "root" modules that no other loaded modules depend on, and
310 /// proceeding to the leaf modules, visiting each module only once
311 /// during the traversal.
312 ///
313 /// This traversal is intended to support various "lookup"
314 /// operations that can find data in any of the loaded modules.
315 ///
316 /// \param Visitor A visitor function that will be invoked with each
317 /// module. The return value must be convertible to bool; when false, the
318 /// visitation continues to modules that the current module depends on. When
319 /// true, the visitation skips any modules that the current module depends on.
320 ///
321 /// \param ModuleFilesHit If non-NULL, contains the set of module files
322 /// that we know we need to visit because the global module index told us to.
323 /// Any module that is known to both the global module index and the module
324 /// manager that is *not* in this set can be skipped.
325 void visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
326 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit = nullptr);
327
328 /// View the graphviz representation of the module graph.
329 void viewGraph();
330
331 ModuleCache &getModuleCache() const { return ModCache; }
332};
333
334} // namespace serialization
335
336} // namespace clang
337
338#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:53
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:30
Deduplication key for a loaded module file in ModuleManager.
Definition Module.h:69
Identifies a module file to be loaded.
Definition Module.h:102
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:1866
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
std::unique_ptr< llvm::MemoryBuffer > lookupBuffer(StringRef Name, off_t &Size, time_t &ModTime)
Returns the in-memory (virtual file) buffer with the given name.
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.
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.
void addInMemoryBuffer(StringRef FileName, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Add an in-memory buffer the list of known buffers.
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:160