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