blob: 201f8fadea617d602b2b62ff2e094b8eb3d53018 [file] [log] [blame]
Douglas Gregord44252e2011-08-25 20:47:51 +00001//===--- 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//===----------------------------------------------------------------------===//
Douglas Gregor7029ce12013-03-19 00:28:20 +000014#include "clang/Lex/ModuleMap.h"
Douglas Gregor7211ac12013-01-25 23:32:03 +000015#include "clang/Serialization/GlobalModuleIndex.h"
Benjamin Krameraf04f982013-08-24 13:16:22 +000016#include "clang/Serialization/ModuleManager.h"
Douglas Gregord44252e2011-08-25 20:47:51 +000017#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000018#include "llvm/Support/Path.h"
Douglas Gregord44252e2011-08-25 20:47:51 +000019#include "llvm/Support/raw_ostream.h"
20#include "llvm/Support/system_error.h"
21
Douglas Gregor9d7c1a22011-10-11 19:27:55 +000022#ifndef NDEBUG
23#include "llvm/Support/GraphWriter.h"
24#endif
25
Douglas Gregord44252e2011-08-25 20:47:51 +000026using namespace clang;
27using namespace serialization;
28
Douglas Gregorde3ef502011-11-30 23:21:26 +000029ModuleFile *ModuleManager::lookup(StringRef Name) {
Douglas Gregordadd85d2013-02-08 21:27:45 +000030 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
31 /*cacheFailure=*/false);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000032 if (Entry)
33 return lookup(Entry);
34
35 return 0;
36}
37
38ModuleFile *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;
Douglas Gregord44252e2011-08-25 20:47:51 +000045}
46
47llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
Douglas Gregordadd85d2013-02-08 21:27:45 +000048 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
49 /*cacheFailure=*/false);
Douglas Gregord44252e2011-08-25 20:47:51 +000050 return InMemoryBuffers[Entry];
51}
52
Douglas Gregor7029ce12013-03-19 00:28:20 +000053ModuleManager::AddModuleResult
Douglas Gregor6fb03ae2012-11-30 19:28:05 +000054ModuleManager::addModule(StringRef FileName, ModuleKind Type,
55 SourceLocation ImportLoc, ModuleFile *ImportedBy,
Douglas Gregor7029ce12013-03-19 00:28:20 +000056 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;
Eli Friedmanc27d0d52013-09-05 23:50:58 +000065 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
66 ErrorStr = "module file out of date";
Douglas Gregor7029ce12013-03-19 00:28:20 +000067 return OutOfDate;
Eli Friedmanc27d0d52013-09-05 23:50:58 +000068 }
Douglas Gregor7029ce12013-03-19 00:28:20 +000069
Douglas Gregord44252e2011-08-25 20:47:51 +000070 if (!Entry && FileName != "-") {
Eli Friedmanc27d0d52013-09-05 23:50:58 +000071 ErrorStr = "module file not found";
Douglas Gregor7029ce12013-03-19 00:28:20 +000072 return Missing;
Douglas Gregord44252e2011-08-25 20:47:51 +000073 }
Douglas Gregor7029ce12013-03-19 00:28:20 +000074
75 // Check whether we already loaded this module, before
Douglas Gregorde3ef502011-11-30 23:21:26 +000076 ModuleFile *&ModuleEntry = Modules[Entry];
Douglas Gregord44252e2011-08-25 20:47:51 +000077 bool NewModule = false;
78 if (!ModuleEntry) {
79 // Allocate a new module.
Douglas Gregor4fc9f3e2012-01-18 20:56:22 +000080 ModuleFile *New = new ModuleFile(Type, Generation);
Douglas Gregorbdb259d2013-01-21 20:07:12 +000081 New->Index = Chain.size();
Douglas Gregord44252e2011-08-25 20:47:51 +000082 New->FileName = FileName.str();
Argyrios Kyrtzidisaedf7142012-10-03 01:58:42 +000083 New->File = Entry;
Douglas Gregor6fb03ae2012-11-30 19:28:05 +000084 New->ImportLoc = ImportLoc;
Douglas Gregord44252e2011-08-25 20:47:51 +000085 Chain.push_back(New);
86 NewModule = true;
87 ModuleEntry = New;
Douglas Gregor6fb03ae2012-11-30 19:28:05 +000088
Dmitri Gribenkof430da42014-02-12 10:33:14 +000089 New->InputFilesValidationTimestamp = 0;
90 if (New->Kind == MK_Module) {
91 std::string TimestampFilename = New->getTimestampFilename();
Ben Langmuirc8130a72014-02-20 21:59:23 +000092 vfs::Status Status;
Dmitri Gribenkof430da42014-02-12 10:33:14 +000093 // A cached stat value would be fine as well.
94 if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
95 New->InputFilesValidationTimestamp =
96 Status.getLastModificationTime().toEpochTime();
97 }
98
Douglas Gregord44252e2011-08-25 20:47:51 +000099 // 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)
Douglas Gregor7029ce12013-03-19 00:28:20 +0000115 return Missing;
Douglas Gregord44252e2011-08-25 20:47:51 +0000116 }
117
118 // Initialize the stream
119 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
Douglas Gregor7029ce12013-03-19 00:28:20 +0000120 (const unsigned char *)New->Buffer->getBufferEnd());
Douglas Gregor7029ce12013-03-19 00:28:20 +0000121 }
Douglas Gregord44252e2011-08-25 20:47:51 +0000122
123 if (ImportedBy) {
124 ModuleEntry->ImportedBy.insert(ImportedBy);
125 ImportedBy->Imports.insert(ModuleEntry);
126 } else {
Douglas Gregor6fb03ae2012-11-30 19:28:05 +0000127 if (!ModuleEntry->DirectlyImported)
128 ModuleEntry->ImportLoc = ImportLoc;
129
Douglas Gregord44252e2011-08-25 20:47:51 +0000130 ModuleEntry->DirectlyImported = true;
131 }
Douglas Gregor7029ce12013-03-19 00:28:20 +0000132
133 Module = ModuleEntry;
134 return NewModule? NewlyLoaded : AlreadyLoaded;
Douglas Gregord44252e2011-08-25 20:47:51 +0000135}
136
Douglas Gregor7029ce12013-03-19 00:28:20 +0000137void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
138 ModuleMap *modMap) {
Douglas Gregor188dbef2012-11-07 17:46:15 +0000139 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.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +0000146 std::function<bool(ModuleFile *)> checkInSet = [&](ModuleFile *MF) {
147 return victimSet.count(MF);
148 };
Douglas Gregor188dbef2012-11-07 17:46:15 +0000149 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);
Douglas Gregor7029ce12013-03-19 00:28:20 +0000156
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 }
Douglas Gregor188dbef2012-11-07 17:46:15 +0000164 delete *victim;
165 }
166
167 // Remove the modules from the chain.
168 Chain.erase(first, last);
169}
170
Douglas Gregord44252e2011-08-25 20:47:51 +0000171void 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
Douglas Gregore97cd902013-01-28 16:46:33 +0000179ModuleManager::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
192void ModuleManager::returnVisitState(VisitState *State) {
193 assert(State->NextState == 0 && "Visited state is in list?");
194 State->NextState = FirstVisitState;
195 FirstVisitState = State;
196}
197
Douglas Gregor7211ac12013-01-25 23:32:03 +0000198void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
199 GlobalIndex = Index;
Douglas Gregor603cd862013-03-22 18:50:14 +0000200 if (!GlobalIndex) {
201 ModulesInCommonWithGlobalIndex.clear();
202 return;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000203 }
Douglas Gregor603cd862013-03-22 18:50:14 +0000204
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
214void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
215 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
216 return;
217
218 ModulesInCommonWithGlobalIndex.push_back(MF);
Douglas Gregor7211ac12013-01-25 23:32:03 +0000219}
220
221ModuleManager::ModuleManager(FileManager &FileMgr)
Douglas Gregore97cd902013-01-28 16:46:33 +0000222 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
Douglas Gregord44252e2011-08-25 20:47:51 +0000223
224ModuleManager::~ModuleManager() {
225 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
226 delete Chain[e - i - 1];
Douglas Gregore97cd902013-01-28 16:46:33 +0000227 delete FirstVisitState;
Douglas Gregord44252e2011-08-25 20:47:51 +0000228}
229
Douglas Gregor7211ac12013-01-25 23:32:03 +0000230void
231ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
232 void *UserData,
Douglas Gregor7029ce12013-03-19 00:28:20 +0000233 llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
Douglas Gregor7211ac12013-01-25 23:32:03 +0000234 // If the visitation order vector is the wrong size, recompute the order.
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000235 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 }
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000254 }
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000255
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?");
Douglas Gregor7211ac12013-01-25 23:32:03 +0000280
Douglas Gregore97cd902013-01-28 16:46:33 +0000281 delete FirstVisitState;
282 FirstVisitState = 0;
Douglas Gregord44252e2011-08-25 20:47:51 +0000283 }
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000284
Douglas Gregore97cd902013-01-28 16:46:33 +0000285 VisitState *State = allocateVisitState();
286 unsigned VisitNumber = State->NextVisitNumber++;
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000287
Douglas Gregor7211ac12013-01-25 23:32:03 +0000288 // 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];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000295 if (!ModuleFilesHit->count(M))
Douglas Gregore97cd902013-01-28 16:46:33 +0000296 State->VisitNumber[M->Index] = VisitNumber;
Douglas Gregor7211ac12013-01-25 23:32:03 +0000297 }
298 }
299
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000300 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
301 ModuleFile *CurrentModule = VisitOrder[I];
302 // Should we skip this module file?
Douglas Gregore97cd902013-01-28 16:46:33 +0000303 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
Douglas Gregord44252e2011-08-25 20:47:51 +0000304 continue;
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000305
306 // Visit the module.
Douglas Gregore97cd902013-01-28 16:46:33 +0000307 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
308 State->VisitNumber[CurrentModule->Index] = VisitNumber;
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000309 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;
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000316 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) {
Douglas Gregore97cd902013-01-28 16:46:33 +0000323 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
324 State->Stack.push_back(*M);
325 State->VisitNumber[(*M)->Index] = VisitNumber;
Douglas Gregord44252e2011-08-25 20:47:51 +0000326 }
327 }
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000328
Douglas Gregore97cd902013-01-28 16:46:33 +0000329 if (State->Stack.empty())
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000330 break;
331
332 // Pop the next module off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000333 NextModule = State->Stack.pop_back_val();
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000334 } while (true);
Douglas Gregord44252e2011-08-25 20:47:51 +0000335 }
Douglas Gregore97cd902013-01-28 16:46:33 +0000336
337 returnVisitState(State);
Douglas Gregord44252e2011-08-25 20:47:51 +0000338}
339
340/// \brief Perform a depth-first visit of the current module.
Douglas Gregorde3ef502011-11-30 23:21:26 +0000341static bool visitDepthFirst(ModuleFile &M,
342 bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregord44252e2011-08-25 20:47:51 +0000343 void *UserData),
344 void *UserData,
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000345 SmallVectorImpl<bool> &Visited) {
Douglas Gregord44252e2011-08-25 20:47:51 +0000346 // Preorder visitation
347 if (Visitor(M, /*Preorder=*/true, UserData))
348 return true;
349
350 // Visit children
Douglas Gregorde3ef502011-11-30 23:21:26 +0000351 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000352 IMEnd = M.Imports.end();
Douglas Gregord44252e2011-08-25 20:47:51 +0000353 IM != IMEnd; ++IM) {
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000354 if (Visited[(*IM)->Index])
Douglas Gregord44252e2011-08-25 20:47:51 +0000355 continue;
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000356 Visited[(*IM)->Index] = true;
357
Douglas Gregord44252e2011-08-25 20:47:51 +0000358 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
359 return true;
360 }
361
362 // Postorder visitation
363 return Visitor(M, /*Preorder=*/false, UserData);
364}
365
Douglas Gregorde3ef502011-11-30 23:21:26 +0000366void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregord44252e2011-08-25 20:47:51 +0000367 void *UserData),
368 void *UserData) {
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000369 SmallVector<bool, 16> Visited(size(), false);
Douglas Gregord44252e2011-08-25 20:47:51 +0000370 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000371 if (Visited[Chain[I]->Index])
Douglas Gregord44252e2011-08-25 20:47:51 +0000372 continue;
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000373 Visited[Chain[I]->Index] = true;
374
Douglas Gregord44252e2011-08-25 20:47:51 +0000375 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
376 return;
377 }
378}
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000379
Douglas Gregor7029ce12013-03-19 00:28:20 +0000380bool 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
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000398#ifndef NDEBUG
399namespace llvm {
400 template<>
401 struct GraphTraits<ModuleManager> {
Douglas Gregorde3ef502011-11-30 23:21:26 +0000402 typedef ModuleFile NodeType;
403 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000404 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
Douglas Gregorde3ef502011-11-30 23:21:26 +0000432 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000433 return llvm::sys::path::stem(M->FileName);
434 }
435 };
436}
437
438void ModuleManager::viewGraph() {
439 llvm::ViewGraph(*this, "Modules");
440}
441#endif