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