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