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"
15bb165fb0SAdrian Prantl #include "clang/Frontend/PCHContainerOperations.h"
16beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h"
177029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h"
187211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h"
19d44252ecSDouglas Gregor #include "llvm/Support/MemoryBuffer.h"
20552c169eSRafael Espindola #include "llvm/Support/Path.h"
218a8e554aSRafael Espindola #include <system_error>
22d44252ecSDouglas Gregor 
239d7c1a2aSDouglas Gregor #ifndef NDEBUG
249d7c1a2aSDouglas Gregor #include "llvm/Support/GraphWriter.h"
259d7c1a2aSDouglas Gregor #endif
269d7c1a2aSDouglas Gregor 
27d44252ecSDouglas Gregor using namespace clang;
28d44252ecSDouglas Gregor using namespace serialization;
29d44252ecSDouglas Gregor 
30de3ef502SDouglas Gregor ModuleFile *ModuleManager::lookup(StringRef Name) {
31dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
32dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
33bf7fc9c5SDouglas Gregor   if (Entry)
34bf7fc9c5SDouglas Gregor     return lookup(Entry);
35bf7fc9c5SDouglas Gregor 
36a13603a2SCraig Topper   return nullptr;
37bf7fc9c5SDouglas Gregor }
38bf7fc9c5SDouglas Gregor 
39bf7fc9c5SDouglas Gregor ModuleFile *ModuleManager::lookup(const FileEntry *File) {
40bf7fc9c5SDouglas Gregor   llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
41bf7fc9c5SDouglas Gregor     = Modules.find(File);
42bf7fc9c5SDouglas Gregor   if (Known == Modules.end())
43a13603a2SCraig Topper     return nullptr;
44bf7fc9c5SDouglas Gregor 
45bf7fc9c5SDouglas Gregor   return Known->second;
46d44252ecSDouglas Gregor }
47d44252ecSDouglas Gregor 
485cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer>
495cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
50dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
51dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
525cd06f26SRafael Espindola   return std::move(InMemoryBuffers[Entry]);
53d44252ecSDouglas Gregor }
54d44252ecSDouglas Gregor 
557029ce1aSDouglas Gregor ModuleManager::AddModuleResult
56d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
576fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
587029ce1aSDouglas Gregor                          unsigned Generation,
597029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
60487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
6170a1b816SBen Langmuir                          ASTFileSignatureReader ReadSignature,
627029ce1aSDouglas Gregor                          ModuleFile *&Module,
637029ce1aSDouglas Gregor                          std::string &ErrorStr) {
64a13603a2SCraig Topper   Module = nullptr;
657029ce1aSDouglas Gregor 
667029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
677029ce1aSDouglas Gregor   // modification time differ.
687029ce1aSDouglas Gregor   const FileEntry *Entry;
69*11f2a477SManman Ren   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
705b390756SRichard Smith     // If we're not expecting to pull this file out of the module cache, it
715b390756SRichard Smith     // might have a different mtime due to being moved across filesystems in
725b390756SRichard Smith     // a distributed build. The size must still match, though. (As must the
735b390756SRichard Smith     // contents, but we can't check that.)
745b390756SRichard Smith     ExpectedModTime = 0;
755b390756SRichard Smith   }
76c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
77c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
787029ce1aSDouglas Gregor     return OutOfDate;
79c27d0d5eSEli Friedman   }
807029ce1aSDouglas Gregor 
81d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
82c27d0d5eSEli Friedman     ErrorStr = "module file not found";
837029ce1aSDouglas Gregor     return Missing;
84d44252ecSDouglas Gregor   }
85d44252ecSDouglas Gregor 
86d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
87de3ef502SDouglas Gregor   ModuleFile *&ModuleEntry = Modules[Entry];
88d44252ecSDouglas Gregor   bool NewModule = false;
89d44252ecSDouglas Gregor   if (!ModuleEntry) {
90d44252ecSDouglas Gregor     // Allocate a new module.
914fc9f3e8SDouglas Gregor     ModuleFile *New = new ModuleFile(Type, Generation);
92bdb259d2SDouglas Gregor     New->Index = Chain.size();
93d44252ecSDouglas Gregor     New->FileName = FileName.str();
94aedf7144SArgyrios Kyrtzidis     New->File = Entry;
956fb03aeaSDouglas Gregor     New->ImportLoc = ImportLoc;
96d44252ecSDouglas Gregor     Chain.push_back(New);
9733e0f7efSRichard Smith     if (!New->isModule())
9833e0f7efSRichard Smith       PCHChain.push_back(New);
999eff8b14SManuel Klimek     if (!ImportedBy)
1009eff8b14SManuel Klimek       Roots.push_back(New);
101d44252ecSDouglas Gregor     NewModule = true;
102d44252ecSDouglas Gregor     ModuleEntry = New;
103d44252ecSDouglas Gregor 
104f430da4dSDmitri Gribenko     New->InputFilesValidationTimestamp = 0;
105e842a474SRichard Smith     if (New->Kind == MK_ImplicitModule) {
106f430da4dSDmitri Gribenko       std::string TimestampFilename = New->getTimestampFilename();
107c8130a74SBen Langmuir       vfs::Status Status;
108f430da4dSDmitri Gribenko       // A cached stat value would be fine as well.
109f430da4dSDmitri Gribenko       if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
110f430da4dSDmitri Gribenko         New->InputFilesValidationTimestamp =
111f430da4dSDmitri Gribenko             Status.getLastModificationTime().toEpochTime();
112f430da4dSDmitri Gribenko     }
113f430da4dSDmitri Gribenko 
114d44252ecSDouglas Gregor     // Load the contents of the module
1155cd06f26SRafael Espindola     if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
116d44252ecSDouglas Gregor       // The buffer was already provided for us.
1175cd06f26SRafael Espindola       New->Buffer = std::move(Buffer);
118d44252ecSDouglas Gregor     } else {
119d44252ecSDouglas Gregor       // Open the AST file.
120a885796dSBenjamin Kramer       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf(
121a885796dSBenjamin Kramer           (std::error_code()));
122d44252ecSDouglas Gregor       if (FileName == "-") {
123a885796dSBenjamin Kramer         Buf = llvm::MemoryBuffer::getSTDIN();
1249801b253SBen Langmuir       } else {
1259801b253SBen Langmuir         // Leave the FileEntry open so if it gets read again by another
1269801b253SBen Langmuir         // ModuleManager it must be the same underlying file.
1279801b253SBen Langmuir         // FIXME: Because FileManager::getFile() doesn't guarantee that it will
1289801b253SBen Langmuir         // give us an open file, this may not be 100% reliable.
129a885796dSBenjamin Kramer         Buf = FileMgr.getBufferForFile(New->File,
130a885796dSBenjamin Kramer                                        /*IsVolatile=*/false,
131a885796dSBenjamin Kramer                                        /*ShouldClose=*/false);
1329801b253SBen Langmuir       }
133d44252ecSDouglas Gregor 
134a885796dSBenjamin Kramer       if (!Buf) {
135a885796dSBenjamin Kramer         ErrorStr = Buf.getError().message();
1367029ce1aSDouglas Gregor         return Missing;
137d44252ecSDouglas Gregor       }
138d44252ecSDouglas Gregor 
139a885796dSBenjamin Kramer       New->Buffer = std::move(*Buf);
140a885796dSBenjamin Kramer     }
141a885796dSBenjamin Kramer 
142bb165fb0SAdrian Prantl     // Initialize the stream.
143fb2398d0SAdrian Prantl     PCHContainerRdr.ExtractPCH(New->Buffer->getMemBufferRef(), New->StreamFile);
144ed982584SBen Langmuir   }
145487ea14aSBen Langmuir 
146487ea14aSBen Langmuir   if (ExpectedSignature) {
147ed982584SBen Langmuir     if (NewModule)
148ed982584SBen Langmuir       ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);
149ed982584SBen Langmuir     else
150ed982584SBen Langmuir       assert(ModuleEntry->Signature == ReadSignature(ModuleEntry->StreamFile));
151ed982584SBen Langmuir 
152ed982584SBen Langmuir     if (ModuleEntry->Signature != ExpectedSignature) {
153ed982584SBen Langmuir       ErrorStr = ModuleEntry->Signature ? "signature mismatch"
154487ea14aSBen Langmuir                                         : "could not read module signature";
155487ea14aSBen Langmuir 
156ed982584SBen Langmuir       if (NewModule) {
157487ea14aSBen Langmuir         // Remove the module file immediately, since removeModules might try to
158487ea14aSBen Langmuir         // invalidate the file cache for Entry, and that is not safe if this
159487ea14aSBen Langmuir         // module is *itself* up to date, but has an out-of-date importer.
160487ea14aSBen Langmuir         Modules.erase(Entry);
1619eff8b14SManuel Klimek         assert(Chain.back() == ModuleEntry);
162487ea14aSBen Langmuir         Chain.pop_back();
16333e0f7efSRichard Smith         if (!ModuleEntry->isModule())
16433e0f7efSRichard Smith           PCHChain.pop_back();
1659eff8b14SManuel Klimek         if (Roots.back() == ModuleEntry)
1669eff8b14SManuel Klimek           Roots.pop_back();
1679eff8b14SManuel Klimek         else
1689eff8b14SManuel Klimek           assert(ImportedBy);
169ed982584SBen Langmuir         delete ModuleEntry;
170487ea14aSBen Langmuir       }
171ed982584SBen Langmuir       return OutOfDate;
172487ea14aSBen Langmuir     }
1737029ce1aSDouglas Gregor   }
174d44252ecSDouglas Gregor 
175d44252ecSDouglas Gregor   if (ImportedBy) {
176d44252ecSDouglas Gregor     ModuleEntry->ImportedBy.insert(ImportedBy);
177d44252ecSDouglas Gregor     ImportedBy->Imports.insert(ModuleEntry);
178d44252ecSDouglas Gregor   } else {
1796fb03aeaSDouglas Gregor     if (!ModuleEntry->DirectlyImported)
1806fb03aeaSDouglas Gregor       ModuleEntry->ImportLoc = ImportLoc;
1816fb03aeaSDouglas Gregor 
182d44252ecSDouglas Gregor     ModuleEntry->DirectlyImported = true;
183d44252ecSDouglas Gregor   }
184d44252ecSDouglas Gregor 
1857029ce1aSDouglas Gregor   Module = ModuleEntry;
1867029ce1aSDouglas Gregor   return NewModule? NewlyLoaded : AlreadyLoaded;
187d44252ecSDouglas Gregor }
188d44252ecSDouglas Gregor 
1899801b253SBen Langmuir void ModuleManager::removeModules(
1909801b253SBen Langmuir     ModuleIterator first, ModuleIterator last,
1919801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
1927029ce1aSDouglas Gregor     ModuleMap *modMap) {
193188dbef2SDouglas Gregor   if (first == last)
194188dbef2SDouglas Gregor     return;
195188dbef2SDouglas Gregor 
196a50dbb20SBen Langmuir   // Explicitly clear VisitOrder since we might not notice it is stale.
197a50dbb20SBen Langmuir   VisitOrder.clear();
198a50dbb20SBen Langmuir 
199188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
200188dbef2SDouglas Gregor   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
201188dbef2SDouglas Gregor 
2029eff8b14SManuel Klimek   auto IsVictim = [&](ModuleFile *MF) {
2039eff8b14SManuel Klimek     return victimSet.count(MF);
2049eff8b14SManuel Klimek   };
205188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
206188dbef2SDouglas Gregor   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
2079eff8b14SManuel Klimek     Chain[i]->ImportedBy.remove_if(IsVictim);
208188dbef2SDouglas Gregor   }
2099eff8b14SManuel Klimek   Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
2109eff8b14SManuel Klimek               Roots.end());
211188dbef2SDouglas Gregor 
21216fe4d17SRichard Smith   // Remove the modules from the PCH chain.
21316fe4d17SRichard Smith   for (auto I = first; I != last; ++I) {
21416fe4d17SRichard Smith     if (!(*I)->isModule()) {
21516fe4d17SRichard Smith       PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), *I),
21616fe4d17SRichard Smith                      PCHChain.end());
21716fe4d17SRichard Smith       break;
21816fe4d17SRichard Smith     }
21916fe4d17SRichard Smith   }
22016fe4d17SRichard Smith 
221188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
222188dbef2SDouglas Gregor   for (ModuleIterator victim = first; victim != last; ++victim) {
223caea1318SBen Langmuir     Modules.erase((*victim)->File);
224ca39214fSBen Langmuir 
2257029ce1aSDouglas Gregor     if (modMap) {
226beee15e7SBen Langmuir       StringRef ModuleName = (*victim)->ModuleName;
2277029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
228a13603a2SCraig Topper         mod->setASTFile(nullptr);
2297029ce1aSDouglas Gregor       }
2307029ce1aSDouglas Gregor     }
2314f05478cSBen Langmuir 
2329801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
2339801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
2349801b253SBen Langmuir     // new files that will be renamed over the old ones.
2359801b253SBen Langmuir     if (LoadedSuccessfully.count(*victim) == 0)
2364f05478cSBen Langmuir       FileMgr.invalidateCache((*victim)->File);
2374f05478cSBen Langmuir 
238188dbef2SDouglas Gregor     delete *victim;
239188dbef2SDouglas Gregor   }
240188dbef2SDouglas Gregor 
241188dbef2SDouglas Gregor   // Remove the modules from the chain.
242188dbef2SDouglas Gregor   Chain.erase(first, last);
243188dbef2SDouglas Gregor }
244188dbef2SDouglas Gregor 
2455cd06f26SRafael Espindola void
2465cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
2475cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
248d44252ecSDouglas Gregor 
2495cd06f26SRafael Espindola   const FileEntry *Entry =
2505cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
2515cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
252d44252ecSDouglas Gregor }
253d44252ecSDouglas Gregor 
254e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
255e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
256e97cd90aSDouglas Gregor   if (FirstVisitState) {
257e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
258e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
259a13603a2SCraig Topper     Result->NextState = nullptr;
260e97cd90aSDouglas Gregor     return Result;
261e97cd90aSDouglas Gregor   }
262e97cd90aSDouglas Gregor 
263e97cd90aSDouglas Gregor   // Allocate and return a new state.
264e97cd90aSDouglas Gregor   return new VisitState(size());
265e97cd90aSDouglas Gregor }
266e97cd90aSDouglas Gregor 
267e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
268a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
269e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
270e97cd90aSDouglas Gregor   FirstVisitState = State;
271e97cd90aSDouglas Gregor }
272e97cd90aSDouglas Gregor 
2737211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
2747211ac15SDouglas Gregor   GlobalIndex = Index;
275603cd869SDouglas Gregor   if (!GlobalIndex) {
276603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
277603cd869SDouglas Gregor     return;
2787029ce1aSDouglas Gregor   }
279603cd869SDouglas Gregor 
280603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
281603cd869SDouglas Gregor   // loaded.
282603cd869SDouglas Gregor   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
283603cd869SDouglas Gregor     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
284603cd869SDouglas Gregor       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
285603cd869SDouglas Gregor     }
286603cd869SDouglas Gregor   }
287603cd869SDouglas Gregor }
288603cd869SDouglas Gregor 
289603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
290603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
291603cd869SDouglas Gregor     return;
292603cd869SDouglas Gregor 
293603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
2947211ac15SDouglas Gregor }
2957211ac15SDouglas Gregor 
296bb165fb0SAdrian Prantl ModuleManager::ModuleManager(FileManager &FileMgr,
297fb2398d0SAdrian Prantl                              const PCHContainerReader &PCHContainerRdr)
298fb2398d0SAdrian Prantl     : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),
299bb165fb0SAdrian Prantl       FirstVisitState(nullptr) {}
300d44252ecSDouglas Gregor 
301d44252ecSDouglas Gregor ModuleManager::~ModuleManager() {
302d44252ecSDouglas Gregor   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
303d44252ecSDouglas Gregor     delete Chain[e - i - 1];
304e97cd90aSDouglas Gregor   delete FirstVisitState;
305d44252ecSDouglas Gregor }
306d44252ecSDouglas Gregor 
3079a9efbafSBenjamin Kramer void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
3084dd9b43cSCraig Topper                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
3097211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
310e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
311d44252ecSDouglas Gregor     unsigned N = size();
312e41d7feaSDouglas Gregor     VisitOrder.clear();
313e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
314d44252ecSDouglas Gregor 
315d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
316d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
317d44252ecSDouglas Gregor     // to seed the queue.
318de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
319d44252ecSDouglas Gregor     Queue.reserve(N);
320bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
321a7c535b3SRichard Smith     UnusedIncomingEdges.resize(size());
322f7e3609fSDavid Majnemer     for (ModuleFile *M : llvm::reverse(*this)) {
323f7e3609fSDavid Majnemer       unsigned Size = M->ImportedBy.size();
324f7e3609fSDavid Majnemer       UnusedIncomingEdges[M->Index] = Size;
325a7c535b3SRichard Smith       if (!Size)
326f7e3609fSDavid Majnemer         Queue.push_back(M);
327d44252ecSDouglas Gregor     }
328d44252ecSDouglas Gregor 
329e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
330e41d7feaSDouglas Gregor     // of its dependencies.
331a7c535b3SRichard Smith     while (!Queue.empty()) {
332a7c535b3SRichard Smith       ModuleFile *CurrentModule = Queue.pop_back_val();
333e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
334d44252ecSDouglas Gregor 
335d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
336d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
337a7c535b3SRichard Smith       for (auto M = CurrentModule->Imports.rbegin(),
338a7c535b3SRichard Smith                 MEnd = CurrentModule->Imports.rend();
339d44252ecSDouglas Gregor            M != MEnd; ++M) {
340d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
341d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
342d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
343d44252ecSDouglas Gregor         // queue to be visited.
344bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
345d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
346d44252ecSDouglas Gregor           Queue.push_back(*M);
347d44252ecSDouglas Gregor       }
348d44252ecSDouglas Gregor     }
349e41d7feaSDouglas Gregor 
350e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3517211ac15SDouglas Gregor 
352e97cd90aSDouglas Gregor     delete FirstVisitState;
353a13603a2SCraig Topper     FirstVisitState = nullptr;
354e41d7feaSDouglas Gregor   }
355e41d7feaSDouglas Gregor 
356e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
357e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
358e41d7feaSDouglas Gregor 
3597211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3607211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3617211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3627211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3637211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3647211ac15SDouglas Gregor     {
3657211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3667029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
367e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
3687211ac15SDouglas Gregor     }
3697211ac15SDouglas Gregor   }
3707211ac15SDouglas Gregor 
371e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
372e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
373e41d7feaSDouglas Gregor     // Should we skip this module file?
374e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
375e41d7feaSDouglas Gregor       continue;
376e41d7feaSDouglas Gregor 
377e41d7feaSDouglas Gregor     // Visit the module.
378e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
379e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
3809a9efbafSBenjamin Kramer     if (!Visitor(*CurrentModule))
381e41d7feaSDouglas Gregor       continue;
382e41d7feaSDouglas Gregor 
383e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
384e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
385e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
386e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
387e41d7feaSDouglas Gregor     do {
388e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
389e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
390e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
391e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
392e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
393e41d7feaSDouglas Gregor            M != MEnd; ++M) {
394e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
395e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
396e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
397e41d7feaSDouglas Gregor         }
398e41d7feaSDouglas Gregor       }
399e41d7feaSDouglas Gregor 
400e97cd90aSDouglas Gregor       if (State->Stack.empty())
401e41d7feaSDouglas Gregor         break;
402e41d7feaSDouglas Gregor 
403e41d7feaSDouglas Gregor       // Pop the next module off the stack.
40425284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
405e41d7feaSDouglas Gregor     } while (true);
406e41d7feaSDouglas Gregor   }
407e97cd90aSDouglas Gregor 
408e97cd90aSDouglas Gregor   returnVisitState(State);
409d44252ecSDouglas Gregor }
410d44252ecSDouglas Gregor 
4117029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4127029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4137029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4147029ce1aSDouglas Gregor                                      const FileEntry *&File) {
41505f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
41605f82ba2SBen Langmuir   // opening the file.
41705f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4187029ce1aSDouglas Gregor 
4197029ce1aSDouglas Gregor   if (!File && FileName != "-") {
4207029ce1aSDouglas Gregor     return false;
4217029ce1aSDouglas Gregor   }
4227029ce1aSDouglas Gregor 
4237029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
424027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
425027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
426027731d7SBen Langmuir     // it will be destroyed by removeModules.
4277029ce1aSDouglas Gregor     return true;
4287029ce1aSDouglas Gregor 
4297029ce1aSDouglas Gregor   return false;
4307029ce1aSDouglas Gregor }
4317029ce1aSDouglas Gregor 
4329d7c1a2aSDouglas Gregor #ifndef NDEBUG
4339d7c1a2aSDouglas Gregor namespace llvm {
4349d7c1a2aSDouglas Gregor   template<>
4359d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
436de3ef502SDouglas Gregor     typedef ModuleFile NodeType;
4372931d171STim Shen     typedef ModuleFile *NodeRef;
438de3ef502SDouglas Gregor     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
4399d7c1a2aSDouglas Gregor     typedef ModuleManager::ModuleConstIterator nodes_iterator;
4409d7c1a2aSDouglas Gregor 
4419d7c1a2aSDouglas Gregor     static ChildIteratorType child_begin(NodeType *Node) {
4429d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4439d7c1a2aSDouglas Gregor     }
4449d7c1a2aSDouglas Gregor 
4459d7c1a2aSDouglas Gregor     static ChildIteratorType child_end(NodeType *Node) {
4469d7c1a2aSDouglas Gregor       return Node->Imports.end();
4479d7c1a2aSDouglas Gregor     }
4489d7c1a2aSDouglas Gregor 
4499d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
4509d7c1a2aSDouglas Gregor       return Manager.begin();
4519d7c1a2aSDouglas Gregor     }
4529d7c1a2aSDouglas Gregor 
4539d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
4549d7c1a2aSDouglas Gregor       return Manager.end();
4559d7c1a2aSDouglas Gregor     }
4569d7c1a2aSDouglas Gregor   };
4579d7c1a2aSDouglas Gregor 
4589d7c1a2aSDouglas Gregor   template<>
4599d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
4609d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
4619d7c1a2aSDouglas Gregor       : DefaultDOTGraphTraits(IsSimple) { }
4629d7c1a2aSDouglas Gregor 
4639d7c1a2aSDouglas Gregor     static bool renderGraphFromBottomUp() {
4649d7c1a2aSDouglas Gregor       return true;
4659d7c1a2aSDouglas Gregor     }
4669d7c1a2aSDouglas Gregor 
467de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
468beee15e7SBen Langmuir       return M->ModuleName;
4699d7c1a2aSDouglas Gregor     }
4709d7c1a2aSDouglas Gregor   };
471ab9db510SAlexander Kornienko }
4729d7c1a2aSDouglas Gregor 
4739d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
4749d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
4759d7c1a2aSDouglas Gregor }
4769d7c1a2aSDouglas Gregor #endif
477