1d44252ecSDouglas Gregor //===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===//
2d44252ecSDouglas Gregor //
3d44252ecSDouglas Gregor //                     The LLVM Compiler Infrastructure
4d44252ecSDouglas Gregor //
5d44252ecSDouglas Gregor // This file is distributed under the University of Illinois Open Source
6d44252ecSDouglas Gregor // License. See LICENSE.TXT for details.
7d44252ecSDouglas Gregor //
8d44252ecSDouglas Gregor //===----------------------------------------------------------------------===//
9d44252ecSDouglas Gregor //
10d44252ecSDouglas Gregor //  This file defines the ModuleManager class, which manages a set of loaded
11d44252ecSDouglas Gregor //  modules for the ASTReader.
12d44252ecSDouglas Gregor //
13d44252ecSDouglas Gregor //===----------------------------------------------------------------------===//
149670f847SMehdi Amini #include "clang/Serialization/ModuleManager.h"
15030d7d6dSDuncan P. N. Exon Smith #include "clang/Basic/MemoryBufferCache.h"
16bb165fb0SAdrian Prantl #include "clang/Frontend/PCHContainerOperations.h"
17beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h"
187029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h"
197211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h"
20d44252ecSDouglas Gregor #include "llvm/Support/MemoryBuffer.h"
21552c169eSRafael Espindola #include "llvm/Support/Path.h"
228a8e554aSRafael Espindola #include <system_error>
23d44252ecSDouglas Gregor 
249d7c1a2aSDouglas Gregor #ifndef NDEBUG
259d7c1a2aSDouglas Gregor #include "llvm/Support/GraphWriter.h"
269d7c1a2aSDouglas Gregor #endif
279d7c1a2aSDouglas Gregor 
28d44252ecSDouglas Gregor using namespace clang;
29d44252ecSDouglas Gregor using namespace serialization;
30d44252ecSDouglas Gregor 
31*d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
32dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
33dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
34bf7fc9c5SDouglas Gregor   if (Entry)
35bf7fc9c5SDouglas Gregor     return lookup(Entry);
36bf7fc9c5SDouglas Gregor 
37a13603a2SCraig Topper   return nullptr;
38bf7fc9c5SDouglas Gregor }
39bf7fc9c5SDouglas Gregor 
40*d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
41*d30446fdSBoris Kolpackov   if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
42*d30446fdSBoris Kolpackov     if (const FileEntry *File = Mod->getASTFile())
43*d30446fdSBoris Kolpackov       return lookup(File);
44*d30446fdSBoris Kolpackov 
45*d30446fdSBoris Kolpackov   return nullptr;
46*d30446fdSBoris Kolpackov }
47*d30446fdSBoris Kolpackov 
4837a93df3SRichard Smith ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
4937a93df3SRichard Smith   auto Known = Modules.find(File);
50bf7fc9c5SDouglas Gregor   if (Known == Modules.end())
51a13603a2SCraig Topper     return nullptr;
52bf7fc9c5SDouglas Gregor 
53bf7fc9c5SDouglas Gregor   return Known->second;
54d44252ecSDouglas Gregor }
55d44252ecSDouglas Gregor 
565cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer>
575cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
58dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
59dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
605cd06f26SRafael Espindola   return std::move(InMemoryBuffers[Entry]);
61d44252ecSDouglas Gregor }
62d44252ecSDouglas Gregor 
6314afc8e7SDuncan P. N. Exon Smith static bool checkSignature(ASTFileSignature Signature,
6414afc8e7SDuncan P. N. Exon Smith                            ASTFileSignature ExpectedSignature,
6514afc8e7SDuncan P. N. Exon Smith                            std::string &ErrorStr) {
6614afc8e7SDuncan P. N. Exon Smith   if (!ExpectedSignature || Signature == ExpectedSignature)
6714afc8e7SDuncan P. N. Exon Smith     return false;
6814afc8e7SDuncan P. N. Exon Smith 
6914afc8e7SDuncan P. N. Exon Smith   ErrorStr =
7014afc8e7SDuncan P. N. Exon Smith       Signature ? "signature mismatch" : "could not read module signature";
7114afc8e7SDuncan P. N. Exon Smith   return true;
7214afc8e7SDuncan P. N. Exon Smith }
7314afc8e7SDuncan P. N. Exon Smith 
7426308a68SDuncan P. N. Exon Smith static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
7526308a68SDuncan P. N. Exon Smith                                 SourceLocation ImportLoc) {
7626308a68SDuncan P. N. Exon Smith   if (ImportedBy) {
7726308a68SDuncan P. N. Exon Smith     MF.ImportedBy.insert(ImportedBy);
7826308a68SDuncan P. N. Exon Smith     ImportedBy->Imports.insert(&MF);
7926308a68SDuncan P. N. Exon Smith   } else {
8026308a68SDuncan P. N. Exon Smith     if (!MF.DirectlyImported)
8126308a68SDuncan P. N. Exon Smith       MF.ImportLoc = ImportLoc;
8226308a68SDuncan P. N. Exon Smith 
8326308a68SDuncan P. N. Exon Smith     MF.DirectlyImported = true;
8426308a68SDuncan P. N. Exon Smith   }
8526308a68SDuncan P. N. Exon Smith }
8626308a68SDuncan P. N. Exon Smith 
877029ce1aSDouglas Gregor ModuleManager::AddModuleResult
88d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
896fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
907029ce1aSDouglas Gregor                          unsigned Generation,
917029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
92487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
9370a1b816SBen Langmuir                          ASTFileSignatureReader ReadSignature,
947029ce1aSDouglas Gregor                          ModuleFile *&Module,
957029ce1aSDouglas Gregor                          std::string &ErrorStr) {
96a13603a2SCraig Topper   Module = nullptr;
977029ce1aSDouglas Gregor 
987029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
997029ce1aSDouglas Gregor   // modification time differ.
1007029ce1aSDouglas Gregor   const FileEntry *Entry;
10111f2a477SManman Ren   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
1025b390756SRichard Smith     // If we're not expecting to pull this file out of the module cache, it
1035b390756SRichard Smith     // might have a different mtime due to being moved across filesystems in
1045b390756SRichard Smith     // a distributed build. The size must still match, though. (As must the
1055b390756SRichard Smith     // contents, but we can't check that.)
1065b390756SRichard Smith     ExpectedModTime = 0;
1075b390756SRichard Smith   }
108c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
109c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
1107029ce1aSDouglas Gregor     return OutOfDate;
111c27d0d5eSEli Friedman   }
1127029ce1aSDouglas Gregor 
113d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
114c27d0d5eSEli Friedman     ErrorStr = "module file not found";
1157029ce1aSDouglas Gregor     return Missing;
116d44252ecSDouglas Gregor   }
117d44252ecSDouglas Gregor 
118d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
11926308a68SDuncan P. N. Exon Smith   if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
12026308a68SDuncan P. N. Exon Smith     // Check the stored signature.
12126308a68SDuncan P. N. Exon Smith     if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
12226308a68SDuncan P. N. Exon Smith       return OutOfDate;
12326308a68SDuncan P. N. Exon Smith 
12426308a68SDuncan P. N. Exon Smith     Module = ModuleEntry;
12526308a68SDuncan P. N. Exon Smith     updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
12626308a68SDuncan P. N. Exon Smith     return AlreadyLoaded;
12726308a68SDuncan P. N. Exon Smith   }
12826308a68SDuncan P. N. Exon Smith 
129d44252ecSDouglas Gregor   // Allocate a new module.
13026308a68SDuncan P. N. Exon Smith   auto NewModule = llvm::make_unique<ModuleFile>(Type, Generation);
131a897f7cdSDuncan P. N. Exon Smith   NewModule->Index = Chain.size();
132a897f7cdSDuncan P. N. Exon Smith   NewModule->FileName = FileName.str();
133a897f7cdSDuncan P. N. Exon Smith   NewModule->File = Entry;
134a897f7cdSDuncan P. N. Exon Smith   NewModule->ImportLoc = ImportLoc;
135a897f7cdSDuncan P. N. Exon Smith   NewModule->InputFilesValidationTimestamp = 0;
136d44252ecSDouglas Gregor 
137a897f7cdSDuncan P. N. Exon Smith   if (NewModule->Kind == MK_ImplicitModule) {
138a897f7cdSDuncan P. N. Exon Smith     std::string TimestampFilename = NewModule->getTimestampFilename();
139c8130a74SBen Langmuir     vfs::Status Status;
140f430da4dSDmitri Gribenko     // A cached stat value would be fine as well.
141f430da4dSDmitri Gribenko     if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
142a897f7cdSDuncan P. N. Exon Smith       NewModule->InputFilesValidationTimestamp =
143ac71c8e2SPavel Labath           llvm::sys::toTimeT(Status.getLastModificationTime());
144f430da4dSDmitri Gribenko   }
145f430da4dSDmitri Gribenko 
146d44252ecSDouglas Gregor   // Load the contents of the module
1475cd06f26SRafael Espindola   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
148d44252ecSDouglas Gregor     // The buffer was already provided for us.
149030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(Buffer));
150030d7d6dSDuncan P. N. Exon Smith   } else if (llvm::MemoryBuffer *Buffer = PCMCache->lookupBuffer(FileName)) {
151030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = Buffer;
152d44252ecSDouglas Gregor   } else {
153d44252ecSDouglas Gregor     // Open the AST file.
15426308a68SDuncan P. N. Exon Smith     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
155d44252ecSDouglas Gregor     if (FileName == "-") {
156a885796dSBenjamin Kramer       Buf = llvm::MemoryBuffer::getSTDIN();
1579801b253SBen Langmuir     } else {
1589801b253SBen Langmuir       // Leave the FileEntry open so if it gets read again by another
1599801b253SBen Langmuir       // ModuleManager it must be the same underlying file.
1609801b253SBen Langmuir       // FIXME: Because FileManager::getFile() doesn't guarantee that it will
1619801b253SBen Langmuir       // give us an open file, this may not be 100% reliable.
162a897f7cdSDuncan P. N. Exon Smith       Buf = FileMgr.getBufferForFile(NewModule->File,
163a885796dSBenjamin Kramer                                      /*IsVolatile=*/false,
164a885796dSBenjamin Kramer                                      /*ShouldClose=*/false);
1659801b253SBen Langmuir     }
166d44252ecSDouglas Gregor 
167a885796dSBenjamin Kramer     if (!Buf) {
168a885796dSBenjamin Kramer       ErrorStr = Buf.getError().message();
1697029ce1aSDouglas Gregor       return Missing;
170d44252ecSDouglas Gregor     }
171d44252ecSDouglas Gregor 
172030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(*Buf));
173a885796dSBenjamin Kramer   }
174a885796dSBenjamin Kramer 
175bb165fb0SAdrian Prantl   // Initialize the stream.
176a897f7cdSDuncan P. N. Exon Smith   NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
177487ea14aSBen Langmuir 
178688b69adSDuncan P. N. Exon Smith   // Read the signature eagerly now so that we can check it.  Avoid calling
179688b69adSDuncan P. N. Exon Smith   // ReadSignature unless there's something to check though.
180688b69adSDuncan P. N. Exon Smith   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
181030d7d6dSDuncan P. N. Exon Smith                                           ExpectedSignature, ErrorStr)) {
182030d7d6dSDuncan P. N. Exon Smith     // Try to remove the buffer.  If it can't be removed, then it was already
183030d7d6dSDuncan P. N. Exon Smith     // validated by this process.
184030d7d6dSDuncan P. N. Exon Smith     if (!PCMCache->tryToRemoveBuffer(NewModule->FileName))
185030d7d6dSDuncan P. N. Exon Smith       FileMgr.invalidateCache(NewModule->File);
186ed982584SBen Langmuir     return OutOfDate;
187030d7d6dSDuncan P. N. Exon Smith   }
188a897f7cdSDuncan P. N. Exon Smith 
18926308a68SDuncan P. N. Exon Smith   // We're keeping this module.  Store it everywhere.
19026308a68SDuncan P. N. Exon Smith   Module = Modules[Entry] = NewModule.get();
191d44252ecSDouglas Gregor 
19226308a68SDuncan P. N. Exon Smith   updateModuleImports(*NewModule, ImportedBy, ImportLoc);
1936fb03aeaSDouglas Gregor 
19426308a68SDuncan P. N. Exon Smith   if (!NewModule->isModule())
19526308a68SDuncan P. N. Exon Smith     PCHChain.push_back(NewModule.get());
19626308a68SDuncan P. N. Exon Smith   if (!ImportedBy)
19726308a68SDuncan P. N. Exon Smith     Roots.push_back(NewModule.get());
1983b99db55SRichard Smith 
199a897f7cdSDuncan P. N. Exon Smith   Chain.push_back(std::move(NewModule));
2003b99db55SRichard Smith   return NewlyLoaded;
201d44252ecSDouglas Gregor }
202d44252ecSDouglas Gregor 
2039801b253SBen Langmuir void ModuleManager::removeModules(
2048e6bc197SDuncan P. N. Exon Smith     ModuleIterator First,
2059801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
2067029ce1aSDouglas Gregor     ModuleMap *modMap) {
2078e6bc197SDuncan P. N. Exon Smith   auto Last = end();
2088e6bc197SDuncan P. N. Exon Smith   if (First == Last)
209188dbef2SDouglas Gregor     return;
210188dbef2SDouglas Gregor 
2118e6bc197SDuncan P. N. Exon Smith 
212a50dbb20SBen Langmuir   // Explicitly clear VisitOrder since we might not notice it is stale.
213a50dbb20SBen Langmuir   VisitOrder.clear();
214a50dbb20SBen Langmuir 
215188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
21696a06e0eSDuncan P. N. Exon Smith   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
2178e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(First)),
2188e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(Last)));
219188dbef2SDouglas Gregor 
2209eff8b14SManuel Klimek   auto IsVictim = [&](ModuleFile *MF) {
2219eff8b14SManuel Klimek     return victimSet.count(MF);
2229eff8b14SManuel Klimek   };
223188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
224073ec350SDuncan P. N. Exon Smith   for (auto I = begin(); I != First; ++I) {
225073ec350SDuncan P. N. Exon Smith     I->Imports.remove_if(IsVictim);
2268e6bc197SDuncan P. N. Exon Smith     I->ImportedBy.remove_if(IsVictim);
227073ec350SDuncan P. N. Exon Smith   }
2289eff8b14SManuel Klimek   Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
2299eff8b14SManuel Klimek               Roots.end());
230188dbef2SDouglas Gregor 
23116fe4d17SRichard Smith   // Remove the modules from the PCH chain.
2328e6bc197SDuncan P. N. Exon Smith   for (auto I = First; I != Last; ++I) {
23396a06e0eSDuncan P. N. Exon Smith     if (!I->isModule()) {
23496a06e0eSDuncan P. N. Exon Smith       PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),
23516fe4d17SRichard Smith                      PCHChain.end());
23616fe4d17SRichard Smith       break;
23716fe4d17SRichard Smith     }
23816fe4d17SRichard Smith   }
23916fe4d17SRichard Smith 
240188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
2418e6bc197SDuncan P. N. Exon Smith   for (ModuleIterator victim = First; victim != Last; ++victim) {
24296a06e0eSDuncan P. N. Exon Smith     Modules.erase(victim->File);
243ca39214fSBen Langmuir 
2447029ce1aSDouglas Gregor     if (modMap) {
24596a06e0eSDuncan P. N. Exon Smith       StringRef ModuleName = victim->ModuleName;
2467029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
247a13603a2SCraig Topper         mod->setASTFile(nullptr);
2487029ce1aSDouglas Gregor       }
2497029ce1aSDouglas Gregor     }
2504f05478cSBen Langmuir 
2519801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
2529801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
2539801b253SBen Langmuir     // new files that will be renamed over the old ones.
254030d7d6dSDuncan P. N. Exon Smith     //
2552c51880aSSimon Pilgrim     // The PCMCache tracks whether the module was successfully loaded in another
256030d7d6dSDuncan P. N. Exon Smith     // thread/context; in that case, it won't need to be rebuilt (and we can't
257030d7d6dSDuncan P. N. Exon Smith     // safely invalidate it anyway).
258030d7d6dSDuncan P. N. Exon Smith     if (LoadedSuccessfully.count(&*victim) == 0 &&
259030d7d6dSDuncan P. N. Exon Smith         !PCMCache->tryToRemoveBuffer(victim->FileName))
26096a06e0eSDuncan P. N. Exon Smith       FileMgr.invalidateCache(victim->File);
261188dbef2SDouglas Gregor   }
262188dbef2SDouglas Gregor 
263a897f7cdSDuncan P. N. Exon Smith   // Delete the modules.
2648e6bc197SDuncan P. N. Exon Smith   Chain.erase(Chain.begin() + (First - begin()), Chain.end());
265188dbef2SDouglas Gregor }
266188dbef2SDouglas Gregor 
2675cd06f26SRafael Espindola void
2685cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
2695cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
270d44252ecSDouglas Gregor 
2715cd06f26SRafael Espindola   const FileEntry *Entry =
2725cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
2735cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
274d44252ecSDouglas Gregor }
275d44252ecSDouglas Gregor 
276e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
277e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
278e97cd90aSDouglas Gregor   if (FirstVisitState) {
279e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
280e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
281a13603a2SCraig Topper     Result->NextState = nullptr;
282e97cd90aSDouglas Gregor     return Result;
283e97cd90aSDouglas Gregor   }
284e97cd90aSDouglas Gregor 
285e97cd90aSDouglas Gregor   // Allocate and return a new state.
286e97cd90aSDouglas Gregor   return new VisitState(size());
287e97cd90aSDouglas Gregor }
288e97cd90aSDouglas Gregor 
289e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
290a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
291e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
292e97cd90aSDouglas Gregor   FirstVisitState = State;
293e97cd90aSDouglas Gregor }
294e97cd90aSDouglas Gregor 
2957211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
2967211ac15SDouglas Gregor   GlobalIndex = Index;
297603cd869SDouglas Gregor   if (!GlobalIndex) {
298603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
299603cd869SDouglas Gregor     return;
3007029ce1aSDouglas Gregor   }
301603cd869SDouglas Gregor 
302603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
303603cd869SDouglas Gregor   // loaded.
304a897f7cdSDuncan P. N. Exon Smith   for (ModuleFile &M : *this)
305a897f7cdSDuncan P. N. Exon Smith     if (!GlobalIndex->loadedModuleFile(&M))
306a897f7cdSDuncan P. N. Exon Smith       ModulesInCommonWithGlobalIndex.push_back(&M);
307603cd869SDouglas Gregor }
308603cd869SDouglas Gregor 
309603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
310603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
311603cd869SDouglas Gregor     return;
312603cd869SDouglas Gregor 
313603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
3147211ac15SDouglas Gregor }
3157211ac15SDouglas Gregor 
316030d7d6dSDuncan P. N. Exon Smith ModuleManager::ModuleManager(FileManager &FileMgr, MemoryBufferCache &PCMCache,
317*d30446fdSBoris Kolpackov                              const PCHContainerReader &PCHContainerRdr,
318*d30446fdSBoris Kolpackov                              const HeaderSearch& HeaderSearchInfo)
319030d7d6dSDuncan P. N. Exon Smith     : FileMgr(FileMgr), PCMCache(&PCMCache), PCHContainerRdr(PCHContainerRdr),
320*d30446fdSBoris Kolpackov       HeaderSearchInfo (HeaderSearchInfo), GlobalIndex(),
321*d30446fdSBoris Kolpackov       FirstVisitState(nullptr) {}
322d44252ecSDouglas Gregor 
323a897f7cdSDuncan P. N. Exon Smith ModuleManager::~ModuleManager() { delete FirstVisitState; }
324d44252ecSDouglas Gregor 
3259a9efbafSBenjamin Kramer void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
3264dd9b43cSCraig Topper                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
3277211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
328e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
329d44252ecSDouglas Gregor     unsigned N = size();
330e41d7feaSDouglas Gregor     VisitOrder.clear();
331e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
332d44252ecSDouglas Gregor 
333d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
334d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
335d44252ecSDouglas Gregor     // to seed the queue.
336de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
337d44252ecSDouglas Gregor     Queue.reserve(N);
338bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
339a7c535b3SRichard Smith     UnusedIncomingEdges.resize(size());
34096a06e0eSDuncan P. N. Exon Smith     for (ModuleFile &M : llvm::reverse(*this)) {
34196a06e0eSDuncan P. N. Exon Smith       unsigned Size = M.ImportedBy.size();
34296a06e0eSDuncan P. N. Exon Smith       UnusedIncomingEdges[M.Index] = Size;
343a7c535b3SRichard Smith       if (!Size)
34496a06e0eSDuncan P. N. Exon Smith         Queue.push_back(&M);
345d44252ecSDouglas Gregor     }
346d44252ecSDouglas Gregor 
347e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
348e41d7feaSDouglas Gregor     // of its dependencies.
349a7c535b3SRichard Smith     while (!Queue.empty()) {
350a7c535b3SRichard Smith       ModuleFile *CurrentModule = Queue.pop_back_val();
351e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
352d44252ecSDouglas Gregor 
353d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
354d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
355a7c535b3SRichard Smith       for (auto M = CurrentModule->Imports.rbegin(),
356a7c535b3SRichard Smith                 MEnd = CurrentModule->Imports.rend();
357d44252ecSDouglas Gregor            M != MEnd; ++M) {
358d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
359d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
360d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
361d44252ecSDouglas Gregor         // queue to be visited.
362bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
363d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
364d44252ecSDouglas Gregor           Queue.push_back(*M);
365d44252ecSDouglas Gregor       }
366d44252ecSDouglas Gregor     }
367e41d7feaSDouglas Gregor 
368e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3697211ac15SDouglas Gregor 
370e97cd90aSDouglas Gregor     delete FirstVisitState;
371a13603a2SCraig Topper     FirstVisitState = nullptr;
372e41d7feaSDouglas Gregor   }
373e41d7feaSDouglas Gregor 
374e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
375e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
376e41d7feaSDouglas Gregor 
3777211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3787211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3797211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3807211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3817211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3827211ac15SDouglas Gregor     {
3837211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3847029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
385e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
3867211ac15SDouglas Gregor     }
3877211ac15SDouglas Gregor   }
3887211ac15SDouglas Gregor 
389e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
390e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
391e41d7feaSDouglas Gregor     // Should we skip this module file?
392e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
393e41d7feaSDouglas Gregor       continue;
394e41d7feaSDouglas Gregor 
395e41d7feaSDouglas Gregor     // Visit the module.
396e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
397e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
3989a9efbafSBenjamin Kramer     if (!Visitor(*CurrentModule))
399e41d7feaSDouglas Gregor       continue;
400e41d7feaSDouglas Gregor 
401e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
402e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
403e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
404e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
405e41d7feaSDouglas Gregor     do {
406e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
407e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
408e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
409e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
410e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
411e41d7feaSDouglas Gregor            M != MEnd; ++M) {
412e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
413e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
414e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
415e41d7feaSDouglas Gregor         }
416e41d7feaSDouglas Gregor       }
417e41d7feaSDouglas Gregor 
418e97cd90aSDouglas Gregor       if (State->Stack.empty())
419e41d7feaSDouglas Gregor         break;
420e41d7feaSDouglas Gregor 
421e41d7feaSDouglas Gregor       // Pop the next module off the stack.
42225284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
423e41d7feaSDouglas Gregor     } while (true);
424e41d7feaSDouglas Gregor   }
425e97cd90aSDouglas Gregor 
426e97cd90aSDouglas Gregor   returnVisitState(State);
427d44252ecSDouglas Gregor }
428d44252ecSDouglas Gregor 
4297029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4307029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4317029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4327029ce1aSDouglas Gregor                                      const FileEntry *&File) {
4333bd6d7fbSRichard Smith   if (FileName == "-") {
4343bd6d7fbSRichard Smith     File = nullptr;
4353bd6d7fbSRichard Smith     return false;
4363bd6d7fbSRichard Smith   }
4373bd6d7fbSRichard Smith 
43805f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
43905f82ba2SBen Langmuir   // opening the file.
44005f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4413bd6d7fbSRichard Smith   if (!File)
4427029ce1aSDouglas Gregor     return false;
4437029ce1aSDouglas Gregor 
4447029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
445027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
446027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
447027731d7SBen Langmuir     // it will be destroyed by removeModules.
4487029ce1aSDouglas Gregor     return true;
4497029ce1aSDouglas Gregor 
4507029ce1aSDouglas Gregor   return false;
4517029ce1aSDouglas Gregor }
4527029ce1aSDouglas Gregor 
4539d7c1a2aSDouglas Gregor #ifndef NDEBUG
4549d7c1a2aSDouglas Gregor namespace llvm {
4559d7c1a2aSDouglas Gregor   template<>
4569d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
4572931d171STim Shen     typedef ModuleFile *NodeRef;
458de3ef502SDouglas Gregor     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
45996a06e0eSDuncan P. N. Exon Smith     typedef pointer_iterator<ModuleManager::ModuleConstIterator> nodes_iterator;
4609d7c1a2aSDouglas Gregor 
461f2187ed3STim Shen     static ChildIteratorType child_begin(NodeRef Node) {
4629d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4639d7c1a2aSDouglas Gregor     }
4649d7c1a2aSDouglas Gregor 
465f2187ed3STim Shen     static ChildIteratorType child_end(NodeRef Node) {
4669d7c1a2aSDouglas Gregor       return Node->Imports.end();
4679d7c1a2aSDouglas Gregor     }
4689d7c1a2aSDouglas Gregor 
4699d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
47096a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.begin());
4719d7c1a2aSDouglas Gregor     }
4729d7c1a2aSDouglas Gregor 
4739d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
47496a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.end());
4759d7c1a2aSDouglas Gregor     }
4769d7c1a2aSDouglas Gregor   };
4779d7c1a2aSDouglas Gregor 
4789d7c1a2aSDouglas Gregor   template<>
4799d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
4809d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
4819d7c1a2aSDouglas Gregor       : DefaultDOTGraphTraits(IsSimple) { }
4829d7c1a2aSDouglas Gregor 
4839d7c1a2aSDouglas Gregor     static bool renderGraphFromBottomUp() {
4849d7c1a2aSDouglas Gregor       return true;
4859d7c1a2aSDouglas Gregor     }
4869d7c1a2aSDouglas Gregor 
487de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
488beee15e7SBen Langmuir       return M->ModuleName;
4899d7c1a2aSDouglas Gregor     }
4909d7c1a2aSDouglas Gregor   };
491ab9db510SAlexander Kornienko }
4929d7c1a2aSDouglas Gregor 
4939d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
4949d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
4959d7c1a2aSDouglas Gregor }
4969d7c1a2aSDouglas Gregor #endif
497