clang 24.0.0git
ModuleManager.cpp
Go to the documentation of this file.
1//===- ModuleManager.cpp - Module Manager ---------------------------------===//
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
16#include "clang/Basic/LLVM.h"
18#include "clang/Lex/ModuleMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SetVector.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/Support/DOTGraphTraits.h"
31#include "llvm/Support/Error.h"
32#include "llvm/Support/GraphWriter.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/VirtualFileSystem.h"
35#include <cassert>
36#include <memory>
37#include <string>
38
39using namespace clang;
40using namespace serialization;
41
42std::optional<ModuleFileKey>
44 if (unsigned SuffixLen = Name.getImplicitModuleSuffixLength()) {
45 StringRef ModuleCachePath = StringRef(Name).drop_back(SuffixLen);
46 StringRef ImplicitModuleSuffix = StringRef(Name).take_back(SuffixLen);
47 if (auto *ModuleCacheDir = ModCache.getDirectoryPtr(ModuleCachePath))
48 return ModuleFileKey(ModuleCacheDir, ImplicitModuleSuffix);
49 } else if (Name.isInMemory()) {
50 off_t Size;
51 time_t ModTime;
52 if (auto *Buf =
53 ModCache.getInMemoryModuleCache().lookupPCM(Name, Size, ModTime))
54 return ModuleFileKey(Buf);
55 } else {
56 if (auto ModuleFile = FileMgr.getOptionalFileRef(Name, /*OpenFile=*/true,
57 /*CacheFailure=*/true,
58 /*IsText=*/false))
60 }
61
62 return std::nullopt;
63}
64
66 if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
67 if (const ModuleFileName *FileName = Mod->getASTFileName())
69
70 return nullptr;
71}
72
74 std::optional<ModuleFileKey> Key = makeKey(Name);
75 return Key ? lookup(*Key) : nullptr;
76}
77
79 return Modules.lookup(Key);
80}
81
82bool ModuleManager::isModuleFileOutOfDate(off_t Size, time_t ModTime,
83 off_t ExpectedSize,
84 time_t ExpectedModTime,
86 bool OutOfDate = false;
87 if (ExpectedSize && ExpectedSize != Size) {
88 Result.Changes.push_back({Change::Size, ExpectedSize, Size});
89 OutOfDate = true;
90 }
91
92 if (ExpectedModTime && ExpectedModTime != ModTime) {
93 Result.Changes.push_back({Change::ModTime, ExpectedModTime, ModTime});
94 OutOfDate = true;
95 }
96
97 return OutOfDate;
98}
99
100bool ModuleManager::checkSignature(ASTFileSignature Signature,
101 ASTFileSignature ExpectedSignature,
103 if (!ExpectedSignature || Signature == ExpectedSignature)
104 return false;
105 Result.SignatureError =
106 Signature ? "signature mismatch" : "could not read module signature";
107 return true;
108}
109
110static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
111 SourceLocation ImportLoc) {
112 if (ImportedBy) {
113 MF.ImportedBy.insert(ImportedBy);
114 ImportedBy->Imports.insert(&MF);
115 } else {
116 if (!MF.DirectlyImported)
117 MF.ImportLoc = ImportLoc;
118
119 MF.DirectlyImported = true;
120 }
121}
122
125 ModuleFile *ImportedBy, unsigned Generation, off_t ExpectedSize,
126 time_t ExpectedModTime, ASTFileSignature ExpectedSignature,
127 ASTFileSignatureReader ReadSignature) {
129
130 uint64_t InputFilesValidationTimestamp = 0;
131 if (Type == MK_ImplicitModule)
132 InputFilesValidationTimestamp = ModCache.getModuleTimestamp(FileName);
133
134 bool IgnoreModTime = Type == MK_ExplicitModule || Type == MK_PrebuiltModule;
135 if (ImportedBy)
136 IgnoreModTime &= ImportedBy->Kind == MK_ExplicitModule ||
137 ImportedBy->Kind == MK_PrebuiltModule;
138 if (IgnoreModTime) {
139 // If neither this file nor the importer are in the module cache, this file
140 // might have a different mtime due to being moved across filesystems in
141 // a distributed build. The size must still match, though. (As must the
142 // contents, but we can't check that.)
143 ExpectedModTime = 0;
144 }
145
146 std::optional<ModuleFileKey> FileKey = makeKey(FileName);
147 if (!FileKey) {
149 return Result;
150 }
151
152 // Check whether we already loaded this module before.
153 // Note: `isModuleFileOutOfDate` and `checkSignature` are mutually exclusive
154 // in practice. If a signature is stored, it means size/mtime values have been
155 // zeroed out. If size/mtime are non-NULL, the signature is empty.
156 if (ModuleFile *ModuleEntry = lookup(*FileKey)) {
157 if (isModuleFileOutOfDate(ModuleEntry->Size, ModuleEntry->ModTime,
158 ExpectedSize, ExpectedModTime, Result)) {
159 Result.setOutOfDate(ModuleEntry->InputFilesValidationStatus);
160 return Result;
161 }
162
163 // Check the stored signature.
164 if (checkSignature(ModuleEntry->Signature, ExpectedSignature, Result)) {
165 Result.setOutOfDate(ModuleEntry->InputFilesValidationStatus);
166 return Result;
167 }
168
169 Result.Module = ModuleEntry;
170 updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
172 return Result;
173 }
174
175 // Load the contents of the module
176 off_t Size = ExpectedSize;
177 time_t ModTime = ExpectedModTime;
178 llvm::MemoryBuffer *ModuleBuffer = nullptr;
179 std::unique_ptr<llvm::MemoryBuffer> NewFileBuffer = nullptr;
180 if (llvm::MemoryBuffer *Buffer =
181 getModuleCache().getInMemoryModuleCache().lookupPCM(FileName, Size,
182 ModTime)) {
183 ModuleBuffer = Buffer;
184 } else if (getModuleCache().getInMemoryModuleCache().shouldBuildPCM(
185 FileName)) {
186 // Report that the module is out of date, since we tried (and failed) to
187 // import it earlier. No ModuleFile exists yet, so derive the validation
188 // status from the module kind being loaded.
192 return Result;
193 } else {
194 auto Buf = [&]() -> Expected<std::unique_ptr<llvm::MemoryBuffer>> {
195 assert(!FileName.isInMemory() && "In-memory module not found");
196
197 // Implicit modules live in the module cache.
198 if (FileName.getImplicitModuleSuffixLength())
199 return ModCache.read(FileName, Size, ModTime);
200
201 // Explicit modules are treated as any other compiler input file, load
202 // them via FileManager.
204 FileName == StringRef("-")
205 ? FileMgr.getSTDIN()
206 : FileMgr.getFileRef(FileName, /*OpenFile=*/true,
207 /*CacheFailure=*/true,
208 /*IsText=*/false);
209 if (!Entry)
210 return Entry.takeError();
211
212 Size = Entry->getSize();
213 ModTime = Entry->getModificationTime();
214
215 // RequiresNullTerminator is false because module files don't need it, and
216 // this allows the file to still be mmapped.
217 return llvm::errorOrToExpected(
218 FileMgr.getBufferForFile(*Entry, /*IsVolatile=*/false,
219 /*RequiresNullTerminator=*/false,
220 /*MaybeLimit=*/std::nullopt,
221 /*IsText=*/false));
222 }();
223
224 if (!Buf) {
225 Result.BufferError = llvm::toString(Buf.takeError());
227 return Result;
228 }
229
230 NewFileBuffer = std::move(*Buf);
231 ModuleBuffer = NewFileBuffer.get();
232 }
233
234 // Allocate bookkeeping for a module file not yet loaded into this reader.
235 auto NewModule = std::make_unique<ModuleFile>(Type, *FileKey, Generation);
236 NewModule->Index = Chain.size();
237 NewModule->FileName = FileName;
238 NewModule->ImportLoc = ImportLoc;
239 NewModule->InputFilesValidationTimestamp = InputFilesValidationTimestamp;
240 NewModule->Size = Size;
241 NewModule->ModTime = ModTime;
242 NewModule->Buffer = ModuleBuffer;
243 // Initialize the stream.
244 NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
245
246 // Check file properties.
247 if (isModuleFileOutOfDate(Size, ModTime, ExpectedSize, ExpectedModTime,
248 Result)) {
249 Result.setOutOfDate(NewModule->InputFilesValidationStatus);
250 return Result;
251 }
252
253 // Read the signature eagerly now so that we can check it. Avoid calling
254 // ReadSignature unless there's something to check though.
255 if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
256 ExpectedSignature, Result)) {
257 Result.setOutOfDate(NewModule->InputFilesValidationStatus);
258 return Result;
259 }
260
261 if (NewFileBuffer)
263 FileName, std::move(NewFileBuffer), Size, ModTime);
264
265 // We're keeping this module. Store it in the map.
266 Result.Module = Modules[*FileKey] = NewModule.get();
267
268 updateModuleImports(*NewModule, ImportedBy, ImportLoc);
269
270 if (!NewModule->isModule())
271 PCHChain.push_back(NewModule.get());
272 if (!ImportedBy)
273 Roots.push_back(NewModule.get());
274
275 Chain.push_back(std::move(NewModule));
277 return Result;
278}
279
281 auto Last = end();
282 if (First == Last)
283 return;
284
285 // Explicitly clear VisitOrder since we might not notice it is stale.
286 VisitOrder.clear();
287
288 // Collect the set of module file pointers that we'll be removing.
290 (llvm::pointer_iterator<ModuleIterator>(First)),
291 (llvm::pointer_iterator<ModuleIterator>(Last)));
292
293 auto IsVictim = [&](ModuleFile *MF) {
294 return victimSet.count(MF);
295 };
296 // Remove any references to the now-destroyed modules.
297 for (auto I = begin(); I != First; ++I) {
298 I->Imports.remove_if(IsVictim);
299 I->ImportedBy.remove_if(IsVictim);
300 }
301 llvm::erase_if(Roots, IsVictim);
302
303 // Remove the modules from the PCH chain.
304 for (auto I = First; I != Last; ++I) {
305 if (!I->isModule()) {
306 PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
307 break;
308 }
309 }
310
311 // Delete the modules.
312 for (ModuleIterator victim = First; victim != Last; ++victim)
313 Modules.erase(victim->FileKey);
314
315 Chain.erase(Chain.begin() + (First - begin()), Chain.end());
316}
317
318std::unique_ptr<ModuleManager::VisitState> ModuleManager::allocateVisitState() {
319 // Fast path: if we have a cached state, use it.
320 if (FirstVisitState) {
321 auto Result = std::move(FirstVisitState);
322 FirstVisitState = std::move(Result->NextState);
323 return Result;
324 }
325
326 // Allocate and return a new state.
327 return std::make_unique<VisitState>(size());
328}
329
330void ModuleManager::returnVisitState(std::unique_ptr<VisitState> State) {
331 assert(State->NextState == nullptr && "Visited state is in list?");
332 State->NextState = std::move(FirstVisitState);
333 FirstVisitState = std::move(State);
334}
335
337 GlobalIndex = Index;
338 if (!GlobalIndex) {
339 ModulesInCommonWithGlobalIndex.clear();
340 return;
341 }
342
343 // Notify the global module index about all of the modules we've already
344 // loaded.
345 for (ModuleFile &M : *this)
346 if (!GlobalIndex->loadedModuleFile(&M))
347 ModulesInCommonWithGlobalIndex.push_back(&M);
348}
349
351 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
352 return;
353
354 ModulesInCommonWithGlobalIndex.push_back(MF);
355}
356
358 const PCHContainerReader &PCHContainerRdr,
359 const HeaderSearch &HeaderSearchInfo)
360 : FileMgr(FileMgr), ModCache(ModCache), PCHContainerRdr(PCHContainerRdr),
361 HeaderSearchInfo(HeaderSearchInfo) {}
362
363void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
364 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
365 // If the visitation order vector is the wrong size, recompute the order.
366 if (VisitOrder.size() != Chain.size()) {
367 unsigned N = size();
368 VisitOrder.clear();
369 VisitOrder.reserve(N);
370
371 // Record the number of incoming edges for each module. When we
372 // encounter a module with no incoming edges, push it into the queue
373 // to seed the queue.
375 Queue.reserve(N);
376 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
377 UnusedIncomingEdges.resize(size());
378 for (ModuleFile &M : llvm::reverse(*this)) {
379 unsigned Size = M.ImportedBy.size();
380 UnusedIncomingEdges[M.Index] = Size;
381 if (!Size)
382 Queue.push_back(&M);
383 }
384
385 // Traverse the graph, making sure to visit a module before visiting any
386 // of its dependencies.
387 while (!Queue.empty()) {
388 ModuleFile *CurrentModule = Queue.pop_back_val();
389 VisitOrder.push_back(CurrentModule);
390
391 // For any module that this module depends on, push it on the
392 // stack (if it hasn't already been marked as visited).
393 for (ModuleFile *M : llvm::reverse(CurrentModule->Imports)) {
394 // Remove our current module as an impediment to visiting the
395 // module we depend on. If we were the last unvisited module
396 // that depends on this particular module, push it into the
397 // queue to be visited.
398 unsigned &NumUnusedEdges = UnusedIncomingEdges[M->Index];
399 if (NumUnusedEdges && (--NumUnusedEdges == 0))
400 Queue.push_back(M);
401 }
402 }
403
404 assert(VisitOrder.size() == N && "Visitation order is wrong?");
405
406 FirstVisitState = nullptr;
407 }
408
409 auto State = allocateVisitState();
410 unsigned VisitNumber = State->NextVisitNumber++;
411
412 // If the caller has provided us with a hit-set that came from the global
413 // module index, mark every module file in common with the global module
414 // index that is *not* in that set as 'visited'.
415 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
416 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
417 {
418 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
419 if (!ModuleFilesHit->count(M))
420 State->VisitNumber[M->Index] = VisitNumber;
421 }
422 }
423
424 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
425 ModuleFile *CurrentModule = VisitOrder[I];
426 // Should we skip this module file?
427 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
428 continue;
429
430 // Visit the module.
431 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
432 State->VisitNumber[CurrentModule->Index] = VisitNumber;
433 if (!Visitor(*CurrentModule))
434 continue;
435
436 // The visitor has requested that cut off visitation of any
437 // module that the current module depends on. To indicate this
438 // behavior, we mark all of the reachable modules as having been visited.
439 ModuleFile *NextModule = CurrentModule;
440 do {
441 // For any module that this module depends on, push it on the
442 // stack (if it hasn't already been marked as visited).
443 for (llvm::SetVector<ModuleFile *>::iterator
444 M = NextModule->Imports.begin(),
445 MEnd = NextModule->Imports.end();
446 M != MEnd; ++M) {
447 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
448 State->Stack.push_back(*M);
449 State->VisitNumber[(*M)->Index] = VisitNumber;
450 }
451 }
452
453 if (State->Stack.empty())
454 break;
455
456 // Pop the next module off the stack.
457 NextModule = State->Stack.pop_back_val();
458 } while (true);
459 }
460
461 returnVisitState(std::move(State));
462}
463
464#ifndef NDEBUG
465namespace llvm {
466
467 template<>
468 struct GraphTraits<ModuleManager> {
470 using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
471 using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
472
474 return Node->Imports.begin();
475 }
476
478 return Node->Imports.end();
479 }
480
481 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
482 return nodes_iterator(Manager.begin());
483 }
484
485 static nodes_iterator nodes_end(const ModuleManager &Manager) {
486 return nodes_iterator(Manager.end());
487 }
488 };
489
490 template<>
492 explicit DOTGraphTraits(bool IsSimple = false)
493 : DefaultDOTGraphTraits(IsSimple) {}
494
495 static bool renderGraphFromBottomUp() { return true; }
496
497 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
498 return M->ModuleName;
499 }
500 };
501
502} // namespace llvm
503
505 llvm::ViewGraph(*this, "Modules");
506}
507#endif
Defines the clang::FileManager interface and associated types.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy, SourceLocation ImportLoc)
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:57
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,...
llvm::MemoryBuffer & addPCM(llvm::StringRef Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer, off_t Size, time_t ModTime)
Store the PCM under the Filename.
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:41
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
Deduplication key for a loaded module file in ModuleManager.
Definition Module.h:79
Identifies a module file to be loaded.
Definition Module.h:109
bool isInMemory() const
Returns true iff this is an in-memory module file, false otherwise.
Definition Module.h:182
unsigned getImplicitModuleSuffixLength() const
Returns the suffix length for an implicit module name, zero otherwise.
Definition Module.h:171
Describes a module or submodule.
Definition Module.h:340
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:1879
The result of attempting to add a new module.
@ Missing
The module file is missing.
@ 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
bool DirectlyImported
Whether this module has been directly imported by the user.
Definition ModuleFile.h:244
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:555
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:280
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:171
llvm::SetVector< ModuleFile * > Imports
List of modules which this module directly imported.
Definition ModuleFile.h:558
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:174
std::string ModuleName
The name of the module.
Definition ModuleFile.h:183
Manages the set of modules loaded by an AST reader.
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
void moduleFileAccepted(ModuleFile *MF)
Notification from the AST reader that the given module file has been "accepted", and will not (can no...
ModuleManager(FileManager &FileMgr, ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, const HeaderSearch &HeaderSearchInfo)
void viewGraph()
View the graphviz representation of the module graph.
ModuleCache & getModuleCache() const
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).
ModuleIterator end()
Forward 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.
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.
@ Disabled
When the validation is disabled. For example, for a precompiled header.
Definition ModuleFile.h:141
@ 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
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:49
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:46
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:61
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
The signature of a module, which is a hash of the AST content.
Definition Module.h:198
std::string getNodeLabel(ModuleFile *M, const ModuleManager &)
static ChildIteratorType child_end(NodeRef Node)
static nodes_iterator nodes_begin(const ModuleManager &Manager)
static ChildIteratorType child_begin(NodeRef Node)
pointer_iterator< ModuleManager::ModuleConstIterator > nodes_iterator
llvm::SetVector< ModuleFile * >::const_iterator ChildIteratorType
static nodes_iterator nodes_end(const ModuleManager &Manager)