1b7d89107SEugene Zelenko //===- ModuleManager.cpp - Module Manager ---------------------------------===//
2d44252ecSDouglas Gregor //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d44252ecSDouglas Gregor //
7d44252ecSDouglas Gregor //===----------------------------------------------------------------------===//
8d44252ecSDouglas Gregor //
9d44252ecSDouglas Gregor //  This file defines the ModuleManager class, which manages a set of loaded
10d44252ecSDouglas Gregor //  modules for the ASTReader.
11d44252ecSDouglas Gregor //
12d44252ecSDouglas Gregor //===----------------------------------------------------------------------===//
13b7d89107SEugene Zelenko 
149670f847SMehdi Amini #include "clang/Serialization/ModuleManager.h"
15b7d89107SEugene Zelenko #include "clang/Basic/FileManager.h"
16b7d89107SEugene Zelenko #include "clang/Basic/LLVM.h"
17beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h"
187029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h"
197211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h"
20*8bef5cd4SDuncan P. N. Exon Smith #include "clang/Serialization/InMemoryModuleCache.h"
21b7d89107SEugene Zelenko #include "clang/Serialization/Module.h"
22f3b0046bSRichard Trieu #include "clang/Serialization/PCHContainerOperations.h"
23b7d89107SEugene Zelenko #include "llvm/ADT/STLExtras.h"
24b7d89107SEugene Zelenko #include "llvm/ADT/SetVector.h"
25b7d89107SEugene Zelenko #include "llvm/ADT/SmallPtrSet.h"
26b7d89107SEugene Zelenko #include "llvm/ADT/SmallVector.h"
27b7d89107SEugene Zelenko #include "llvm/ADT/StringRef.h"
28b7d89107SEugene Zelenko #include "llvm/ADT/iterator.h"
29b7d89107SEugene Zelenko #include "llvm/Support/Chrono.h"
30b7d89107SEugene Zelenko #include "llvm/Support/DOTGraphTraits.h"
31b7d89107SEugene Zelenko #include "llvm/Support/ErrorOr.h"
329d7c1a2aSDouglas Gregor #include "llvm/Support/GraphWriter.h"
33b7d89107SEugene Zelenko #include "llvm/Support/MemoryBuffer.h"
34fc51490bSJonas Devlieghere #include "llvm/Support/VirtualFileSystem.h"
35b7d89107SEugene Zelenko #include <algorithm>
36b7d89107SEugene Zelenko #include <cassert>
37b7d89107SEugene Zelenko #include <memory>
38b7d89107SEugene Zelenko #include <string>
39b7d89107SEugene Zelenko #include <system_error>
409d7c1a2aSDouglas Gregor 
41d44252ecSDouglas Gregor using namespace clang;
42d44252ecSDouglas Gregor using namespace serialization;
43d44252ecSDouglas Gregor 
44d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
45dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
46dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
47bf7fc9c5SDouglas Gregor   if (Entry)
48bf7fc9c5SDouglas Gregor     return lookup(Entry);
49bf7fc9c5SDouglas Gregor 
50a13603a2SCraig Topper   return nullptr;
51bf7fc9c5SDouglas Gregor }
52bf7fc9c5SDouglas Gregor 
53d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
54d30446fdSBoris Kolpackov   if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
55d30446fdSBoris Kolpackov     if (const FileEntry *File = Mod->getASTFile())
56d30446fdSBoris Kolpackov       return lookup(File);
57d30446fdSBoris Kolpackov 
58d30446fdSBoris Kolpackov   return nullptr;
59d30446fdSBoris Kolpackov }
60d30446fdSBoris Kolpackov 
6137a93df3SRichard Smith ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
6237a93df3SRichard Smith   auto Known = Modules.find(File);
63bf7fc9c5SDouglas Gregor   if (Known == Modules.end())
64a13603a2SCraig Topper     return nullptr;
65bf7fc9c5SDouglas Gregor 
66bf7fc9c5SDouglas Gregor   return Known->second;
67d44252ecSDouglas Gregor }
68d44252ecSDouglas Gregor 
695cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer>
705cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
71dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
72dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
735cd06f26SRafael Espindola   return std::move(InMemoryBuffers[Entry]);
74d44252ecSDouglas Gregor }
75d44252ecSDouglas Gregor 
7614afc8e7SDuncan P. N. Exon Smith static bool checkSignature(ASTFileSignature Signature,
7714afc8e7SDuncan P. N. Exon Smith                            ASTFileSignature ExpectedSignature,
7814afc8e7SDuncan P. N. Exon Smith                            std::string &ErrorStr) {
7914afc8e7SDuncan P. N. Exon Smith   if (!ExpectedSignature || Signature == ExpectedSignature)
8014afc8e7SDuncan P. N. Exon Smith     return false;
8114afc8e7SDuncan P. N. Exon Smith 
8214afc8e7SDuncan P. N. Exon Smith   ErrorStr =
8314afc8e7SDuncan P. N. Exon Smith       Signature ? "signature mismatch" : "could not read module signature";
8414afc8e7SDuncan P. N. Exon Smith   return true;
8514afc8e7SDuncan P. N. Exon Smith }
8614afc8e7SDuncan P. N. Exon Smith 
8726308a68SDuncan P. N. Exon Smith static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
8826308a68SDuncan P. N. Exon Smith                                 SourceLocation ImportLoc) {
8926308a68SDuncan P. N. Exon Smith   if (ImportedBy) {
9026308a68SDuncan P. N. Exon Smith     MF.ImportedBy.insert(ImportedBy);
9126308a68SDuncan P. N. Exon Smith     ImportedBy->Imports.insert(&MF);
9226308a68SDuncan P. N. Exon Smith   } else {
9326308a68SDuncan P. N. Exon Smith     if (!MF.DirectlyImported)
9426308a68SDuncan P. N. Exon Smith       MF.ImportLoc = ImportLoc;
9526308a68SDuncan P. N. Exon Smith 
9626308a68SDuncan P. N. Exon Smith     MF.DirectlyImported = true;
9726308a68SDuncan P. N. Exon Smith   }
9826308a68SDuncan P. N. Exon Smith }
9926308a68SDuncan P. N. Exon Smith 
1007029ce1aSDouglas Gregor ModuleManager::AddModuleResult
101d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
1026fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
1037029ce1aSDouglas Gregor                          unsigned Generation,
1047029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
105487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
10670a1b816SBen Langmuir                          ASTFileSignatureReader ReadSignature,
1077029ce1aSDouglas Gregor                          ModuleFile *&Module,
1087029ce1aSDouglas Gregor                          std::string &ErrorStr) {
109a13603a2SCraig Topper   Module = nullptr;
1107029ce1aSDouglas Gregor 
1117029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
1127029ce1aSDouglas Gregor   // modification time differ.
1137029ce1aSDouglas Gregor   const FileEntry *Entry;
11411f2a477SManman Ren   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
1155b390756SRichard Smith     // If we're not expecting to pull this file out of the module cache, it
1165b390756SRichard Smith     // might have a different mtime due to being moved across filesystems in
1175b390756SRichard Smith     // a distributed build. The size must still match, though. (As must the
1185b390756SRichard Smith     // contents, but we can't check that.)
1195b390756SRichard Smith     ExpectedModTime = 0;
1205b390756SRichard Smith   }
121c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
122c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
1237029ce1aSDouglas Gregor     return OutOfDate;
124c27d0d5eSEli Friedman   }
1257029ce1aSDouglas Gregor 
126d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
127c27d0d5eSEli Friedman     ErrorStr = "module file not found";
1287029ce1aSDouglas Gregor     return Missing;
129d44252ecSDouglas Gregor   }
130d44252ecSDouglas Gregor 
131d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
13226308a68SDuncan P. N. Exon Smith   if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
13326308a68SDuncan P. N. Exon Smith     // Check the stored signature.
13426308a68SDuncan P. N. Exon Smith     if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
13526308a68SDuncan P. N. Exon Smith       return OutOfDate;
13626308a68SDuncan P. N. Exon Smith 
13726308a68SDuncan P. N. Exon Smith     Module = ModuleEntry;
13826308a68SDuncan P. N. Exon Smith     updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
13926308a68SDuncan P. N. Exon Smith     return AlreadyLoaded;
14026308a68SDuncan P. N. Exon Smith   }
14126308a68SDuncan P. N. Exon Smith 
142d44252ecSDouglas Gregor   // Allocate a new module.
14326308a68SDuncan P. N. Exon Smith   auto NewModule = llvm::make_unique<ModuleFile>(Type, Generation);
144a897f7cdSDuncan P. N. Exon Smith   NewModule->Index = Chain.size();
145a897f7cdSDuncan P. N. Exon Smith   NewModule->FileName = FileName.str();
146a897f7cdSDuncan P. N. Exon Smith   NewModule->File = Entry;
147a897f7cdSDuncan P. N. Exon Smith   NewModule->ImportLoc = ImportLoc;
148a897f7cdSDuncan P. N. Exon Smith   NewModule->InputFilesValidationTimestamp = 0;
149d44252ecSDouglas Gregor 
150a897f7cdSDuncan P. N. Exon Smith   if (NewModule->Kind == MK_ImplicitModule) {
151a897f7cdSDuncan P. N. Exon Smith     std::string TimestampFilename = NewModule->getTimestampFilename();
152fc51490bSJonas Devlieghere     llvm::vfs::Status Status;
153f430da4dSDmitri Gribenko     // A cached stat value would be fine as well.
154f430da4dSDmitri Gribenko     if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
155a897f7cdSDuncan P. N. Exon Smith       NewModule->InputFilesValidationTimestamp =
156ac71c8e2SPavel Labath           llvm::sys::toTimeT(Status.getLastModificationTime());
157f430da4dSDmitri Gribenko   }
158f430da4dSDmitri Gribenko 
159d44252ecSDouglas Gregor   // Load the contents of the module
1605cd06f26SRafael Espindola   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
161d44252ecSDouglas Gregor     // The buffer was already provided for us.
162*8bef5cd4SDuncan P. N. Exon Smith     NewModule->Buffer = &ModuleCache->addBuffer(FileName, std::move(Buffer));
16349092d13SAdrian Prantl     // Since the cached buffer is reused, it is safe to close the file
16449092d13SAdrian Prantl     // descriptor that was opened while stat()ing the PCM in
16549092d13SAdrian Prantl     // lookupModuleFile() above, it won't be needed any longer.
16649092d13SAdrian Prantl     Entry->closeFile();
167*8bef5cd4SDuncan P. N. Exon Smith   } else if (llvm::MemoryBuffer *Buffer =
168*8bef5cd4SDuncan P. N. Exon Smith                  getModuleCache().lookupBuffer(FileName)) {
169030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = Buffer;
17049092d13SAdrian Prantl     // As above, the file descriptor is no longer needed.
17149092d13SAdrian Prantl     Entry->closeFile();
172d44252ecSDouglas Gregor   } else {
173d44252ecSDouglas Gregor     // Open the AST file.
17426308a68SDuncan P. N. Exon Smith     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
175d44252ecSDouglas Gregor     if (FileName == "-") {
176a885796dSBenjamin Kramer       Buf = llvm::MemoryBuffer::getSTDIN();
1779801b253SBen Langmuir     } else {
17849092d13SAdrian Prantl       // Get a buffer of the file and close the file descriptor when done.
179a897f7cdSDuncan P. N. Exon Smith       Buf = FileMgr.getBufferForFile(NewModule->File,
180a885796dSBenjamin Kramer                                      /*IsVolatile=*/false,
18149092d13SAdrian Prantl                                      /*ShouldClose=*/true);
1829801b253SBen Langmuir     }
183d44252ecSDouglas Gregor 
184a885796dSBenjamin Kramer     if (!Buf) {
185a885796dSBenjamin Kramer       ErrorStr = Buf.getError().message();
1867029ce1aSDouglas Gregor       return Missing;
187d44252ecSDouglas Gregor     }
188d44252ecSDouglas Gregor 
189*8bef5cd4SDuncan P. N. Exon Smith     NewModule->Buffer = &getModuleCache().addBuffer(FileName, std::move(*Buf));
190a885796dSBenjamin Kramer   }
191a885796dSBenjamin Kramer 
192bb165fb0SAdrian Prantl   // Initialize the stream.
193a897f7cdSDuncan P. N. Exon Smith   NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
194487ea14aSBen Langmuir 
195688b69adSDuncan P. N. Exon Smith   // Read the signature eagerly now so that we can check it.  Avoid calling
196688b69adSDuncan P. N. Exon Smith   // ReadSignature unless there's something to check though.
197688b69adSDuncan P. N. Exon Smith   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
198030d7d6dSDuncan P. N. Exon Smith                                           ExpectedSignature, ErrorStr)) {
199030d7d6dSDuncan P. N. Exon Smith     // Try to remove the buffer.  If it can't be removed, then it was already
200030d7d6dSDuncan P. N. Exon Smith     // validated by this process.
201*8bef5cd4SDuncan P. N. Exon Smith     if (!getModuleCache().tryToRemoveBuffer(NewModule->FileName))
202030d7d6dSDuncan P. N. Exon Smith       FileMgr.invalidateCache(NewModule->File);
203ed982584SBen Langmuir     return OutOfDate;
204030d7d6dSDuncan P. N. Exon Smith   }
205a897f7cdSDuncan P. N. Exon Smith 
20626308a68SDuncan P. N. Exon Smith   // We're keeping this module.  Store it everywhere.
20726308a68SDuncan P. N. Exon Smith   Module = Modules[Entry] = NewModule.get();
208d44252ecSDouglas Gregor 
20926308a68SDuncan P. N. Exon Smith   updateModuleImports(*NewModule, ImportedBy, ImportLoc);
2106fb03aeaSDouglas Gregor 
21126308a68SDuncan P. N. Exon Smith   if (!NewModule->isModule())
21226308a68SDuncan P. N. Exon Smith     PCHChain.push_back(NewModule.get());
21326308a68SDuncan P. N. Exon Smith   if (!ImportedBy)
21426308a68SDuncan P. N. Exon Smith     Roots.push_back(NewModule.get());
2153b99db55SRichard Smith 
216a897f7cdSDuncan P. N. Exon Smith   Chain.push_back(std::move(NewModule));
2173b99db55SRichard Smith   return NewlyLoaded;
218d44252ecSDouglas Gregor }
219d44252ecSDouglas Gregor 
2209801b253SBen Langmuir void ModuleManager::removeModules(
2218e6bc197SDuncan P. N. Exon Smith     ModuleIterator First,
2229801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
2237029ce1aSDouglas Gregor     ModuleMap *modMap) {
2248e6bc197SDuncan P. N. Exon Smith   auto Last = end();
2258e6bc197SDuncan P. N. Exon Smith   if (First == Last)
226188dbef2SDouglas Gregor     return;
227188dbef2SDouglas Gregor 
228a50dbb20SBen Langmuir   // Explicitly clear VisitOrder since we might not notice it is stale.
229a50dbb20SBen Langmuir   VisitOrder.clear();
230a50dbb20SBen Langmuir 
231188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
23296a06e0eSDuncan P. N. Exon Smith   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
2338e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(First)),
2348e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(Last)));
235188dbef2SDouglas Gregor 
2369eff8b14SManuel Klimek   auto IsVictim = [&](ModuleFile *MF) {
2379eff8b14SManuel Klimek     return victimSet.count(MF);
2389eff8b14SManuel Klimek   };
239188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
240073ec350SDuncan P. N. Exon Smith   for (auto I = begin(); I != First; ++I) {
241073ec350SDuncan P. N. Exon Smith     I->Imports.remove_if(IsVictim);
2428e6bc197SDuncan P. N. Exon Smith     I->ImportedBy.remove_if(IsVictim);
243073ec350SDuncan P. N. Exon Smith   }
2449eff8b14SManuel Klimek   Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
2459eff8b14SManuel Klimek               Roots.end());
246188dbef2SDouglas Gregor 
24716fe4d17SRichard Smith   // Remove the modules from the PCH chain.
2488e6bc197SDuncan P. N. Exon Smith   for (auto I = First; I != Last; ++I) {
24996a06e0eSDuncan P. N. Exon Smith     if (!I->isModule()) {
25096a06e0eSDuncan P. N. Exon Smith       PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),
25116fe4d17SRichard Smith                      PCHChain.end());
25216fe4d17SRichard Smith       break;
25316fe4d17SRichard Smith     }
25416fe4d17SRichard Smith   }
25516fe4d17SRichard Smith 
256188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
2578e6bc197SDuncan P. N. Exon Smith   for (ModuleIterator victim = First; victim != Last; ++victim) {
25896a06e0eSDuncan P. N. Exon Smith     Modules.erase(victim->File);
259ca39214fSBen Langmuir 
2607029ce1aSDouglas Gregor     if (modMap) {
26196a06e0eSDuncan P. N. Exon Smith       StringRef ModuleName = victim->ModuleName;
2627029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
263a13603a2SCraig Topper         mod->setASTFile(nullptr);
2647029ce1aSDouglas Gregor       }
2657029ce1aSDouglas Gregor     }
2664f05478cSBen Langmuir 
2679801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
2689801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
2699801b253SBen Langmuir     // new files that will be renamed over the old ones.
270030d7d6dSDuncan P. N. Exon Smith     //
271*8bef5cd4SDuncan P. N. Exon Smith     // The ModuleCache tracks whether the module was successfully loaded in
272*8bef5cd4SDuncan P. N. Exon Smith     // another thread/context; in that case, it won't need to be rebuilt (and
273*8bef5cd4SDuncan P. N. Exon Smith     // we can't safely invalidate it anyway).
274030d7d6dSDuncan P. N. Exon Smith     if (LoadedSuccessfully.count(&*victim) == 0 &&
275*8bef5cd4SDuncan P. N. Exon Smith         !getModuleCache().tryToRemoveBuffer(victim->FileName))
27696a06e0eSDuncan P. N. Exon Smith       FileMgr.invalidateCache(victim->File);
277188dbef2SDouglas Gregor   }
278188dbef2SDouglas Gregor 
279a897f7cdSDuncan P. N. Exon Smith   // Delete the modules.
2808e6bc197SDuncan P. N. Exon Smith   Chain.erase(Chain.begin() + (First - begin()), Chain.end());
281188dbef2SDouglas Gregor }
282188dbef2SDouglas Gregor 
2835cd06f26SRafael Espindola void
2845cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
2855cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
2865cd06f26SRafael Espindola   const FileEntry *Entry =
2875cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
2885cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
289d44252ecSDouglas Gregor }
290d44252ecSDouglas Gregor 
291e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
292e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
293e97cd90aSDouglas Gregor   if (FirstVisitState) {
294e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
295e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
296a13603a2SCraig Topper     Result->NextState = nullptr;
297e97cd90aSDouglas Gregor     return Result;
298e97cd90aSDouglas Gregor   }
299e97cd90aSDouglas Gregor 
300e97cd90aSDouglas Gregor   // Allocate and return a new state.
301e97cd90aSDouglas Gregor   return new VisitState(size());
302e97cd90aSDouglas Gregor }
303e97cd90aSDouglas Gregor 
304e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
305a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
306e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
307e97cd90aSDouglas Gregor   FirstVisitState = State;
308e97cd90aSDouglas Gregor }
309e97cd90aSDouglas Gregor 
3107211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
3117211ac15SDouglas Gregor   GlobalIndex = Index;
312603cd869SDouglas Gregor   if (!GlobalIndex) {
313603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
314603cd869SDouglas Gregor     return;
3157029ce1aSDouglas Gregor   }
316603cd869SDouglas Gregor 
317603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
318603cd869SDouglas Gregor   // loaded.
319a897f7cdSDuncan P. N. Exon Smith   for (ModuleFile &M : *this)
320a897f7cdSDuncan P. N. Exon Smith     if (!GlobalIndex->loadedModuleFile(&M))
321a897f7cdSDuncan P. N. Exon Smith       ModulesInCommonWithGlobalIndex.push_back(&M);
322603cd869SDouglas Gregor }
323603cd869SDouglas Gregor 
324603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
325603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
326603cd869SDouglas Gregor     return;
327603cd869SDouglas Gregor 
328603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
3297211ac15SDouglas Gregor }
3307211ac15SDouglas Gregor 
331*8bef5cd4SDuncan P. N. Exon Smith ModuleManager::ModuleManager(FileManager &FileMgr,
332*8bef5cd4SDuncan P. N. Exon Smith                              InMemoryModuleCache &ModuleCache,
333d30446fdSBoris Kolpackov                              const PCHContainerReader &PCHContainerRdr,
334d30446fdSBoris Kolpackov                              const HeaderSearch &HeaderSearchInfo)
335*8bef5cd4SDuncan P. N. Exon Smith     : FileMgr(FileMgr), ModuleCache(&ModuleCache),
336*8bef5cd4SDuncan P. N. Exon Smith       PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
337d44252ecSDouglas Gregor 
338a897f7cdSDuncan P. N. Exon Smith ModuleManager::~ModuleManager() { delete FirstVisitState; }
339d44252ecSDouglas Gregor 
3409a9efbafSBenjamin Kramer void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
3414dd9b43cSCraig Topper                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
3427211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
343e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
344d44252ecSDouglas Gregor     unsigned N = size();
345e41d7feaSDouglas Gregor     VisitOrder.clear();
346e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
347d44252ecSDouglas Gregor 
348d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
349d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
350d44252ecSDouglas Gregor     // to seed the queue.
351de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
352d44252ecSDouglas Gregor     Queue.reserve(N);
353bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
354a7c535b3SRichard Smith     UnusedIncomingEdges.resize(size());
35596a06e0eSDuncan P. N. Exon Smith     for (ModuleFile &M : llvm::reverse(*this)) {
35696a06e0eSDuncan P. N. Exon Smith       unsigned Size = M.ImportedBy.size();
35796a06e0eSDuncan P. N. Exon Smith       UnusedIncomingEdges[M.Index] = Size;
358a7c535b3SRichard Smith       if (!Size)
35996a06e0eSDuncan P. N. Exon Smith         Queue.push_back(&M);
360d44252ecSDouglas Gregor     }
361d44252ecSDouglas Gregor 
362e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
363e41d7feaSDouglas Gregor     // of its dependencies.
364a7c535b3SRichard Smith     while (!Queue.empty()) {
365a7c535b3SRichard Smith       ModuleFile *CurrentModule = Queue.pop_back_val();
366e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
367d44252ecSDouglas Gregor 
368d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
369d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
370a7c535b3SRichard Smith       for (auto M = CurrentModule->Imports.rbegin(),
371a7c535b3SRichard Smith                 MEnd = CurrentModule->Imports.rend();
372d44252ecSDouglas Gregor            M != MEnd; ++M) {
373d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
374d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
375d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
376d44252ecSDouglas Gregor         // queue to be visited.
377bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
378d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
379d44252ecSDouglas Gregor           Queue.push_back(*M);
380d44252ecSDouglas Gregor       }
381d44252ecSDouglas Gregor     }
382e41d7feaSDouglas Gregor 
383e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3847211ac15SDouglas Gregor 
385e97cd90aSDouglas Gregor     delete FirstVisitState;
386a13603a2SCraig Topper     FirstVisitState = nullptr;
387e41d7feaSDouglas Gregor   }
388e41d7feaSDouglas Gregor 
389e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
390e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
391e41d7feaSDouglas Gregor 
3927211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3937211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3947211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3957211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3967211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3977211ac15SDouglas Gregor     {
3987211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3997029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
400e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
4017211ac15SDouglas Gregor     }
4027211ac15SDouglas Gregor   }
4037211ac15SDouglas Gregor 
404e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
405e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
406e41d7feaSDouglas Gregor     // Should we skip this module file?
407e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
408e41d7feaSDouglas Gregor       continue;
409e41d7feaSDouglas Gregor 
410e41d7feaSDouglas Gregor     // Visit the module.
411e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
412e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
4139a9efbafSBenjamin Kramer     if (!Visitor(*CurrentModule))
414e41d7feaSDouglas Gregor       continue;
415e41d7feaSDouglas Gregor 
416e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
417e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
418e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
419e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
420e41d7feaSDouglas Gregor     do {
421e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
422e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
423e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
424e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
425e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
426e41d7feaSDouglas Gregor            M != MEnd; ++M) {
427e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
428e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
429e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
430e41d7feaSDouglas Gregor         }
431e41d7feaSDouglas Gregor       }
432e41d7feaSDouglas Gregor 
433e97cd90aSDouglas Gregor       if (State->Stack.empty())
434e41d7feaSDouglas Gregor         break;
435e41d7feaSDouglas Gregor 
436e41d7feaSDouglas Gregor       // Pop the next module off the stack.
43725284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
438e41d7feaSDouglas Gregor     } while (true);
439e41d7feaSDouglas Gregor   }
440e97cd90aSDouglas Gregor 
441e97cd90aSDouglas Gregor   returnVisitState(State);
442d44252ecSDouglas Gregor }
443d44252ecSDouglas Gregor 
4447029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4457029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4467029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4477029ce1aSDouglas Gregor                                      const FileEntry *&File) {
4483bd6d7fbSRichard Smith   if (FileName == "-") {
4493bd6d7fbSRichard Smith     File = nullptr;
4503bd6d7fbSRichard Smith     return false;
4513bd6d7fbSRichard Smith   }
4523bd6d7fbSRichard Smith 
45305f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
45405f82ba2SBen Langmuir   // opening the file.
45505f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4563bd6d7fbSRichard Smith   if (!File)
4577029ce1aSDouglas Gregor     return false;
4587029ce1aSDouglas Gregor 
4597029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
460027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
461027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
462027731d7SBen Langmuir     // it will be destroyed by removeModules.
4637029ce1aSDouglas Gregor     return true;
4647029ce1aSDouglas Gregor 
4657029ce1aSDouglas Gregor   return false;
4667029ce1aSDouglas Gregor }
4677029ce1aSDouglas Gregor 
4689d7c1a2aSDouglas Gregor #ifndef NDEBUG
4699d7c1a2aSDouglas Gregor namespace llvm {
470b7d89107SEugene Zelenko 
4719d7c1a2aSDouglas Gregor   template<>
4729d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
473b7d89107SEugene Zelenko     using NodeRef = ModuleFile *;
474b7d89107SEugene Zelenko     using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
475b7d89107SEugene Zelenko     using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
4769d7c1a2aSDouglas Gregor 
477f2187ed3STim Shen     static ChildIteratorType child_begin(NodeRef Node) {
4789d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4799d7c1a2aSDouglas Gregor     }
4809d7c1a2aSDouglas Gregor 
481f2187ed3STim Shen     static ChildIteratorType child_end(NodeRef Node) {
4829d7c1a2aSDouglas Gregor       return Node->Imports.end();
4839d7c1a2aSDouglas Gregor     }
4849d7c1a2aSDouglas Gregor 
4859d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
48696a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.begin());
4879d7c1a2aSDouglas Gregor     }
4889d7c1a2aSDouglas Gregor 
4899d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
49096a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.end());
4919d7c1a2aSDouglas Gregor     }
4929d7c1a2aSDouglas Gregor   };
4939d7c1a2aSDouglas Gregor 
4949d7c1a2aSDouglas Gregor   template<>
4959d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
4969d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
4979d7c1a2aSDouglas Gregor         : DefaultDOTGraphTraits(IsSimple) {}
4989d7c1a2aSDouglas Gregor 
499b7d89107SEugene Zelenko     static bool renderGraphFromBottomUp() { return true; }
5009d7c1a2aSDouglas Gregor 
501de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
502beee15e7SBen Langmuir       return M->ModuleName;
5039d7c1a2aSDouglas Gregor     }
5049d7c1a2aSDouglas Gregor   };
505b7d89107SEugene Zelenko 
506b7d89107SEugene Zelenko } // namespace llvm
5079d7c1a2aSDouglas Gregor 
5089d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
5099d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
5109d7c1a2aSDouglas Gregor }
5119d7c1a2aSDouglas Gregor #endif
512