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