1 //===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ModuleManager class, which manages a set of loaded
11 // modules for the ASTReader.
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"
23 #include "llvm/Support/GraphWriter.h"
26 using namespace clang;
27 using namespace serialization;
29 ModuleFile *ModuleManager::lookup(StringRef Name) {
30 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
31 /*cacheFailure=*/false);
38 ModuleFile *ModuleManager::lookup(const FileEntry *File) {
39 llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
41 if (Known == Modules.end())
47 llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
48 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
49 /*cacheFailure=*/false);
50 return InMemoryBuffers[Entry];
53 ModuleManager::AddModuleResult
54 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
55 SourceLocation ImportLoc, ModuleFile *ImportedBy,
57 off_t ExpectedSize, time_t ExpectedModTime,
59 std::string &ErrorStr) {
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))
68 if (!Entry && FileName != "-") {
69 ErrorStr = "file not found";
73 // Check whether we already loaded this module, before
74 ModuleFile *&ModuleEntry = Modules[Entry];
75 bool NewModule = false;
77 // Allocate a new module.
78 ModuleFile *New = new ModuleFile(Type, Generation);
79 New->Index = Chain.size();
80 New->FileName = FileName.str();
82 New->ImportLoc = ImportLoc;
87 // Load the contents of the module
88 if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
89 // The buffer was already provided for us.
90 assert(Buffer && "Passed null buffer");
91 New->Buffer.reset(Buffer);
95 if (FileName == "-") {
96 ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
98 ErrorStr = ec.message();
100 New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
106 // Initialize the stream
107 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
108 (const unsigned char *)New->Buffer->getBufferEnd());
112 ModuleEntry->ImportedBy.insert(ImportedBy);
113 ImportedBy->Imports.insert(ModuleEntry);
115 if (!ModuleEntry->DirectlyImported)
116 ModuleEntry->ImportLoc = ImportLoc;
118 ModuleEntry->DirectlyImported = true;
121 Module = ModuleEntry;
122 return NewModule? NewlyLoaded : AlreadyLoaded;
126 /// \brief Predicate that checks whether a module file occurs within
128 class IsInModuleFileSet : public std::unary_function<ModuleFile *, bool> {
129 llvm::SmallPtrSet<ModuleFile *, 4> &Removed;
132 IsInModuleFileSet(llvm::SmallPtrSet<ModuleFile *, 4> &Removed)
133 : Removed(Removed) { }
135 bool operator()(ModuleFile *MF) const {
136 return Removed.count(MF);
141 void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
146 // Collect the set of module file pointers that we'll be removing.
147 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
149 // Remove any references to the now-destroyed modules.
150 IsInModuleFileSet checkInSet(victimSet);
151 for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
152 Chain[i]->ImportedBy.remove_if(checkInSet);
155 // Delete the modules and erase them from the various structures.
156 for (ModuleIterator victim = first; victim != last; ++victim) {
157 Modules.erase((*victim)->File);
159 FileMgr.invalidateCache((*victim)->File);
161 StringRef ModuleName = llvm::sys::path::stem((*victim)->FileName);
162 if (Module *mod = modMap->findModule(ModuleName)) {
169 // Remove the modules from the chain.
170 Chain.erase(first, last);
173 void ModuleManager::addInMemoryBuffer(StringRef FileName,
174 llvm::MemoryBuffer *Buffer) {
176 const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
177 Buffer->getBufferSize(), 0);
178 InMemoryBuffers[Entry] = Buffer;
181 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
182 // Fast path: if we have a cached state, use it.
183 if (FirstVisitState) {
184 VisitState *Result = FirstVisitState;
185 FirstVisitState = FirstVisitState->NextState;
186 Result->NextState = 0;
190 // Allocate and return a new state.
191 return new VisitState(size());
194 void ModuleManager::returnVisitState(VisitState *State) {
195 assert(State->NextState == 0 && "Visited state is in list?");
196 State->NextState = FirstVisitState;
197 FirstVisitState = State;
200 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
203 ModulesInCommonWithGlobalIndex.clear();
207 // Notify the global module index about all of the modules we've already
209 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
210 if (!GlobalIndex->loadedModuleFile(Chain[I])) {
211 ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
216 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
217 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
220 ModulesInCommonWithGlobalIndex.push_back(MF);
223 ModuleManager::ModuleManager(FileManager &FileMgr)
224 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
226 ModuleManager::~ModuleManager() {
227 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
228 delete Chain[e - i - 1];
229 delete FirstVisitState;
233 ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
235 llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
236 // If the visitation order vector is the wrong size, recompute the order.
237 if (VisitOrder.size() != Chain.size()) {
240 VisitOrder.reserve(N);
242 // Record the number of incoming edges for each module. When we
243 // encounter a module with no incoming edges, push it into the queue
244 // to seed the queue.
245 SmallVector<ModuleFile *, 4> Queue;
247 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
248 UnusedIncomingEdges.reserve(size());
249 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
250 if (unsigned Size = (*M)->ImportedBy.size())
251 UnusedIncomingEdges.push_back(Size);
253 UnusedIncomingEdges.push_back(0);
258 // Traverse the graph, making sure to visit a module before visiting any
259 // of its dependencies.
260 unsigned QueueStart = 0;
261 while (QueueStart < Queue.size()) {
262 ModuleFile *CurrentModule = Queue[QueueStart++];
263 VisitOrder.push_back(CurrentModule);
265 // For any module that this module depends on, push it on the
266 // stack (if it hasn't already been marked as visited).
267 for (llvm::SetVector<ModuleFile *>::iterator
268 M = CurrentModule->Imports.begin(),
269 MEnd = CurrentModule->Imports.end();
271 // Remove our current module as an impediment to visiting the
272 // module we depend on. If we were the last unvisited module
273 // that depends on this particular module, push it into the
274 // queue to be visited.
275 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
276 if (NumUnusedEdges && (--NumUnusedEdges == 0))
281 assert(VisitOrder.size() == N && "Visitation order is wrong?");
283 delete FirstVisitState;
287 VisitState *State = allocateVisitState();
288 unsigned VisitNumber = State->NextVisitNumber++;
290 // If the caller has provided us with a hit-set that came from the global
291 // module index, mark every module file in common with the global module
292 // index that is *not* in that set as 'visited'.
293 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
294 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
296 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
297 if (!ModuleFilesHit->count(M))
298 State->VisitNumber[M->Index] = VisitNumber;
302 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
303 ModuleFile *CurrentModule = VisitOrder[I];
304 // Should we skip this module file?
305 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
309 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
310 State->VisitNumber[CurrentModule->Index] = VisitNumber;
311 if (!Visitor(*CurrentModule, UserData))
314 // The visitor has requested that cut off visitation of any
315 // module that the current module depends on. To indicate this
316 // behavior, we mark all of the reachable modules as having been visited.
317 ModuleFile *NextModule = CurrentModule;
319 // For any module that this module depends on, push it on the
320 // stack (if it hasn't already been marked as visited).
321 for (llvm::SetVector<ModuleFile *>::iterator
322 M = NextModule->Imports.begin(),
323 MEnd = NextModule->Imports.end();
325 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
326 State->Stack.push_back(*M);
327 State->VisitNumber[(*M)->Index] = VisitNumber;
331 if (State->Stack.empty())
334 // Pop the next module off the stack.
335 NextModule = State->Stack.back();
336 State->Stack.pop_back();
340 returnVisitState(State);
343 /// \brief Perform a depth-first visit of the current module.
344 static bool visitDepthFirst(ModuleFile &M,
345 bool (*Visitor)(ModuleFile &M, bool Preorder,
348 SmallVectorImpl<bool> &Visited) {
349 // Preorder visitation
350 if (Visitor(M, /*Preorder=*/true, UserData))
354 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
355 IMEnd = M.Imports.end();
357 if (Visited[(*IM)->Index])
359 Visited[(*IM)->Index] = true;
361 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
365 // Postorder visitation
366 return Visitor(M, /*Preorder=*/false, UserData);
369 void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
372 SmallVector<bool, 16> Visited(size(), false);
373 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
374 if (Visited[Chain[I]->Index])
376 Visited[Chain[I]->Index] = true;
378 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
383 bool ModuleManager::lookupModuleFile(StringRef FileName,
385 time_t ExpectedModTime,
386 const FileEntry *&File) {
387 File = FileMgr.getFile(FileName, /*openFile=*/false, /*cacheFailure=*/false);
389 if (!File && FileName != "-") {
393 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
394 (ExpectedModTime && ExpectedModTime != File->getModificationTime())) {
404 struct GraphTraits<ModuleManager> {
405 typedef ModuleFile NodeType;
406 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
407 typedef ModuleManager::ModuleConstIterator nodes_iterator;
409 static ChildIteratorType child_begin(NodeType *Node) {
410 return Node->Imports.begin();
413 static ChildIteratorType child_end(NodeType *Node) {
414 return Node->Imports.end();
417 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
418 return Manager.begin();
421 static nodes_iterator nodes_end(const ModuleManager &Manager) {
422 return Manager.end();
427 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
428 explicit DOTGraphTraits(bool IsSimple = false)
429 : DefaultDOTGraphTraits(IsSimple) { }
431 static bool renderGraphFromBottomUp() {
435 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
436 return llvm::sys::path::stem(M->FileName);
441 void ModuleManager::viewGraph() {
442 llvm::ViewGraph(*this, "Modules");