1 //===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ModuleManager class, which manages a set of loaded
11 //  modules for the ASTReader.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/HeaderSearch.h"
15 #include "clang/Lex/ModuleMap.h"
16 #include "clang/Serialization/ASTReader.h"
17 #include "clang/Serialization/GlobalModuleIndex.h"
18 #include "clang/Serialization/ModuleManager.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <system_error>
23 
24 #ifndef NDEBUG
25 #include "llvm/Support/GraphWriter.h"
26 #endif
27 
28 using namespace clang;
29 using namespace serialization;
30 
31 ModuleFile *ModuleManager::lookup(StringRef Name) {
32   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
33                                            /*cacheFailure=*/false);
34   if (Entry)
35     return lookup(Entry);
36 
37   return nullptr;
38 }
39 
40 ModuleFile *ModuleManager::lookup(const FileEntry *File) {
41   llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
42     = Modules.find(File);
43   if (Known == Modules.end())
44     return nullptr;
45 
46   return Known->second;
47 }
48 
49 std::unique_ptr<llvm::MemoryBuffer>
50 ModuleManager::lookupBuffer(StringRef Name) {
51   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
52                                            /*cacheFailure=*/false);
53   return std::move(InMemoryBuffers[Entry]);
54 }
55 
56 ModuleManager::AddModuleResult
57 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
58                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
59                          unsigned Generation,
60                          off_t ExpectedSize, time_t ExpectedModTime,
61                          ASTFileSignature ExpectedSignature,
62                          std::function<ASTFileSignature(llvm::BitstreamReader &)>
63                              ReadSignature,
64                          ModuleFile *&Module,
65                          std::string &ErrorStr) {
66   Module = nullptr;
67 
68   // Look for the file entry. This only fails if the expected size or
69   // modification time differ.
70   const FileEntry *Entry;
71   if (Type == MK_ExplicitModule) {
72     // If we're not expecting to pull this file out of the module cache, it
73     // might have a different mtime due to being moved across filesystems in
74     // a distributed build. The size must still match, though. (As must the
75     // contents, but we can't check that.)
76     ExpectedModTime = 0;
77   }
78   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
79     ErrorStr = "module file out of date";
80     return OutOfDate;
81   }
82 
83   if (!Entry && FileName != "-") {
84     ErrorStr = "module file not found";
85     return Missing;
86   }
87 
88   // Check whether we already loaded this module, before
89   ModuleFile *&ModuleEntry = Modules[Entry];
90   bool NewModule = false;
91   if (!ModuleEntry) {
92     // Allocate a new module.
93     ModuleFile *New = new ModuleFile(Type, Generation);
94     New->Index = Chain.size();
95     New->FileName = FileName.str();
96     New->File = Entry;
97     New->ImportLoc = ImportLoc;
98     Chain.push_back(New);
99     NewModule = true;
100     ModuleEntry = New;
101 
102     New->InputFilesValidationTimestamp = 0;
103     if (New->Kind == MK_ImplicitModule) {
104       std::string TimestampFilename = New->getTimestampFilename();
105       vfs::Status Status;
106       // A cached stat value would be fine as well.
107       if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
108         New->InputFilesValidationTimestamp =
109             Status.getLastModificationTime().toEpochTime();
110     }
111 
112     // Load the contents of the module
113     if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
114       // The buffer was already provided for us.
115       New->Buffer = std::move(Buffer);
116     } else {
117       // Open the AST file.
118       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf(
119           (std::error_code()));
120       if (FileName == "-") {
121         Buf = llvm::MemoryBuffer::getSTDIN();
122       } else {
123         // Leave the FileEntry open so if it gets read again by another
124         // ModuleManager it must be the same underlying file.
125         // FIXME: Because FileManager::getFile() doesn't guarantee that it will
126         // give us an open file, this may not be 100% reliable.
127         Buf = FileMgr.getBufferForFile(New->File,
128                                        /*IsVolatile=*/false,
129                                        /*ShouldClose=*/false);
130       }
131 
132       if (!Buf) {
133         ErrorStr = Buf.getError().message();
134         return Missing;
135       }
136 
137       New->Buffer = std::move(*Buf);
138     }
139 
140     // Initialize the stream.
141     ASTReader::InitStreamFileWithModule(New->Buffer->getMemBufferRef(),
142                                         New->StreamFile);
143   }
144 
145   if (ExpectedSignature) {
146     if (NewModule)
147       ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);
148     else
149       assert(ModuleEntry->Signature == ReadSignature(ModuleEntry->StreamFile));
150 
151     if (ModuleEntry->Signature != ExpectedSignature) {
152       ErrorStr = ModuleEntry->Signature ? "signature mismatch"
153                                         : "could not read module signature";
154 
155       if (NewModule) {
156         // Remove the module file immediately, since removeModules might try to
157         // invalidate the file cache for Entry, and that is not safe if this
158         // module is *itself* up to date, but has an out-of-date importer.
159         Modules.erase(Entry);
160         Chain.pop_back();
161         delete ModuleEntry;
162       }
163       return OutOfDate;
164     }
165   }
166 
167   if (ImportedBy) {
168     ModuleEntry->ImportedBy.insert(ImportedBy);
169     ImportedBy->Imports.insert(ModuleEntry);
170   } else {
171     if (!ModuleEntry->DirectlyImported)
172       ModuleEntry->ImportLoc = ImportLoc;
173 
174     ModuleEntry->DirectlyImported = true;
175   }
176 
177   Module = ModuleEntry;
178   return NewModule? NewlyLoaded : AlreadyLoaded;
179 }
180 
181 void ModuleManager::removeModules(
182     ModuleIterator first, ModuleIterator last,
183     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
184     ModuleMap *modMap) {
185   if (first == last)
186     return;
187 
188   // Collect the set of module file pointers that we'll be removing.
189   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
190 
191   // Remove any references to the now-destroyed modules.
192   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
193     Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
194       return victimSet.count(MF);
195     });
196   }
197 
198   // Delete the modules and erase them from the various structures.
199   for (ModuleIterator victim = first; victim != last; ++victim) {
200     Modules.erase((*victim)->File);
201 
202     if (modMap) {
203       StringRef ModuleName = (*victim)->ModuleName;
204       if (Module *mod = modMap->findModule(ModuleName)) {
205         mod->setASTFile(nullptr);
206       }
207     }
208 
209     // Files that didn't make it through ReadASTCore successfully will be
210     // rebuilt (or there was an error). Invalidate them so that we can load the
211     // new files that will be renamed over the old ones.
212     if (LoadedSuccessfully.count(*victim) == 0)
213       FileMgr.invalidateCache((*victim)->File);
214 
215     delete *victim;
216   }
217 
218   // Remove the modules from the chain.
219   Chain.erase(first, last);
220 }
221 
222 void
223 ModuleManager::addInMemoryBuffer(StringRef FileName,
224                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
225 
226   const FileEntry *Entry =
227       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
228   InMemoryBuffers[Entry] = std::move(Buffer);
229 }
230 
231 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
232   // Fast path: if we have a cached state, use it.
233   if (FirstVisitState) {
234     VisitState *Result = FirstVisitState;
235     FirstVisitState = FirstVisitState->NextState;
236     Result->NextState = nullptr;
237     return Result;
238   }
239 
240   // Allocate and return a new state.
241   return new VisitState(size());
242 }
243 
244 void ModuleManager::returnVisitState(VisitState *State) {
245   assert(State->NextState == nullptr && "Visited state is in list?");
246   State->NextState = FirstVisitState;
247   FirstVisitState = State;
248 }
249 
250 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
251   GlobalIndex = Index;
252   if (!GlobalIndex) {
253     ModulesInCommonWithGlobalIndex.clear();
254     return;
255   }
256 
257   // Notify the global module index about all of the modules we've already
258   // loaded.
259   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
260     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
261       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
262     }
263   }
264 }
265 
266 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
267   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
268     return;
269 
270   ModulesInCommonWithGlobalIndex.push_back(MF);
271 }
272 
273 ModuleManager::ModuleManager(FileManager &FileMgr)
274   : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(nullptr) {}
275 
276 ModuleManager::~ModuleManager() {
277   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
278     delete Chain[e - i - 1];
279   delete FirstVisitState;
280 }
281 
282 void
283 ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
284                      void *UserData,
285                      llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
286   // If the visitation order vector is the wrong size, recompute the order.
287   if (VisitOrder.size() != Chain.size()) {
288     unsigned N = size();
289     VisitOrder.clear();
290     VisitOrder.reserve(N);
291 
292     // Record the number of incoming edges for each module. When we
293     // encounter a module with no incoming edges, push it into the queue
294     // to seed the queue.
295     SmallVector<ModuleFile *, 4> Queue;
296     Queue.reserve(N);
297     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
298     UnusedIncomingEdges.reserve(size());
299     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
300       if (unsigned Size = (*M)->ImportedBy.size())
301         UnusedIncomingEdges.push_back(Size);
302       else {
303         UnusedIncomingEdges.push_back(0);
304         Queue.push_back(*M);
305       }
306     }
307 
308     // Traverse the graph, making sure to visit a module before visiting any
309     // of its dependencies.
310     unsigned QueueStart = 0;
311     while (QueueStart < Queue.size()) {
312       ModuleFile *CurrentModule = Queue[QueueStart++];
313       VisitOrder.push_back(CurrentModule);
314 
315       // For any module that this module depends on, push it on the
316       // stack (if it hasn't already been marked as visited).
317       for (llvm::SetVector<ModuleFile *>::iterator
318              M = CurrentModule->Imports.begin(),
319              MEnd = CurrentModule->Imports.end();
320            M != MEnd; ++M) {
321         // Remove our current module as an impediment to visiting the
322         // module we depend on. If we were the last unvisited module
323         // that depends on this particular module, push it into the
324         // queue to be visited.
325         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
326         if (NumUnusedEdges && (--NumUnusedEdges == 0))
327           Queue.push_back(*M);
328       }
329     }
330 
331     assert(VisitOrder.size() == N && "Visitation order is wrong?");
332 
333     delete FirstVisitState;
334     FirstVisitState = nullptr;
335   }
336 
337   VisitState *State = allocateVisitState();
338   unsigned VisitNumber = State->NextVisitNumber++;
339 
340   // If the caller has provided us with a hit-set that came from the global
341   // module index, mark every module file in common with the global module
342   // index that is *not* in that set as 'visited'.
343   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
344     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
345     {
346       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
347       if (!ModuleFilesHit->count(M))
348         State->VisitNumber[M->Index] = VisitNumber;
349     }
350   }
351 
352   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
353     ModuleFile *CurrentModule = VisitOrder[I];
354     // Should we skip this module file?
355     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
356       continue;
357 
358     // Visit the module.
359     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
360     State->VisitNumber[CurrentModule->Index] = VisitNumber;
361     if (!Visitor(*CurrentModule, UserData))
362       continue;
363 
364     // The visitor has requested that cut off visitation of any
365     // module that the current module depends on. To indicate this
366     // behavior, we mark all of the reachable modules as having been visited.
367     ModuleFile *NextModule = CurrentModule;
368     do {
369       // For any module that this module depends on, push it on the
370       // stack (if it hasn't already been marked as visited).
371       for (llvm::SetVector<ModuleFile *>::iterator
372              M = NextModule->Imports.begin(),
373              MEnd = NextModule->Imports.end();
374            M != MEnd; ++M) {
375         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
376           State->Stack.push_back(*M);
377           State->VisitNumber[(*M)->Index] = VisitNumber;
378         }
379       }
380 
381       if (State->Stack.empty())
382         break;
383 
384       // Pop the next module off the stack.
385       NextModule = State->Stack.pop_back_val();
386     } while (true);
387   }
388 
389   returnVisitState(State);
390 }
391 
392 /// \brief Perform a depth-first visit of the current module.
393 static bool visitDepthFirst(ModuleFile &M,
394                             bool (*Visitor)(ModuleFile &M, bool Preorder,
395                                             void *UserData),
396                             void *UserData,
397                             SmallVectorImpl<bool> &Visited) {
398   // Preorder visitation
399   if (Visitor(M, /*Preorder=*/true, UserData))
400     return true;
401 
402   // Visit children
403   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
404                                             IMEnd = M.Imports.end();
405        IM != IMEnd; ++IM) {
406     if (Visited[(*IM)->Index])
407       continue;
408     Visited[(*IM)->Index] = true;
409 
410     if (visitDepthFirst(**IM, Visitor, UserData, Visited))
411       return true;
412   }
413 
414   // Postorder visitation
415   return Visitor(M, /*Preorder=*/false, UserData);
416 }
417 
418 void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
419                                                     void *UserData),
420                                     void *UserData) {
421   SmallVector<bool, 16> Visited(size(), false);
422   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
423     if (Visited[Chain[I]->Index])
424       continue;
425     Visited[Chain[I]->Index] = true;
426 
427     if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
428       return;
429   }
430 }
431 
432 bool ModuleManager::lookupModuleFile(StringRef FileName,
433                                      off_t ExpectedSize,
434                                      time_t ExpectedModTime,
435                                      const FileEntry *&File) {
436   // Open the file immediately to ensure there is no race between stat'ing and
437   // opening the file.
438   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
439 
440   if (!File && FileName != "-") {
441     return false;
442   }
443 
444   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
445       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
446     // Do not destroy File, as it may be referenced. If we need to rebuild it,
447     // it will be destroyed by removeModules.
448     return true;
449 
450   return false;
451 }
452 
453 #ifndef NDEBUG
454 namespace llvm {
455   template<>
456   struct GraphTraits<ModuleManager> {
457     typedef ModuleFile NodeType;
458     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
459     typedef ModuleManager::ModuleConstIterator nodes_iterator;
460 
461     static ChildIteratorType child_begin(NodeType *Node) {
462       return Node->Imports.begin();
463     }
464 
465     static ChildIteratorType child_end(NodeType *Node) {
466       return Node->Imports.end();
467     }
468 
469     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
470       return Manager.begin();
471     }
472 
473     static nodes_iterator nodes_end(const ModuleManager &Manager) {
474       return Manager.end();
475     }
476   };
477 
478   template<>
479   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
480     explicit DOTGraphTraits(bool IsSimple = false)
481       : DefaultDOTGraphTraits(IsSimple) { }
482 
483     static bool renderGraphFromBottomUp() {
484       return true;
485     }
486 
487     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
488       return M->ModuleName;
489     }
490   };
491 }
492 
493 void ModuleManager::viewGraph() {
494   llvm::ViewGraph(*this, "Modules");
495 }
496 #endif
497