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