xref: /llvm-project/clang/lib/Serialization/ModuleManager.cpp (revision ca39214f4e9fddf247e880ef9562865be850fce6)
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 0;
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 0;
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 = 0;
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 void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
139                                   ModuleMap *modMap) {
140   if (first == last)
141     return;
142 
143   // Collect the set of module file pointers that we'll be removing.
144   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
145 
146   // Remove any references to the now-destroyed modules.
147   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
148     Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
149       return victimSet.count(MF);
150     });
151   }
152 
153   // Delete the modules and erase them from the various structures.
154   for (ModuleIterator victim = first; victim != last; ++victim) {
155     const FileEntry *F = (*victim)->File;
156     Modules.erase(F);
157 
158     // Refresh the stat() information for the module file so stale information
159     // doesn't get stored accidentally.
160     vfs::Status UpdatedStat;
161     if (FileMgr.getNoncachedStatValue(F->getName(), UpdatedStat)) {
162       llvm::report_fatal_error(Twine("module file '") + F->getName() +
163                                "' removed after it has been used");
164     } else {
165       FileMgr.modifyFileEntry(const_cast<FileEntry *>(F), UpdatedStat.getSize(),
166           UpdatedStat.getLastModificationTime().toEpochTime());
167     }
168 
169     if (modMap) {
170       StringRef ModuleName = (*victim)->ModuleName;
171       if (Module *mod = modMap->findModule(ModuleName)) {
172         mod->setASTFile(0);
173       }
174     }
175     delete *victim;
176   }
177 
178   // Remove the modules from the chain.
179   Chain.erase(first, last);
180 }
181 
182 void ModuleManager::addInMemoryBuffer(StringRef FileName,
183                                       llvm::MemoryBuffer *Buffer) {
184 
185   const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
186                                                   Buffer->getBufferSize(), 0);
187   InMemoryBuffers[Entry] = Buffer;
188 }
189 
190 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
191   // Fast path: if we have a cached state, use it.
192   if (FirstVisitState) {
193     VisitState *Result = FirstVisitState;
194     FirstVisitState = FirstVisitState->NextState;
195     Result->NextState = 0;
196     return Result;
197   }
198 
199   // Allocate and return a new state.
200   return new VisitState(size());
201 }
202 
203 void ModuleManager::returnVisitState(VisitState *State) {
204   assert(State->NextState == 0 && "Visited state is in list?");
205   State->NextState = FirstVisitState;
206   FirstVisitState = State;
207 }
208 
209 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
210   GlobalIndex = Index;
211   if (!GlobalIndex) {
212     ModulesInCommonWithGlobalIndex.clear();
213     return;
214   }
215 
216   // Notify the global module index about all of the modules we've already
217   // loaded.
218   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
219     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
220       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
221     }
222   }
223 }
224 
225 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
226   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
227     return;
228 
229   ModulesInCommonWithGlobalIndex.push_back(MF);
230 }
231 
232 ModuleManager::ModuleManager(FileManager &FileMgr)
233   : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
234 
235 ModuleManager::~ModuleManager() {
236   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
237     delete Chain[e - i - 1];
238   delete FirstVisitState;
239 }
240 
241 void
242 ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
243                      void *UserData,
244                      llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
245   // If the visitation order vector is the wrong size, recompute the order.
246   if (VisitOrder.size() != Chain.size()) {
247     unsigned N = size();
248     VisitOrder.clear();
249     VisitOrder.reserve(N);
250 
251     // Record the number of incoming edges for each module. When we
252     // encounter a module with no incoming edges, push it into the queue
253     // to seed the queue.
254     SmallVector<ModuleFile *, 4> Queue;
255     Queue.reserve(N);
256     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
257     UnusedIncomingEdges.reserve(size());
258     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
259       if (unsigned Size = (*M)->ImportedBy.size())
260         UnusedIncomingEdges.push_back(Size);
261       else {
262         UnusedIncomingEdges.push_back(0);
263         Queue.push_back(*M);
264       }
265     }
266 
267     // Traverse the graph, making sure to visit a module before visiting any
268     // of its dependencies.
269     unsigned QueueStart = 0;
270     while (QueueStart < Queue.size()) {
271       ModuleFile *CurrentModule = Queue[QueueStart++];
272       VisitOrder.push_back(CurrentModule);
273 
274       // For any module that this module depends on, push it on the
275       // stack (if it hasn't already been marked as visited).
276       for (llvm::SetVector<ModuleFile *>::iterator
277              M = CurrentModule->Imports.begin(),
278              MEnd = CurrentModule->Imports.end();
279            M != MEnd; ++M) {
280         // Remove our current module as an impediment to visiting the
281         // module we depend on. If we were the last unvisited module
282         // that depends on this particular module, push it into the
283         // queue to be visited.
284         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
285         if (NumUnusedEdges && (--NumUnusedEdges == 0))
286           Queue.push_back(*M);
287       }
288     }
289 
290     assert(VisitOrder.size() == N && "Visitation order is wrong?");
291 
292     delete FirstVisitState;
293     FirstVisitState = 0;
294   }
295 
296   VisitState *State = allocateVisitState();
297   unsigned VisitNumber = State->NextVisitNumber++;
298 
299   // If the caller has provided us with a hit-set that came from the global
300   // module index, mark every module file in common with the global module
301   // index that is *not* in that set as 'visited'.
302   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
303     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
304     {
305       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
306       if (!ModuleFilesHit->count(M))
307         State->VisitNumber[M->Index] = VisitNumber;
308     }
309   }
310 
311   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
312     ModuleFile *CurrentModule = VisitOrder[I];
313     // Should we skip this module file?
314     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
315       continue;
316 
317     // Visit the module.
318     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
319     State->VisitNumber[CurrentModule->Index] = VisitNumber;
320     if (!Visitor(*CurrentModule, UserData))
321       continue;
322 
323     // The visitor has requested that cut off visitation of any
324     // module that the current module depends on. To indicate this
325     // behavior, we mark all of the reachable modules as having been visited.
326     ModuleFile *NextModule = CurrentModule;
327     do {
328       // For any module that this module depends on, push it on the
329       // stack (if it hasn't already been marked as visited).
330       for (llvm::SetVector<ModuleFile *>::iterator
331              M = NextModule->Imports.begin(),
332              MEnd = NextModule->Imports.end();
333            M != MEnd; ++M) {
334         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
335           State->Stack.push_back(*M);
336           State->VisitNumber[(*M)->Index] = VisitNumber;
337         }
338       }
339 
340       if (State->Stack.empty())
341         break;
342 
343       // Pop the next module off the stack.
344       NextModule = State->Stack.pop_back_val();
345     } while (true);
346   }
347 
348   returnVisitState(State);
349 }
350 
351 /// \brief Perform a depth-first visit of the current module.
352 static bool visitDepthFirst(ModuleFile &M,
353                             bool (*Visitor)(ModuleFile &M, bool Preorder,
354                                             void *UserData),
355                             void *UserData,
356                             SmallVectorImpl<bool> &Visited) {
357   // Preorder visitation
358   if (Visitor(M, /*Preorder=*/true, UserData))
359     return true;
360 
361   // Visit children
362   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
363                                             IMEnd = M.Imports.end();
364        IM != IMEnd; ++IM) {
365     if (Visited[(*IM)->Index])
366       continue;
367     Visited[(*IM)->Index] = true;
368 
369     if (visitDepthFirst(**IM, Visitor, UserData, Visited))
370       return true;
371   }
372 
373   // Postorder visitation
374   return Visitor(M, /*Preorder=*/false, UserData);
375 }
376 
377 void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
378                                                     void *UserData),
379                                     void *UserData) {
380   SmallVector<bool, 16> Visited(size(), false);
381   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
382     if (Visited[Chain[I]->Index])
383       continue;
384     Visited[Chain[I]->Index] = true;
385 
386     if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
387       return;
388   }
389 }
390 
391 bool ModuleManager::lookupModuleFile(StringRef FileName,
392                                      off_t ExpectedSize,
393                                      time_t ExpectedModTime,
394                                      const FileEntry *&File) {
395   // Open the file immediately to ensure there is no race between stat'ing and
396   // opening the file.
397   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
398 
399   if (!File && FileName != "-") {
400     return false;
401   }
402 
403   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
404       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
405     // Do not destroy File, as it may be referenced. If we need to rebuild it,
406     // it will be destroyed by removeModules.
407     return true;
408 
409   return false;
410 }
411 
412 #ifndef NDEBUG
413 namespace llvm {
414   template<>
415   struct GraphTraits<ModuleManager> {
416     typedef ModuleFile NodeType;
417     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
418     typedef ModuleManager::ModuleConstIterator nodes_iterator;
419 
420     static ChildIteratorType child_begin(NodeType *Node) {
421       return Node->Imports.begin();
422     }
423 
424     static ChildIteratorType child_end(NodeType *Node) {
425       return Node->Imports.end();
426     }
427 
428     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
429       return Manager.begin();
430     }
431 
432     static nodes_iterator nodes_end(const ModuleManager &Manager) {
433       return Manager.end();
434     }
435   };
436 
437   template<>
438   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
439     explicit DOTGraphTraits(bool IsSimple = false)
440       : DefaultDOTGraphTraits(IsSimple) { }
441 
442     static bool renderGraphFromBottomUp() {
443       return true;
444     }
445 
446     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
447       return M->ModuleName;
448     }
449   };
450 }
451 
452 void ModuleManager::viewGraph() {
453   llvm::ViewGraph(*this, "Modules");
454 }
455 #endif
456