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"
208bef5cd4SDuncan P. N. Exon Smith #include "clang/Serialization/InMemoryModuleCache.h"
21f7170d17SDuncan P. N. Exon Smith #include "clang/Serialization/ModuleFile.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 
lookupByFileName(StringRef Name) const44d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
458d323d15SHarlan Haskins   auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
4649a3ad21SRui Ueyama                                /*CacheFailure=*/false);
47bf7fc9c5SDouglas Gregor   if (Entry)
488d323d15SHarlan Haskins     return lookup(*Entry);
49bf7fc9c5SDouglas Gregor 
50a13603a2SCraig Topper   return nullptr;
51bf7fc9c5SDouglas Gregor }
52bf7fc9c5SDouglas Gregor 
lookupByModuleName(StringRef Name) const53d30446fdSBoris 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 
lookup(const FileEntry * File) const6137a93df3SRichard 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>
lookupBuffer(StringRef Name)705cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
718d323d15SHarlan Haskins   auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
7249a3ad21SRui Ueyama                                /*CacheFailure=*/false);
738d323d15SHarlan Haskins   if (!Entry)
748d323d15SHarlan Haskins     return nullptr;
758d323d15SHarlan Haskins   return std::move(InMemoryBuffers[*Entry]);
76d44252ecSDouglas Gregor }
77d44252ecSDouglas Gregor 
checkSignature(ASTFileSignature Signature,ASTFileSignature ExpectedSignature,std::string & ErrorStr)7814afc8e7SDuncan P. N. Exon Smith static bool checkSignature(ASTFileSignature Signature,
7914afc8e7SDuncan P. N. Exon Smith                            ASTFileSignature ExpectedSignature,
8014afc8e7SDuncan P. N. Exon Smith                            std::string &ErrorStr) {
8114afc8e7SDuncan P. N. Exon Smith   if (!ExpectedSignature || Signature == ExpectedSignature)
8214afc8e7SDuncan P. N. Exon Smith     return false;
8314afc8e7SDuncan P. N. Exon Smith 
8414afc8e7SDuncan P. N. Exon Smith   ErrorStr =
8514afc8e7SDuncan P. N. Exon Smith       Signature ? "signature mismatch" : "could not read module signature";
8614afc8e7SDuncan P. N. Exon Smith   return true;
8714afc8e7SDuncan P. N. Exon Smith }
8814afc8e7SDuncan P. N. Exon Smith 
updateModuleImports(ModuleFile & MF,ModuleFile * ImportedBy,SourceLocation ImportLoc)8926308a68SDuncan P. N. Exon Smith static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
9026308a68SDuncan P. N. Exon Smith                                 SourceLocation ImportLoc) {
9126308a68SDuncan P. N. Exon Smith   if (ImportedBy) {
9226308a68SDuncan P. N. Exon Smith     MF.ImportedBy.insert(ImportedBy);
9326308a68SDuncan P. N. Exon Smith     ImportedBy->Imports.insert(&MF);
9426308a68SDuncan P. N. Exon Smith   } else {
9526308a68SDuncan P. N. Exon Smith     if (!MF.DirectlyImported)
9626308a68SDuncan P. N. Exon Smith       MF.ImportLoc = ImportLoc;
9726308a68SDuncan P. N. Exon Smith 
9826308a68SDuncan P. N. Exon Smith     MF.DirectlyImported = true;
9926308a68SDuncan P. N. Exon Smith   }
10026308a68SDuncan P. N. Exon Smith }
10126308a68SDuncan P. N. Exon Smith 
1027029ce1aSDouglas Gregor 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)103d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
1046fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
1057029ce1aSDouglas Gregor                          unsigned Generation,
1067029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
107487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
10870a1b816SBen Langmuir                          ASTFileSignatureReader ReadSignature,
1097029ce1aSDouglas Gregor                          ModuleFile *&Module,
1107029ce1aSDouglas Gregor                          std::string &ErrorStr) {
111a13603a2SCraig Topper   Module = nullptr;
1127029ce1aSDouglas Gregor 
1137029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
1147029ce1aSDouglas Gregor   // modification time differ.
1159f151df1SDuncan P. N. Exon Smith   OptionalFileEntryRefDegradesToFileEntryPtr Entry;
11611f2a477SManman Ren   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
1175b390756SRichard Smith     // If we're not expecting to pull this file out of the module cache, it
1185b390756SRichard Smith     // might have a different mtime due to being moved across filesystems in
1195b390756SRichard Smith     // a distributed build. The size must still match, though. (As must the
1205b390756SRichard Smith     // contents, but we can't check that.)
1215b390756SRichard Smith     ExpectedModTime = 0;
1225b390756SRichard Smith   }
1230a2be46cSDuncan P. N. Exon Smith   // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule
1240a2be46cSDuncan P. N. Exon Smith   // when using an ASTFileSignature.
125c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
126c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
1277029ce1aSDouglas Gregor     return OutOfDate;
128c27d0d5eSEli Friedman   }
1297029ce1aSDouglas Gregor 
130d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
131c27d0d5eSEli Friedman     ErrorStr = "module file not found";
1327029ce1aSDouglas Gregor     return Missing;
133d44252ecSDouglas Gregor   }
134d44252ecSDouglas Gregor 
135272742a9SAdrian Prantl   // The ModuleManager's use of FileEntry nodes as the keys for its map of
136272742a9SAdrian Prantl   // loaded modules is less than ideal. Uniqueness for FileEntry nodes is
137272742a9SAdrian Prantl   // maintained by FileManager, which in turn uses inode numbers on hosts
138272742a9SAdrian Prantl   // that support that. When coupled with the module cache's proclivity for
139272742a9SAdrian Prantl   // turning over and deleting stale PCMs, this means entries for different
140272742a9SAdrian Prantl   // module files can wind up reusing the same underlying inode. When this
141272742a9SAdrian Prantl   // happens, subsequent accesses to the Modules map will disagree on the
142272742a9SAdrian Prantl   // ModuleFile associated with a given file. In general, it is not sufficient
143272742a9SAdrian Prantl   // to resolve this conundrum with a type like FileEntryRef that stores the
144272742a9SAdrian Prantl   // name of the FileEntry node on first access because of path canonicalization
145272742a9SAdrian Prantl   // issues. However, the paths constructed for implicit module builds are
146272742a9SAdrian Prantl   // fully under Clang's control. We *can*, therefore, rely on their structure
147272742a9SAdrian Prantl   // being consistent across operating systems and across subsequent accesses
148272742a9SAdrian Prantl   // to the Modules map.
149272742a9SAdrian Prantl   auto implicitModuleNamesMatch = [](ModuleKind Kind, const ModuleFile *MF,
150272742a9SAdrian Prantl                                      const FileEntry *Entry) -> bool {
151272742a9SAdrian Prantl     if (Kind != MK_ImplicitModule)
152272742a9SAdrian Prantl       return true;
153272742a9SAdrian Prantl     return Entry->getName() == MF->FileName;
154272742a9SAdrian Prantl   };
155272742a9SAdrian Prantl 
156d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
15726308a68SDuncan P. N. Exon Smith   if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
158272742a9SAdrian Prantl     if (implicitModuleNamesMatch(Type, ModuleEntry, Entry)) {
15926308a68SDuncan P. N. Exon Smith       // Check the stored signature.
16026308a68SDuncan P. N. Exon Smith       if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
16126308a68SDuncan P. N. Exon Smith         return OutOfDate;
16226308a68SDuncan P. N. Exon Smith 
16326308a68SDuncan P. N. Exon Smith       Module = ModuleEntry;
16426308a68SDuncan P. N. Exon Smith       updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
16526308a68SDuncan P. N. Exon Smith       return AlreadyLoaded;
16626308a68SDuncan P. N. Exon Smith     }
167272742a9SAdrian Prantl   }
16826308a68SDuncan P. N. Exon Smith 
169d44252ecSDouglas Gregor   // Allocate a new module.
1702b3d49b6SJonas Devlieghere   auto NewModule = std::make_unique<ModuleFile>(Type, Generation);
171a897f7cdSDuncan P. N. Exon Smith   NewModule->Index = Chain.size();
172a897f7cdSDuncan P. N. Exon Smith   NewModule->FileName = FileName.str();
173a897f7cdSDuncan P. N. Exon Smith   NewModule->File = Entry;
174a897f7cdSDuncan P. N. Exon Smith   NewModule->ImportLoc = ImportLoc;
175a897f7cdSDuncan P. N. Exon Smith   NewModule->InputFilesValidationTimestamp = 0;
176d44252ecSDouglas Gregor 
177a897f7cdSDuncan P. N. Exon Smith   if (NewModule->Kind == MK_ImplicitModule) {
178a897f7cdSDuncan P. N. Exon Smith     std::string TimestampFilename = NewModule->getTimestampFilename();
179fc51490bSJonas Devlieghere     llvm::vfs::Status Status;
180f430da4dSDmitri Gribenko     // A cached stat value would be fine as well.
181f430da4dSDmitri Gribenko     if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
182a897f7cdSDuncan P. N. Exon Smith       NewModule->InputFilesValidationTimestamp =
183ac71c8e2SPavel Labath           llvm::sys::toTimeT(Status.getLastModificationTime());
184f430da4dSDmitri Gribenko   }
185f430da4dSDmitri Gribenko 
186d44252ecSDouglas Gregor   // Load the contents of the module
1875cd06f26SRafael Espindola   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
188d44252ecSDouglas Gregor     // The buffer was already provided for us.
18957a2eaf3SRumeet Dhindsa     NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer));
19049092d13SAdrian Prantl     // Since the cached buffer is reused, it is safe to close the file
19149092d13SAdrian Prantl     // descriptor that was opened while stat()ing the PCM in
19249092d13SAdrian Prantl     // lookupModuleFile() above, it won't be needed any longer.
19349092d13SAdrian Prantl     Entry->closeFile();
1948bef5cd4SDuncan P. N. Exon Smith   } else if (llvm::MemoryBuffer *Buffer =
1950a2be46cSDuncan P. N. Exon Smith                  getModuleCache().lookupPCM(FileName)) {
196030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = Buffer;
19749092d13SAdrian Prantl     // As above, the file descriptor is no longer needed.
19849092d13SAdrian Prantl     Entry->closeFile();
19957a2eaf3SRumeet Dhindsa   } else if (getModuleCache().shouldBuildPCM(FileName)) {
20057a2eaf3SRumeet Dhindsa     // Report that the module is out of date, since we tried (and failed) to
20157a2eaf3SRumeet Dhindsa     // import it earlier.
20257a2eaf3SRumeet Dhindsa     Entry->closeFile();
20357a2eaf3SRumeet Dhindsa     return OutOfDate;
204d44252ecSDouglas Gregor   } else {
205d44252ecSDouglas Gregor     // Open the AST file.
20626308a68SDuncan P. N. Exon Smith     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
207d44252ecSDouglas Gregor     if (FileName == "-") {
208a885796dSBenjamin Kramer       Buf = llvm::MemoryBuffer::getSTDIN();
2099801b253SBen Langmuir     } else {
21049092d13SAdrian Prantl       // Get a buffer of the file and close the file descriptor when done.
2111727c6aaSMichael Spencer       // The file is volatile because in a parallel build we expect multiple
2121727c6aaSMichael Spencer       // compiler processes to use the same module file rebuilding it if needed.
2131727c6aaSMichael Spencer       //
2141727c6aaSMichael Spencer       // RequiresNullTerminator is false because module files don't need it, and
2151727c6aaSMichael Spencer       // this allows the file to still be mmapped.
2161727c6aaSMichael Spencer       Buf = FileMgr.getBufferForFile(NewModule->File,
2171727c6aaSMichael Spencer                                      /*IsVolatile=*/true,
2181727c6aaSMichael Spencer                                      /*RequiresNullTerminator=*/false);
2199801b253SBen Langmuir     }
220d44252ecSDouglas Gregor 
221a885796dSBenjamin Kramer     if (!Buf) {
222a885796dSBenjamin Kramer       ErrorStr = Buf.getError().message();
2237029ce1aSDouglas Gregor       return Missing;
224d44252ecSDouglas Gregor     }
225d44252ecSDouglas Gregor 
2260a2be46cSDuncan P. N. Exon Smith     NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf));
227a885796dSBenjamin Kramer   }
228a885796dSBenjamin Kramer 
229bb165fb0SAdrian Prantl   // Initialize the stream.
230a897f7cdSDuncan P. N. Exon Smith   NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
231487ea14aSBen Langmuir 
232688b69adSDuncan P. N. Exon Smith   // Read the signature eagerly now so that we can check it.  Avoid calling
233688b69adSDuncan P. N. Exon Smith   // ReadSignature unless there's something to check though.
234688b69adSDuncan P. N. Exon Smith   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
235f91b6f81SVolodymyr Sapsai                                           ExpectedSignature, ErrorStr))
236ed982584SBen Langmuir     return OutOfDate;
237a897f7cdSDuncan P. N. Exon Smith 
23826308a68SDuncan P. N. Exon Smith   // We're keeping this module.  Store it everywhere.
23926308a68SDuncan P. N. Exon Smith   Module = Modules[Entry] = NewModule.get();
240d44252ecSDouglas Gregor 
24126308a68SDuncan P. N. Exon Smith   updateModuleImports(*NewModule, ImportedBy, ImportLoc);
2426fb03aeaSDouglas Gregor 
24326308a68SDuncan P. N. Exon Smith   if (!NewModule->isModule())
24426308a68SDuncan P. N. Exon Smith     PCHChain.push_back(NewModule.get());
24526308a68SDuncan P. N. Exon Smith   if (!ImportedBy)
24626308a68SDuncan P. N. Exon Smith     Roots.push_back(NewModule.get());
2473b99db55SRichard Smith 
248a897f7cdSDuncan P. N. Exon Smith   Chain.push_back(std::move(NewModule));
2493b99db55SRichard Smith   return NewlyLoaded;
250d44252ecSDouglas Gregor }
251d44252ecSDouglas Gregor 
removeModules(ModuleIterator First,ModuleMap * modMap)2528e9e433aSDuncan P. N. Exon Smith void ModuleManager::removeModules(ModuleIterator First, ModuleMap *modMap) {
2538e6bc197SDuncan P. N. Exon Smith   auto Last = end();
2548e6bc197SDuncan P. N. Exon Smith   if (First == Last)
255188dbef2SDouglas Gregor     return;
256188dbef2SDouglas Gregor 
257a50dbb20SBen Langmuir   // Explicitly clear VisitOrder since we might not notice it is stale.
258a50dbb20SBen Langmuir   VisitOrder.clear();
259a50dbb20SBen Langmuir 
260188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
26196a06e0eSDuncan P. N. Exon Smith   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
2628e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(First)),
2638e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(Last)));
264188dbef2SDouglas Gregor 
2659eff8b14SManuel Klimek   auto IsVictim = [&](ModuleFile *MF) {
2669eff8b14SManuel Klimek     return victimSet.count(MF);
2679eff8b14SManuel Klimek   };
268188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
269073ec350SDuncan P. N. Exon Smith   for (auto I = begin(); I != First; ++I) {
270073ec350SDuncan P. N. Exon Smith     I->Imports.remove_if(IsVictim);
2718e6bc197SDuncan P. N. Exon Smith     I->ImportedBy.remove_if(IsVictim);
272073ec350SDuncan P. N. Exon Smith   }
273d245f2e8SKazu Hirata   llvm::erase_if(Roots, IsVictim);
274188dbef2SDouglas Gregor 
27516fe4d17SRichard Smith   // Remove the modules from the PCH chain.
2768e6bc197SDuncan P. N. Exon Smith   for (auto I = First; I != Last; ++I) {
27796a06e0eSDuncan P. N. Exon Smith     if (!I->isModule()) {
27875e74e07SFangrui Song       PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
27916fe4d17SRichard Smith       break;
28016fe4d17SRichard Smith     }
28116fe4d17SRichard Smith   }
28216fe4d17SRichard Smith 
283188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
2848e6bc197SDuncan P. N. Exon Smith   for (ModuleIterator victim = First; victim != Last; ++victim) {
28596a06e0eSDuncan P. N. Exon Smith     Modules.erase(victim->File);
286ca39214fSBen Langmuir 
2877029ce1aSDouglas Gregor     if (modMap) {
28896a06e0eSDuncan P. N. Exon Smith       StringRef ModuleName = victim->ModuleName;
2897029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
2909f151df1SDuncan P. N. Exon Smith         mod->setASTFile(None);
2917029ce1aSDouglas Gregor       }
2927029ce1aSDouglas Gregor     }
293188dbef2SDouglas Gregor   }
294188dbef2SDouglas Gregor 
295a897f7cdSDuncan P. N. Exon Smith   // Delete the modules.
2968e6bc197SDuncan P. N. Exon Smith   Chain.erase(Chain.begin() + (First - begin()), Chain.end());
297188dbef2SDouglas Gregor }
298188dbef2SDouglas Gregor 
2995cd06f26SRafael Espindola void
addInMemoryBuffer(StringRef FileName,std::unique_ptr<llvm::MemoryBuffer> Buffer)3005cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
3015cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
3025cd06f26SRafael Espindola   const FileEntry *Entry =
3035cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
3045cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
305d44252ecSDouglas Gregor }
306d44252ecSDouglas Gregor 
allocateVisitState()307*baa9b7c3SDavid Blaikie std::unique_ptr<ModuleManager::VisitState> ModuleManager::allocateVisitState() {
308e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
309e97cd90aSDouglas Gregor   if (FirstVisitState) {
310*baa9b7c3SDavid Blaikie     auto Result = std::move(FirstVisitState);
311*baa9b7c3SDavid Blaikie     FirstVisitState = std::move(Result->NextState);
312e97cd90aSDouglas Gregor     return Result;
313e97cd90aSDouglas Gregor   }
314e97cd90aSDouglas Gregor 
315e97cd90aSDouglas Gregor   // Allocate and return a new state.
316*baa9b7c3SDavid Blaikie   return std::make_unique<VisitState>(size());
317e97cd90aSDouglas Gregor }
318e97cd90aSDouglas Gregor 
returnVisitState(std::unique_ptr<VisitState> State)319*baa9b7c3SDavid Blaikie void ModuleManager::returnVisitState(std::unique_ptr<VisitState> State) {
320a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
321*baa9b7c3SDavid Blaikie   State->NextState = std::move(FirstVisitState);
322*baa9b7c3SDavid Blaikie   FirstVisitState = std::move(State);
323e97cd90aSDouglas Gregor }
324e97cd90aSDouglas Gregor 
setGlobalIndex(GlobalModuleIndex * Index)3257211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
3267211ac15SDouglas Gregor   GlobalIndex = Index;
327603cd869SDouglas Gregor   if (!GlobalIndex) {
328603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
329603cd869SDouglas Gregor     return;
3307029ce1aSDouglas Gregor   }
331603cd869SDouglas Gregor 
332603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
333603cd869SDouglas Gregor   // loaded.
334a897f7cdSDuncan P. N. Exon Smith   for (ModuleFile &M : *this)
335a897f7cdSDuncan P. N. Exon Smith     if (!GlobalIndex->loadedModuleFile(&M))
336a897f7cdSDuncan P. N. Exon Smith       ModulesInCommonWithGlobalIndex.push_back(&M);
337603cd869SDouglas Gregor }
338603cd869SDouglas Gregor 
moduleFileAccepted(ModuleFile * MF)339603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
340603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
341603cd869SDouglas Gregor     return;
342603cd869SDouglas Gregor 
343603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
3447211ac15SDouglas Gregor }
3457211ac15SDouglas Gregor 
ModuleManager(FileManager & FileMgr,InMemoryModuleCache & ModuleCache,const PCHContainerReader & PCHContainerRdr,const HeaderSearch & HeaderSearchInfo)3468bef5cd4SDuncan P. N. Exon Smith ModuleManager::ModuleManager(FileManager &FileMgr,
3478bef5cd4SDuncan P. N. Exon Smith                              InMemoryModuleCache &ModuleCache,
348d30446fdSBoris Kolpackov                              const PCHContainerReader &PCHContainerRdr,
349d30446fdSBoris Kolpackov                              const HeaderSearch &HeaderSearchInfo)
3508bef5cd4SDuncan P. N. Exon Smith     : FileMgr(FileMgr), ModuleCache(&ModuleCache),
3518bef5cd4SDuncan P. N. Exon Smith       PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
352d44252ecSDouglas Gregor 
visit(llvm::function_ref<bool (ModuleFile & M)> Visitor,llvm::SmallPtrSetImpl<ModuleFile * > * ModuleFilesHit)3539a9efbafSBenjamin Kramer void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
3544dd9b43cSCraig Topper                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
3557211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
356e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
357d44252ecSDouglas Gregor     unsigned N = size();
358e41d7feaSDouglas Gregor     VisitOrder.clear();
359e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
360d44252ecSDouglas Gregor 
361d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
362d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
363d44252ecSDouglas Gregor     // to seed the queue.
364de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
365d44252ecSDouglas Gregor     Queue.reserve(N);
366bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
367a7c535b3SRichard Smith     UnusedIncomingEdges.resize(size());
36896a06e0eSDuncan P. N. Exon Smith     for (ModuleFile &M : llvm::reverse(*this)) {
36996a06e0eSDuncan P. N. Exon Smith       unsigned Size = M.ImportedBy.size();
37096a06e0eSDuncan P. N. Exon Smith       UnusedIncomingEdges[M.Index] = Size;
371a7c535b3SRichard Smith       if (!Size)
37296a06e0eSDuncan P. N. Exon Smith         Queue.push_back(&M);
373d44252ecSDouglas Gregor     }
374d44252ecSDouglas Gregor 
375e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
376e41d7feaSDouglas Gregor     // of its dependencies.
377a7c535b3SRichard Smith     while (!Queue.empty()) {
378a7c535b3SRichard Smith       ModuleFile *CurrentModule = Queue.pop_back_val();
379e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
380d44252ecSDouglas Gregor 
381d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
382d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
38374115602SKazu Hirata       for (ModuleFile *M : llvm::reverse(CurrentModule->Imports)) {
384d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
385d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
386d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
387d44252ecSDouglas Gregor         // queue to be visited.
38874115602SKazu Hirata         unsigned &NumUnusedEdges = UnusedIncomingEdges[M->Index];
389d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
39074115602SKazu Hirata           Queue.push_back(M);
391d44252ecSDouglas Gregor       }
392d44252ecSDouglas Gregor     }
393e41d7feaSDouglas Gregor 
394e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3957211ac15SDouglas Gregor 
396a13603a2SCraig Topper     FirstVisitState = nullptr;
397e41d7feaSDouglas Gregor   }
398e41d7feaSDouglas Gregor 
399*baa9b7c3SDavid Blaikie   auto State = allocateVisitState();
400e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
401e41d7feaSDouglas Gregor 
4027211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
4037211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
4047211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
4057211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
4067211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
4077211ac15SDouglas Gregor     {
4087211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
4097029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
410e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
4117211ac15SDouglas Gregor     }
4127211ac15SDouglas Gregor   }
4137211ac15SDouglas Gregor 
414e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
415e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
416e41d7feaSDouglas Gregor     // Should we skip this module file?
417e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
418e41d7feaSDouglas Gregor       continue;
419e41d7feaSDouglas Gregor 
420e41d7feaSDouglas Gregor     // Visit the module.
421e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
422e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
4239a9efbafSBenjamin Kramer     if (!Visitor(*CurrentModule))
424e41d7feaSDouglas Gregor       continue;
425e41d7feaSDouglas Gregor 
426e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
427e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
428e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
429e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
430e41d7feaSDouglas Gregor     do {
431e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
432e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
433e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
434e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
435e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
436e41d7feaSDouglas Gregor            M != MEnd; ++M) {
437e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
438e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
439e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
440e41d7feaSDouglas Gregor         }
441e41d7feaSDouglas Gregor       }
442e41d7feaSDouglas Gregor 
443e97cd90aSDouglas Gregor       if (State->Stack.empty())
444e41d7feaSDouglas Gregor         break;
445e41d7feaSDouglas Gregor 
446e41d7feaSDouglas Gregor       // Pop the next module off the stack.
44725284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
448e41d7feaSDouglas Gregor     } while (true);
449e41d7feaSDouglas Gregor   }
450e97cd90aSDouglas Gregor 
451*baa9b7c3SDavid Blaikie   returnVisitState(std::move(State));
452d44252ecSDouglas Gregor }
453d44252ecSDouglas Gregor 
lookupModuleFile(StringRef FileName,off_t ExpectedSize,time_t ExpectedModTime,Optional<FileEntryRef> & File)4549f151df1SDuncan P. N. Exon Smith bool ModuleManager::lookupModuleFile(StringRef FileName, off_t ExpectedSize,
4557029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4569f151df1SDuncan P. N. Exon Smith                                      Optional<FileEntryRef> &File) {
4579f151df1SDuncan P. N. Exon Smith   File = None;
458946406aeSDuncan P. N. Exon Smith   if (FileName == "-")
4593bd6d7fbSRichard Smith     return false;
4603bd6d7fbSRichard Smith 
46105f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
46205f82ba2SBen Langmuir   // opening the file.
4639f151df1SDuncan P. N. Exon Smith   Optional<FileEntryRef> FileOrErr =
4649f151df1SDuncan P. N. Exon Smith       expectedToOptional(FileMgr.getFileRef(FileName, /*OpenFile=*/true,
4659f151df1SDuncan P. N. Exon Smith                                             /*CacheFailure=*/false));
466946406aeSDuncan P. N. Exon Smith   if (!FileOrErr)
4677029ce1aSDouglas Gregor     return false;
468946406aeSDuncan P. N. Exon Smith 
4698d323d15SHarlan Haskins   File = *FileOrErr;
4707029ce1aSDouglas Gregor 
4717029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
472027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
473027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
474027731d7SBen Langmuir     // it will be destroyed by removeModules.
4757029ce1aSDouglas Gregor     return true;
4767029ce1aSDouglas Gregor 
4777029ce1aSDouglas Gregor   return false;
4787029ce1aSDouglas Gregor }
4797029ce1aSDouglas Gregor 
4809d7c1a2aSDouglas Gregor #ifndef NDEBUG
4819d7c1a2aSDouglas Gregor namespace llvm {
482b7d89107SEugene Zelenko 
4839d7c1a2aSDouglas Gregor   template<>
4849d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
485b7d89107SEugene Zelenko     using NodeRef = ModuleFile *;
486b7d89107SEugene Zelenko     using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
487b7d89107SEugene Zelenko     using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
4889d7c1a2aSDouglas Gregor 
child_beginllvm::GraphTraits489f2187ed3STim Shen     static ChildIteratorType child_begin(NodeRef Node) {
4909d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4919d7c1a2aSDouglas Gregor     }
4929d7c1a2aSDouglas Gregor 
child_endllvm::GraphTraits493f2187ed3STim Shen     static ChildIteratorType child_end(NodeRef Node) {
4949d7c1a2aSDouglas Gregor       return Node->Imports.end();
4959d7c1a2aSDouglas Gregor     }
4969d7c1a2aSDouglas Gregor 
nodes_beginllvm::GraphTraits4979d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
49896a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.begin());
4999d7c1a2aSDouglas Gregor     }
5009d7c1a2aSDouglas Gregor 
nodes_endllvm::GraphTraits5019d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
50296a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.end());
5039d7c1a2aSDouglas Gregor     }
5049d7c1a2aSDouglas Gregor   };
5059d7c1a2aSDouglas Gregor 
5069d7c1a2aSDouglas Gregor   template<>
5079d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits5089d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
5099d7c1a2aSDouglas Gregor         : DefaultDOTGraphTraits(IsSimple) {}
5109d7c1a2aSDouglas Gregor 
renderGraphFromBottomUpllvm::DOTGraphTraits511b7d89107SEugene Zelenko     static bool renderGraphFromBottomUp() { return true; }
5129d7c1a2aSDouglas Gregor 
getNodeLabelllvm::DOTGraphTraits513de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
514beee15e7SBen Langmuir       return M->ModuleName;
5159d7c1a2aSDouglas Gregor     }
5169d7c1a2aSDouglas Gregor   };
517b7d89107SEugene Zelenko 
518b7d89107SEugene Zelenko } // namespace llvm
5199d7c1a2aSDouglas Gregor 
viewGraph()5209d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
5219d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
5229d7c1a2aSDouglas Gregor }
5239d7c1a2aSDouglas Gregor #endif
524