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