xref: /openbsd-src/gnu/llvm/clang/lib/Serialization/ModuleManager.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===- ModuleManager.cpp - Module Manager ---------------------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick //  This file defines the ModuleManager class, which manages a set of loaded
10e5dd7070Spatrick //  modules for the ASTReader.
11e5dd7070Spatrick //
12e5dd7070Spatrick //===----------------------------------------------------------------------===//
13e5dd7070Spatrick 
14e5dd7070Spatrick #include "clang/Serialization/ModuleManager.h"
15e5dd7070Spatrick #include "clang/Basic/FileManager.h"
16e5dd7070Spatrick #include "clang/Basic/LLVM.h"
17e5dd7070Spatrick #include "clang/Lex/HeaderSearch.h"
18e5dd7070Spatrick #include "clang/Lex/ModuleMap.h"
19e5dd7070Spatrick #include "clang/Serialization/GlobalModuleIndex.h"
20e5dd7070Spatrick #include "clang/Serialization/InMemoryModuleCache.h"
21e5dd7070Spatrick #include "clang/Serialization/ModuleFile.h"
22e5dd7070Spatrick #include "clang/Serialization/PCHContainerOperations.h"
23e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
24e5dd7070Spatrick #include "llvm/ADT/SetVector.h"
25e5dd7070Spatrick #include "llvm/ADT/SmallPtrSet.h"
26e5dd7070Spatrick #include "llvm/ADT/SmallVector.h"
27e5dd7070Spatrick #include "llvm/ADT/StringRef.h"
28e5dd7070Spatrick #include "llvm/ADT/iterator.h"
29e5dd7070Spatrick #include "llvm/Support/Chrono.h"
30e5dd7070Spatrick #include "llvm/Support/DOTGraphTraits.h"
31e5dd7070Spatrick #include "llvm/Support/ErrorOr.h"
32e5dd7070Spatrick #include "llvm/Support/GraphWriter.h"
33e5dd7070Spatrick #include "llvm/Support/MemoryBuffer.h"
34e5dd7070Spatrick #include "llvm/Support/VirtualFileSystem.h"
35e5dd7070Spatrick #include <algorithm>
36e5dd7070Spatrick #include <cassert>
37e5dd7070Spatrick #include <memory>
38e5dd7070Spatrick #include <string>
39e5dd7070Spatrick #include <system_error>
40e5dd7070Spatrick 
41e5dd7070Spatrick using namespace clang;
42e5dd7070Spatrick using namespace serialization;
43e5dd7070Spatrick 
lookupByFileName(StringRef Name) const44e5dd7070Spatrick ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
45e5dd7070Spatrick   auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
46e5dd7070Spatrick                                /*CacheFailure=*/false);
47e5dd7070Spatrick   if (Entry)
48e5dd7070Spatrick     return lookup(*Entry);
49e5dd7070Spatrick 
50e5dd7070Spatrick   return nullptr;
51e5dd7070Spatrick }
52e5dd7070Spatrick 
lookupByModuleName(StringRef Name) const53e5dd7070Spatrick ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
54e5dd7070Spatrick   if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
55e5dd7070Spatrick     if (const FileEntry *File = Mod->getASTFile())
56e5dd7070Spatrick       return lookup(File);
57e5dd7070Spatrick 
58e5dd7070Spatrick   return nullptr;
59e5dd7070Spatrick }
60e5dd7070Spatrick 
lookup(const FileEntry * File) const61e5dd7070Spatrick ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
62e5dd7070Spatrick   auto Known = Modules.find(File);
63e5dd7070Spatrick   if (Known == Modules.end())
64e5dd7070Spatrick     return nullptr;
65e5dd7070Spatrick 
66e5dd7070Spatrick   return Known->second;
67e5dd7070Spatrick }
68e5dd7070Spatrick 
69e5dd7070Spatrick std::unique_ptr<llvm::MemoryBuffer>
lookupBuffer(StringRef Name)70e5dd7070Spatrick ModuleManager::lookupBuffer(StringRef Name) {
71e5dd7070Spatrick   auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
72e5dd7070Spatrick                                /*CacheFailure=*/false);
73e5dd7070Spatrick   if (!Entry)
74e5dd7070Spatrick     return nullptr;
75e5dd7070Spatrick   return std::move(InMemoryBuffers[*Entry]);
76e5dd7070Spatrick }
77e5dd7070Spatrick 
checkSignature(ASTFileSignature Signature,ASTFileSignature ExpectedSignature,std::string & ErrorStr)78e5dd7070Spatrick static bool checkSignature(ASTFileSignature Signature,
79e5dd7070Spatrick                            ASTFileSignature ExpectedSignature,
80e5dd7070Spatrick                            std::string &ErrorStr) {
81e5dd7070Spatrick   if (!ExpectedSignature || Signature == ExpectedSignature)
82e5dd7070Spatrick     return false;
83e5dd7070Spatrick 
84e5dd7070Spatrick   ErrorStr =
85e5dd7070Spatrick       Signature ? "signature mismatch" : "could not read module signature";
86e5dd7070Spatrick   return true;
87e5dd7070Spatrick }
88e5dd7070Spatrick 
updateModuleImports(ModuleFile & MF,ModuleFile * ImportedBy,SourceLocation ImportLoc)89e5dd7070Spatrick static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
90e5dd7070Spatrick                                 SourceLocation ImportLoc) {
91e5dd7070Spatrick   if (ImportedBy) {
92e5dd7070Spatrick     MF.ImportedBy.insert(ImportedBy);
93e5dd7070Spatrick     ImportedBy->Imports.insert(&MF);
94e5dd7070Spatrick   } else {
95e5dd7070Spatrick     if (!MF.DirectlyImported)
96e5dd7070Spatrick       MF.ImportLoc = ImportLoc;
97e5dd7070Spatrick 
98e5dd7070Spatrick     MF.DirectlyImported = true;
99e5dd7070Spatrick   }
100e5dd7070Spatrick }
101e5dd7070Spatrick 
102e5dd7070Spatrick ModuleManager::AddModuleResult
addModule(StringRef FileName,ModuleKind Type,SourceLocation ImportLoc,ModuleFile * ImportedBy,unsigned Generation,off_t ExpectedSize,time_t ExpectedModTime,ASTFileSignature ExpectedSignature,ASTFileSignatureReader ReadSignature,ModuleFile * & Module,std::string & ErrorStr)103e5dd7070Spatrick ModuleManager::addModule(StringRef FileName, ModuleKind Type,
104e5dd7070Spatrick                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
105e5dd7070Spatrick                          unsigned Generation,
106e5dd7070Spatrick                          off_t ExpectedSize, time_t ExpectedModTime,
107e5dd7070Spatrick                          ASTFileSignature ExpectedSignature,
108e5dd7070Spatrick                          ASTFileSignatureReader ReadSignature,
109e5dd7070Spatrick                          ModuleFile *&Module,
110e5dd7070Spatrick                          std::string &ErrorStr) {
111e5dd7070Spatrick   Module = nullptr;
112e5dd7070Spatrick 
113e5dd7070Spatrick   // Look for the file entry. This only fails if the expected size or
114e5dd7070Spatrick   // modification time differ.
115a9ac8606Spatrick   OptionalFileEntryRefDegradesToFileEntryPtr Entry;
116e5dd7070Spatrick   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
117e5dd7070Spatrick     // If we're not expecting to pull this file out of the module cache, it
118e5dd7070Spatrick     // might have a different mtime due to being moved across filesystems in
119e5dd7070Spatrick     // a distributed build. The size must still match, though. (As must the
120e5dd7070Spatrick     // contents, but we can't check that.)
121e5dd7070Spatrick     ExpectedModTime = 0;
122e5dd7070Spatrick   }
123e5dd7070Spatrick   // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule
124e5dd7070Spatrick   // when using an ASTFileSignature.
125e5dd7070Spatrick   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
126e5dd7070Spatrick     ErrorStr = "module file out of date";
127e5dd7070Spatrick     return OutOfDate;
128e5dd7070Spatrick   }
129e5dd7070Spatrick 
130e5dd7070Spatrick   if (!Entry && FileName != "-") {
131e5dd7070Spatrick     ErrorStr = "module file not found";
132e5dd7070Spatrick     return Missing;
133e5dd7070Spatrick   }
134e5dd7070Spatrick 
135a9ac8606Spatrick   // The ModuleManager's use of FileEntry nodes as the keys for its map of
136a9ac8606Spatrick   // loaded modules is less than ideal. Uniqueness for FileEntry nodes is
137a9ac8606Spatrick   // maintained by FileManager, which in turn uses inode numbers on hosts
138a9ac8606Spatrick   // that support that. When coupled with the module cache's proclivity for
139a9ac8606Spatrick   // turning over and deleting stale PCMs, this means entries for different
140a9ac8606Spatrick   // module files can wind up reusing the same underlying inode. When this
141a9ac8606Spatrick   // happens, subsequent accesses to the Modules map will disagree on the
142a9ac8606Spatrick   // ModuleFile associated with a given file. In general, it is not sufficient
143a9ac8606Spatrick   // to resolve this conundrum with a type like FileEntryRef that stores the
144a9ac8606Spatrick   // name of the FileEntry node on first access because of path canonicalization
145a9ac8606Spatrick   // issues. However, the paths constructed for implicit module builds are
146a9ac8606Spatrick   // fully under Clang's control. We *can*, therefore, rely on their structure
147a9ac8606Spatrick   // being consistent across operating systems and across subsequent accesses
148a9ac8606Spatrick   // to the Modules map.
149a9ac8606Spatrick   auto implicitModuleNamesMatch = [](ModuleKind Kind, const ModuleFile *MF,
150a9ac8606Spatrick                                      const FileEntry *Entry) -> bool {
151a9ac8606Spatrick     if (Kind != MK_ImplicitModule)
152a9ac8606Spatrick       return true;
153a9ac8606Spatrick     return Entry->getName() == MF->FileName;
154a9ac8606Spatrick   };
155a9ac8606Spatrick 
156e5dd7070Spatrick   // Check whether we already loaded this module, before
157e5dd7070Spatrick   if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
158a9ac8606Spatrick     if (implicitModuleNamesMatch(Type, ModuleEntry, Entry)) {
159e5dd7070Spatrick       // Check the stored signature.
160e5dd7070Spatrick       if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
161e5dd7070Spatrick         return OutOfDate;
162e5dd7070Spatrick 
163e5dd7070Spatrick       Module = ModuleEntry;
164e5dd7070Spatrick       updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
165e5dd7070Spatrick       return AlreadyLoaded;
166e5dd7070Spatrick     }
167a9ac8606Spatrick   }
168e5dd7070Spatrick 
169e5dd7070Spatrick   // Allocate a new module.
170e5dd7070Spatrick   auto NewModule = std::make_unique<ModuleFile>(Type, Generation);
171e5dd7070Spatrick   NewModule->Index = Chain.size();
172e5dd7070Spatrick   NewModule->FileName = FileName.str();
173e5dd7070Spatrick   NewModule->File = Entry;
174e5dd7070Spatrick   NewModule->ImportLoc = ImportLoc;
175e5dd7070Spatrick   NewModule->InputFilesValidationTimestamp = 0;
176e5dd7070Spatrick 
177e5dd7070Spatrick   if (NewModule->Kind == MK_ImplicitModule) {
178e5dd7070Spatrick     std::string TimestampFilename = NewModule->getTimestampFilename();
179e5dd7070Spatrick     llvm::vfs::Status Status;
180e5dd7070Spatrick     // A cached stat value would be fine as well.
181e5dd7070Spatrick     if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
182e5dd7070Spatrick       NewModule->InputFilesValidationTimestamp =
183e5dd7070Spatrick           llvm::sys::toTimeT(Status.getLastModificationTime());
184e5dd7070Spatrick   }
185e5dd7070Spatrick 
186e5dd7070Spatrick   // Load the contents of the module
187e5dd7070Spatrick   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
188e5dd7070Spatrick     // The buffer was already provided for us.
189e5dd7070Spatrick     NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer));
190e5dd7070Spatrick     // Since the cached buffer is reused, it is safe to close the file
191e5dd7070Spatrick     // descriptor that was opened while stat()ing the PCM in
192e5dd7070Spatrick     // lookupModuleFile() above, it won't be needed any longer.
193e5dd7070Spatrick     Entry->closeFile();
194e5dd7070Spatrick   } else if (llvm::MemoryBuffer *Buffer =
195e5dd7070Spatrick                  getModuleCache().lookupPCM(FileName)) {
196e5dd7070Spatrick     NewModule->Buffer = Buffer;
197e5dd7070Spatrick     // As above, the file descriptor is no longer needed.
198e5dd7070Spatrick     Entry->closeFile();
199e5dd7070Spatrick   } else if (getModuleCache().shouldBuildPCM(FileName)) {
200e5dd7070Spatrick     // Report that the module is out of date, since we tried (and failed) to
201e5dd7070Spatrick     // import it earlier.
202e5dd7070Spatrick     Entry->closeFile();
203e5dd7070Spatrick     return OutOfDate;
204e5dd7070Spatrick   } else {
205e5dd7070Spatrick     // Open the AST file.
206e5dd7070Spatrick     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
207e5dd7070Spatrick     if (FileName == "-") {
208e5dd7070Spatrick       Buf = llvm::MemoryBuffer::getSTDIN();
209e5dd7070Spatrick     } else {
210e5dd7070Spatrick       // Get a buffer of the file and close the file descriptor when done.
211ec727ea7Spatrick       // The file is volatile because in a parallel build we expect multiple
212ec727ea7Spatrick       // compiler processes to use the same module file rebuilding it if needed.
213ec727ea7Spatrick       //
214ec727ea7Spatrick       // RequiresNullTerminator is false because module files don't need it, and
215ec727ea7Spatrick       // this allows the file to still be mmapped.
216ec727ea7Spatrick       Buf = FileMgr.getBufferForFile(NewModule->File,
217ec727ea7Spatrick                                      /*IsVolatile=*/true,
218ec727ea7Spatrick                                      /*RequiresNullTerminator=*/false);
219e5dd7070Spatrick     }
220e5dd7070Spatrick 
221e5dd7070Spatrick     if (!Buf) {
222e5dd7070Spatrick       ErrorStr = Buf.getError().message();
223e5dd7070Spatrick       return Missing;
224e5dd7070Spatrick     }
225e5dd7070Spatrick 
226e5dd7070Spatrick     NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf));
227e5dd7070Spatrick   }
228e5dd7070Spatrick 
229e5dd7070Spatrick   // Initialize the stream.
230e5dd7070Spatrick   NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
231e5dd7070Spatrick 
232e5dd7070Spatrick   // Read the signature eagerly now so that we can check it.  Avoid calling
233e5dd7070Spatrick   // ReadSignature unless there's something to check though.
234e5dd7070Spatrick   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
235e5dd7070Spatrick                                           ExpectedSignature, ErrorStr))
236e5dd7070Spatrick     return OutOfDate;
237e5dd7070Spatrick 
238e5dd7070Spatrick   // We're keeping this module.  Store it everywhere.
239e5dd7070Spatrick   Module = Modules[Entry] = NewModule.get();
240e5dd7070Spatrick 
241e5dd7070Spatrick   updateModuleImports(*NewModule, ImportedBy, ImportLoc);
242e5dd7070Spatrick 
243e5dd7070Spatrick   if (!NewModule->isModule())
244e5dd7070Spatrick     PCHChain.push_back(NewModule.get());
245e5dd7070Spatrick   if (!ImportedBy)
246e5dd7070Spatrick     Roots.push_back(NewModule.get());
247e5dd7070Spatrick 
248e5dd7070Spatrick   Chain.push_back(std::move(NewModule));
249e5dd7070Spatrick   return NewlyLoaded;
250e5dd7070Spatrick }
251e5dd7070Spatrick 
removeModules(ModuleIterator First)252*12c85518Srobert void ModuleManager::removeModules(ModuleIterator First) {
253e5dd7070Spatrick   auto Last = end();
254e5dd7070Spatrick   if (First == Last)
255e5dd7070Spatrick     return;
256e5dd7070Spatrick 
257e5dd7070Spatrick   // Explicitly clear VisitOrder since we might not notice it is stale.
258e5dd7070Spatrick   VisitOrder.clear();
259e5dd7070Spatrick 
260e5dd7070Spatrick   // Collect the set of module file pointers that we'll be removing.
261e5dd7070Spatrick   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
262e5dd7070Spatrick       (llvm::pointer_iterator<ModuleIterator>(First)),
263e5dd7070Spatrick       (llvm::pointer_iterator<ModuleIterator>(Last)));
264e5dd7070Spatrick 
265e5dd7070Spatrick   auto IsVictim = [&](ModuleFile *MF) {
266e5dd7070Spatrick     return victimSet.count(MF);
267e5dd7070Spatrick   };
268e5dd7070Spatrick   // Remove any references to the now-destroyed modules.
269e5dd7070Spatrick   for (auto I = begin(); I != First; ++I) {
270e5dd7070Spatrick     I->Imports.remove_if(IsVictim);
271e5dd7070Spatrick     I->ImportedBy.remove_if(IsVictim);
272e5dd7070Spatrick   }
273*12c85518Srobert   llvm::erase_if(Roots, IsVictim);
274e5dd7070Spatrick 
275e5dd7070Spatrick   // Remove the modules from the PCH chain.
276e5dd7070Spatrick   for (auto I = First; I != Last; ++I) {
277e5dd7070Spatrick     if (!I->isModule()) {
278e5dd7070Spatrick       PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
279e5dd7070Spatrick       break;
280e5dd7070Spatrick     }
281e5dd7070Spatrick   }
282e5dd7070Spatrick 
283*12c85518Srobert   // Delete the modules.
284*12c85518Srobert   for (ModuleIterator victim = First; victim != Last; ++victim)
285e5dd7070Spatrick     Modules.erase(victim->File);
286e5dd7070Spatrick 
287e5dd7070Spatrick   Chain.erase(Chain.begin() + (First - begin()), Chain.end());
288e5dd7070Spatrick }
289e5dd7070Spatrick 
290e5dd7070Spatrick void
addInMemoryBuffer(StringRef FileName,std::unique_ptr<llvm::MemoryBuffer> Buffer)291e5dd7070Spatrick ModuleManager::addInMemoryBuffer(StringRef FileName,
292e5dd7070Spatrick                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
293e5dd7070Spatrick   const FileEntry *Entry =
294e5dd7070Spatrick       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
295e5dd7070Spatrick   InMemoryBuffers[Entry] = std::move(Buffer);
296e5dd7070Spatrick }
297e5dd7070Spatrick 
allocateVisitState()298*12c85518Srobert std::unique_ptr<ModuleManager::VisitState> ModuleManager::allocateVisitState() {
299e5dd7070Spatrick   // Fast path: if we have a cached state, use it.
300e5dd7070Spatrick   if (FirstVisitState) {
301*12c85518Srobert     auto Result = std::move(FirstVisitState);
302*12c85518Srobert     FirstVisitState = std::move(Result->NextState);
303e5dd7070Spatrick     return Result;
304e5dd7070Spatrick   }
305e5dd7070Spatrick 
306e5dd7070Spatrick   // Allocate and return a new state.
307*12c85518Srobert   return std::make_unique<VisitState>(size());
308e5dd7070Spatrick }
309e5dd7070Spatrick 
returnVisitState(std::unique_ptr<VisitState> State)310*12c85518Srobert void ModuleManager::returnVisitState(std::unique_ptr<VisitState> State) {
311e5dd7070Spatrick   assert(State->NextState == nullptr && "Visited state is in list?");
312*12c85518Srobert   State->NextState = std::move(FirstVisitState);
313*12c85518Srobert   FirstVisitState = std::move(State);
314e5dd7070Spatrick }
315e5dd7070Spatrick 
setGlobalIndex(GlobalModuleIndex * Index)316e5dd7070Spatrick void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
317e5dd7070Spatrick   GlobalIndex = Index;
318e5dd7070Spatrick   if (!GlobalIndex) {
319e5dd7070Spatrick     ModulesInCommonWithGlobalIndex.clear();
320e5dd7070Spatrick     return;
321e5dd7070Spatrick   }
322e5dd7070Spatrick 
323e5dd7070Spatrick   // Notify the global module index about all of the modules we've already
324e5dd7070Spatrick   // loaded.
325e5dd7070Spatrick   for (ModuleFile &M : *this)
326e5dd7070Spatrick     if (!GlobalIndex->loadedModuleFile(&M))
327e5dd7070Spatrick       ModulesInCommonWithGlobalIndex.push_back(&M);
328e5dd7070Spatrick }
329e5dd7070Spatrick 
moduleFileAccepted(ModuleFile * MF)330e5dd7070Spatrick void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
331e5dd7070Spatrick   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
332e5dd7070Spatrick     return;
333e5dd7070Spatrick 
334e5dd7070Spatrick   ModulesInCommonWithGlobalIndex.push_back(MF);
335e5dd7070Spatrick }
336e5dd7070Spatrick 
ModuleManager(FileManager & FileMgr,InMemoryModuleCache & ModuleCache,const PCHContainerReader & PCHContainerRdr,const HeaderSearch & HeaderSearchInfo)337e5dd7070Spatrick ModuleManager::ModuleManager(FileManager &FileMgr,
338e5dd7070Spatrick                              InMemoryModuleCache &ModuleCache,
339e5dd7070Spatrick                              const PCHContainerReader &PCHContainerRdr,
340e5dd7070Spatrick                              const HeaderSearch &HeaderSearchInfo)
341e5dd7070Spatrick     : FileMgr(FileMgr), ModuleCache(&ModuleCache),
342e5dd7070Spatrick       PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
343e5dd7070Spatrick 
visit(llvm::function_ref<bool (ModuleFile & M)> Visitor,llvm::SmallPtrSetImpl<ModuleFile * > * ModuleFilesHit)344e5dd7070Spatrick void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
345e5dd7070Spatrick                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
346e5dd7070Spatrick   // If the visitation order vector is the wrong size, recompute the order.
347e5dd7070Spatrick   if (VisitOrder.size() != Chain.size()) {
348e5dd7070Spatrick     unsigned N = size();
349e5dd7070Spatrick     VisitOrder.clear();
350e5dd7070Spatrick     VisitOrder.reserve(N);
351e5dd7070Spatrick 
352e5dd7070Spatrick     // Record the number of incoming edges for each module. When we
353e5dd7070Spatrick     // encounter a module with no incoming edges, push it into the queue
354e5dd7070Spatrick     // to seed the queue.
355e5dd7070Spatrick     SmallVector<ModuleFile *, 4> Queue;
356e5dd7070Spatrick     Queue.reserve(N);
357e5dd7070Spatrick     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
358e5dd7070Spatrick     UnusedIncomingEdges.resize(size());
359e5dd7070Spatrick     for (ModuleFile &M : llvm::reverse(*this)) {
360e5dd7070Spatrick       unsigned Size = M.ImportedBy.size();
361e5dd7070Spatrick       UnusedIncomingEdges[M.Index] = Size;
362e5dd7070Spatrick       if (!Size)
363e5dd7070Spatrick         Queue.push_back(&M);
364e5dd7070Spatrick     }
365e5dd7070Spatrick 
366e5dd7070Spatrick     // Traverse the graph, making sure to visit a module before visiting any
367e5dd7070Spatrick     // of its dependencies.
368e5dd7070Spatrick     while (!Queue.empty()) {
369e5dd7070Spatrick       ModuleFile *CurrentModule = Queue.pop_back_val();
370e5dd7070Spatrick       VisitOrder.push_back(CurrentModule);
371e5dd7070Spatrick 
372e5dd7070Spatrick       // For any module that this module depends on, push it on the
373e5dd7070Spatrick       // stack (if it hasn't already been marked as visited).
374*12c85518Srobert       for (ModuleFile *M : llvm::reverse(CurrentModule->Imports)) {
375e5dd7070Spatrick         // Remove our current module as an impediment to visiting the
376e5dd7070Spatrick         // module we depend on. If we were the last unvisited module
377e5dd7070Spatrick         // that depends on this particular module, push it into the
378e5dd7070Spatrick         // queue to be visited.
379*12c85518Srobert         unsigned &NumUnusedEdges = UnusedIncomingEdges[M->Index];
380e5dd7070Spatrick         if (NumUnusedEdges && (--NumUnusedEdges == 0))
381*12c85518Srobert           Queue.push_back(M);
382e5dd7070Spatrick       }
383e5dd7070Spatrick     }
384e5dd7070Spatrick 
385e5dd7070Spatrick     assert(VisitOrder.size() == N && "Visitation order is wrong?");
386e5dd7070Spatrick 
387e5dd7070Spatrick     FirstVisitState = nullptr;
388e5dd7070Spatrick   }
389e5dd7070Spatrick 
390*12c85518Srobert   auto State = allocateVisitState();
391e5dd7070Spatrick   unsigned VisitNumber = State->NextVisitNumber++;
392e5dd7070Spatrick 
393e5dd7070Spatrick   // If the caller has provided us with a hit-set that came from the global
394e5dd7070Spatrick   // module index, mark every module file in common with the global module
395e5dd7070Spatrick   // index that is *not* in that set as 'visited'.
396e5dd7070Spatrick   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
397e5dd7070Spatrick     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
398e5dd7070Spatrick     {
399e5dd7070Spatrick       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
400e5dd7070Spatrick       if (!ModuleFilesHit->count(M))
401e5dd7070Spatrick         State->VisitNumber[M->Index] = VisitNumber;
402e5dd7070Spatrick     }
403e5dd7070Spatrick   }
404e5dd7070Spatrick 
405e5dd7070Spatrick   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
406e5dd7070Spatrick     ModuleFile *CurrentModule = VisitOrder[I];
407e5dd7070Spatrick     // Should we skip this module file?
408e5dd7070Spatrick     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
409e5dd7070Spatrick       continue;
410e5dd7070Spatrick 
411e5dd7070Spatrick     // Visit the module.
412e5dd7070Spatrick     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
413e5dd7070Spatrick     State->VisitNumber[CurrentModule->Index] = VisitNumber;
414e5dd7070Spatrick     if (!Visitor(*CurrentModule))
415e5dd7070Spatrick       continue;
416e5dd7070Spatrick 
417e5dd7070Spatrick     // The visitor has requested that cut off visitation of any
418e5dd7070Spatrick     // module that the current module depends on. To indicate this
419e5dd7070Spatrick     // behavior, we mark all of the reachable modules as having been visited.
420e5dd7070Spatrick     ModuleFile *NextModule = CurrentModule;
421e5dd7070Spatrick     do {
422e5dd7070Spatrick       // For any module that this module depends on, push it on the
423e5dd7070Spatrick       // stack (if it hasn't already been marked as visited).
424e5dd7070Spatrick       for (llvm::SetVector<ModuleFile *>::iterator
425e5dd7070Spatrick              M = NextModule->Imports.begin(),
426e5dd7070Spatrick              MEnd = NextModule->Imports.end();
427e5dd7070Spatrick            M != MEnd; ++M) {
428e5dd7070Spatrick         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
429e5dd7070Spatrick           State->Stack.push_back(*M);
430e5dd7070Spatrick           State->VisitNumber[(*M)->Index] = VisitNumber;
431e5dd7070Spatrick         }
432e5dd7070Spatrick       }
433e5dd7070Spatrick 
434e5dd7070Spatrick       if (State->Stack.empty())
435e5dd7070Spatrick         break;
436e5dd7070Spatrick 
437e5dd7070Spatrick       // Pop the next module off the stack.
438e5dd7070Spatrick       NextModule = State->Stack.pop_back_val();
439e5dd7070Spatrick     } while (true);
440e5dd7070Spatrick   }
441e5dd7070Spatrick 
442*12c85518Srobert   returnVisitState(std::move(State));
443e5dd7070Spatrick }
444e5dd7070Spatrick 
lookupModuleFile(StringRef FileName,off_t ExpectedSize,time_t ExpectedModTime,OptionalFileEntryRef & File)445a9ac8606Spatrick bool ModuleManager::lookupModuleFile(StringRef FileName, off_t ExpectedSize,
446e5dd7070Spatrick                                      time_t ExpectedModTime,
447*12c85518Srobert                                      OptionalFileEntryRef &File) {
448*12c85518Srobert   File = std::nullopt;
449a9ac8606Spatrick   if (FileName == "-")
450e5dd7070Spatrick     return false;
451e5dd7070Spatrick 
452e5dd7070Spatrick   // Open the file immediately to ensure there is no race between stat'ing and
453e5dd7070Spatrick   // opening the file.
454*12c85518Srobert   OptionalFileEntryRef FileOrErr =
455a9ac8606Spatrick       expectedToOptional(FileMgr.getFileRef(FileName, /*OpenFile=*/true,
456a9ac8606Spatrick                                             /*CacheFailure=*/false));
457a9ac8606Spatrick   if (!FileOrErr)
458e5dd7070Spatrick     return false;
459a9ac8606Spatrick 
460e5dd7070Spatrick   File = *FileOrErr;
461e5dd7070Spatrick 
462e5dd7070Spatrick   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
463e5dd7070Spatrick       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
464e5dd7070Spatrick     // Do not destroy File, as it may be referenced. If we need to rebuild it,
465e5dd7070Spatrick     // it will be destroyed by removeModules.
466e5dd7070Spatrick     return true;
467e5dd7070Spatrick 
468e5dd7070Spatrick   return false;
469e5dd7070Spatrick }
470e5dd7070Spatrick 
471e5dd7070Spatrick #ifndef NDEBUG
472e5dd7070Spatrick namespace llvm {
473e5dd7070Spatrick 
474e5dd7070Spatrick   template<>
475e5dd7070Spatrick   struct GraphTraits<ModuleManager> {
476e5dd7070Spatrick     using NodeRef = ModuleFile *;
477e5dd7070Spatrick     using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
478e5dd7070Spatrick     using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
479e5dd7070Spatrick 
child_beginllvm::GraphTraits480e5dd7070Spatrick     static ChildIteratorType child_begin(NodeRef Node) {
481e5dd7070Spatrick       return Node->Imports.begin();
482e5dd7070Spatrick     }
483e5dd7070Spatrick 
child_endllvm::GraphTraits484e5dd7070Spatrick     static ChildIteratorType child_end(NodeRef Node) {
485e5dd7070Spatrick       return Node->Imports.end();
486e5dd7070Spatrick     }
487e5dd7070Spatrick 
nodes_beginllvm::GraphTraits488e5dd7070Spatrick     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
489e5dd7070Spatrick       return nodes_iterator(Manager.begin());
490e5dd7070Spatrick     }
491e5dd7070Spatrick 
nodes_endllvm::GraphTraits492e5dd7070Spatrick     static nodes_iterator nodes_end(const ModuleManager &Manager) {
493e5dd7070Spatrick       return nodes_iterator(Manager.end());
494e5dd7070Spatrick     }
495e5dd7070Spatrick   };
496e5dd7070Spatrick 
497e5dd7070Spatrick   template<>
498e5dd7070Spatrick   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits499e5dd7070Spatrick     explicit DOTGraphTraits(bool IsSimple = false)
500e5dd7070Spatrick         : DefaultDOTGraphTraits(IsSimple) {}
501e5dd7070Spatrick 
renderGraphFromBottomUpllvm::DOTGraphTraits502e5dd7070Spatrick     static bool renderGraphFromBottomUp() { return true; }
503e5dd7070Spatrick 
getNodeLabelllvm::DOTGraphTraits504e5dd7070Spatrick     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
505e5dd7070Spatrick       return M->ModuleName;
506e5dd7070Spatrick     }
507e5dd7070Spatrick   };
508e5dd7070Spatrick 
509e5dd7070Spatrick } // namespace llvm
510e5dd7070Spatrick 
viewGraph()511e5dd7070Spatrick void ModuleManager::viewGraph() {
512e5dd7070Spatrick   llvm::ViewGraph(*this, "Modules");
513e5dd7070Spatrick }
514e5dd7070Spatrick #endif
515