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