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