blob: 878ee46382bd7548947e031efb9c9ca7fc9a26a1 [file] [log] [blame]
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001//===- ModuleManager.cpp - Module Manager ---------------------------------===//
Douglas Gregord44252e2011-08-25 20:47:51 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregord44252e2011-08-25 20:47:51 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ModuleManager class, which manages a set of loaded
10// modules for the ASTReader.
11//
12//===----------------------------------------------------------------------===//
Eugene Zelenkob7d89102017-11-11 00:08:50 +000013
Mehdi Amini9670f842016-07-18 19:02:11 +000014#include "clang/Serialization/ModuleManager.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/LLVM.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000017#include "clang/Lex/HeaderSearch.h"
Douglas Gregor7029ce12013-03-19 00:28:20 +000018#include "clang/Lex/ModuleMap.h"
Douglas Gregor7211ac12013-01-25 23:32:03 +000019#include "clang/Serialization/GlobalModuleIndex.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000020#include "clang/Serialization/InMemoryModuleCache.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000021#include "clang/Serialization/Module.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000022#include "clang/Serialization/PCHContainerOperations.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000023#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/iterator.h"
29#include "llvm/Support/Chrono.h"
30#include "llvm/Support/DOTGraphTraits.h"
31#include "llvm/Support/ErrorOr.h"
Douglas Gregor9d7c1a22011-10-11 19:27:55 +000032#include "llvm/Support/GraphWriter.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000033#include "llvm/Support/MemoryBuffer.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000034#include "llvm/Support/VirtualFileSystem.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000035#include <algorithm>
36#include <cassert>
37#include <memory>
38#include <string>
39#include <system_error>
Douglas Gregor9d7c1a22011-10-11 19:27:55 +000040
Douglas Gregord44252e2011-08-25 20:47:51 +000041using namespace clang;
42using namespace serialization;
43
Boris Kolpackovd30446f2017-08-31 06:26:43 +000044ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
Harlan Haskins8d323d12019-08-01 21:31:56 +000045 auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
46 /*CacheFailure=*/false);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000047 if (Entry)
Harlan Haskins8d323d12019-08-01 21:31:56 +000048 return lookup(*Entry);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000049
Craig Toppera13603a2014-05-22 05:54:18 +000050 return nullptr;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000051}
52
Boris Kolpackovd30446f2017-08-31 06:26:43 +000053ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
54 if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
55 if (const FileEntry *File = Mod->getASTFile())
56 return lookup(File);
57
58 return nullptr;
59}
60
Richard Smith37a93df2017-02-18 00:32:02 +000061ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
62 auto Known = Modules.find(File);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000063 if (Known == Modules.end())
Craig Toppera13603a2014-05-22 05:54:18 +000064 return nullptr;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000065
66 return Known->second;
Douglas Gregord44252e2011-08-25 20:47:51 +000067}
68
Rafael Espindola5cd06f22014-08-18 19:16:31 +000069std::unique_ptr<llvm::MemoryBuffer>
70ModuleManager::lookupBuffer(StringRef Name) {
Harlan Haskins8d323d12019-08-01 21:31:56 +000071 auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
72 /*CacheFailure=*/false);
73 if (!Entry)
74 return nullptr;
75 return std::move(InMemoryBuffers[*Entry]);
Douglas Gregord44252e2011-08-25 20:47:51 +000076}
77
Duncan P. N. Exon Smith14afc8e2017-01-28 21:34:28 +000078static bool checkSignature(ASTFileSignature Signature,
79 ASTFileSignature ExpectedSignature,
80 std::string &ErrorStr) {
81 if (!ExpectedSignature || Signature == ExpectedSignature)
82 return false;
83
84 ErrorStr =
85 Signature ? "signature mismatch" : "could not read module signature";
86 return true;
87}
88
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +000089static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
90 SourceLocation ImportLoc) {
91 if (ImportedBy) {
92 MF.ImportedBy.insert(ImportedBy);
93 ImportedBy->Imports.insert(&MF);
94 } else {
95 if (!MF.DirectlyImported)
96 MF.ImportLoc = ImportLoc;
97
98 MF.DirectlyImported = true;
99 }
100}
101
Douglas Gregor7029ce12013-03-19 00:28:20 +0000102ModuleManager::AddModuleResult
Douglas Gregor6fb03ae2012-11-30 19:28:05 +0000103ModuleManager::addModule(StringRef FileName, ModuleKind Type,
104 SourceLocation ImportLoc, ModuleFile *ImportedBy,
Douglas Gregor7029ce12013-03-19 00:28:20 +0000105 unsigned Generation,
106 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +0000107 ASTFileSignature ExpectedSignature,
Ben Langmuir70a1b812015-03-24 04:43:52 +0000108 ASTFileSignatureReader ReadSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +0000109 ModuleFile *&Module,
110 std::string &ErrorStr) {
Craig Toppera13603a2014-05-22 05:54:18 +0000111 Module = nullptr;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000112
113 // Look for the file entry. This only fails if the expected size or
114 // modification time differ.
115 const FileEntry *Entry;
Manman Ren11f2a472016-08-18 17:42:15 +0000116 if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
Richard Smith5b390752014-11-21 05:37:20 +0000117 // If we're not expecting to pull this file out of the module cache, it
118 // might have a different mtime due to being moved across filesystems in
119 // a distributed build. The size must still match, though. (As must the
120 // contents, but we can't check that.)
121 ExpectedModTime = 0;
122 }
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +0000123 // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule
124 // when using an ASTFileSignature.
Eli Friedmanc27d0d52013-09-05 23:50:58 +0000125 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
126 ErrorStr = "module file out of date";
Douglas Gregor7029ce12013-03-19 00:28:20 +0000127 return OutOfDate;
Eli Friedmanc27d0d52013-09-05 23:50:58 +0000128 }
Douglas Gregor7029ce12013-03-19 00:28:20 +0000129
Douglas Gregord44252e2011-08-25 20:47:51 +0000130 if (!Entry && FileName != "-") {
Eli Friedmanc27d0d52013-09-05 23:50:58 +0000131 ErrorStr = "module file not found";
Douglas Gregor7029ce12013-03-19 00:28:20 +0000132 return Missing;
Douglas Gregord44252e2011-08-25 20:47:51 +0000133 }
Douglas Gregor7029ce12013-03-19 00:28:20 +0000134
135 // Check whether we already loaded this module, before
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000136 if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
137 // Check the stored signature.
138 if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
Ben Langmuired982582014-11-08 00:34:30 +0000139 return OutOfDate;
Duncan P. N. Exon Smitha897f7c2017-01-28 22:24:01 +0000140
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000141 Module = ModuleEntry;
142 updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
Richard Smith3b99db52016-09-02 00:10:28 +0000143 return AlreadyLoaded;
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000144 }
Richard Smith3b99db52016-09-02 00:10:28 +0000145
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000146 // Allocate a new module.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000147 auto NewModule = std::make_unique<ModuleFile>(Type, Generation);
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000148 NewModule->Index = Chain.size();
149 NewModule->FileName = FileName.str();
150 NewModule->File = Entry;
151 NewModule->ImportLoc = ImportLoc;
152 NewModule->InputFilesValidationTimestamp = 0;
153
154 if (NewModule->Kind == MK_ImplicitModule) {
155 std::string TimestampFilename = NewModule->getTimestampFilename();
Jonas Devliegherefc514902018-10-10 13:27:25 +0000156 llvm::vfs::Status Status;
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000157 // A cached stat value would be fine as well.
158 if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
159 NewModule->InputFilesValidationTimestamp =
160 llvm::sys::toTimeT(Status.getLastModificationTime());
161 }
162
163 // Load the contents of the module
164 if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
165 // The buffer was already provided for us.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +0000166 NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer));
Adrian Prantl49092d12018-08-20 17:10:27 +0000167 // Since the cached buffer is reused, it is safe to close the file
168 // descriptor that was opened while stat()ing the PCM in
169 // lookupModuleFile() above, it won't be needed any longer.
170 Entry->closeFile();
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000171 } else if (llvm::MemoryBuffer *Buffer =
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +0000172 getModuleCache().lookupPCM(FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000173 NewModule->Buffer = Buffer;
Adrian Prantl49092d12018-08-20 17:10:27 +0000174 // As above, the file descriptor is no longer needed.
175 Entry->closeFile();
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +0000176 } else if (getModuleCache().shouldBuildPCM(FileName)) {
177 // Report that the module is out of date, since we tried (and failed) to
178 // import it earlier.
179 Entry->closeFile();
180 return OutOfDate;
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000181 } else {
182 // Open the AST file.
183 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
184 if (FileName == "-") {
185 Buf = llvm::MemoryBuffer::getSTDIN();
186 } else {
Adrian Prantl49092d12018-08-20 17:10:27 +0000187 // Get a buffer of the file and close the file descriptor when done.
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000188 Buf = FileMgr.getBufferForFile(NewModule->File,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000189 /*isVolatile=*/false,
Adrian Prantl49092d12018-08-20 17:10:27 +0000190 /*ShouldClose=*/true);
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000191 }
192
193 if (!Buf) {
194 ErrorStr = Buf.getError().message();
195 return Missing;
196 }
197
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +0000198 NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf));
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000199 }
200
201 // Initialize the stream.
202 NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
203
Duncan P. N. Exon Smith688b69a2017-01-29 04:42:21 +0000204 // Read the signature eagerly now so that we can check it. Avoid calling
205 // ReadSignature unless there's something to check though.
206 if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
Volodymyr Sapsaif91b6f82019-08-28 23:31:32 +0000207 ExpectedSignature, ErrorStr))
Duncan P. N. Exon Smith26308a62017-01-28 23:22:40 +0000208 return OutOfDate;
209
210 // We're keeping this module. Store it everywhere.
211 Module = Modules[Entry] = NewModule.get();
212
213 updateModuleImports(*NewModule, ImportedBy, ImportLoc);
214
215 if (!NewModule->isModule())
216 PCHChain.push_back(NewModule.get());
217 if (!ImportedBy)
218 Roots.push_back(NewModule.get());
Richard Smith3b99db52016-09-02 00:10:28 +0000219
Duncan P. N. Exon Smitha897f7c2017-01-28 22:24:01 +0000220 Chain.push_back(std::move(NewModule));
Richard Smith3b99db52016-09-02 00:10:28 +0000221 return NewlyLoaded;
Douglas Gregord44252e2011-08-25 20:47:51 +0000222}
223
Ben Langmuir9801b252014-06-20 00:24:56 +0000224void ModuleManager::removeModules(
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +0000225 ModuleIterator First,
Ben Langmuir9801b252014-06-20 00:24:56 +0000226 llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
227 ModuleMap *modMap) {
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +0000228 auto Last = end();
229 if (First == Last)
Douglas Gregor188dbef2012-11-07 17:46:15 +0000230 return;
231
Ben Langmuira50dbb22015-10-21 23:12:45 +0000232 // Explicitly clear VisitOrder since we might not notice it is stale.
233 VisitOrder.clear();
234
Douglas Gregor188dbef2012-11-07 17:46:15 +0000235 // Collect the set of module file pointers that we'll be removing.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000236 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +0000237 (llvm::pointer_iterator<ModuleIterator>(First)),
238 (llvm::pointer_iterator<ModuleIterator>(Last)));
Douglas Gregor188dbef2012-11-07 17:46:15 +0000239
Manuel Klimek9eff8b12015-05-20 10:29:23 +0000240 auto IsVictim = [&](ModuleFile *MF) {
241 return victimSet.count(MF);
242 };
Douglas Gregor188dbef2012-11-07 17:46:15 +0000243 // Remove any references to the now-destroyed modules.
Duncan P. N. Exon Smith073ec352017-01-28 23:12:13 +0000244 for (auto I = begin(); I != First; ++I) {
245 I->Imports.remove_if(IsVictim);
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +0000246 I->ImportedBy.remove_if(IsVictim);
Duncan P. N. Exon Smith073ec352017-01-28 23:12:13 +0000247 }
Manuel Klimek9eff8b12015-05-20 10:29:23 +0000248 Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
249 Roots.end());
Douglas Gregor188dbef2012-11-07 17:46:15 +0000250
Richard Smith16fe4d12015-07-22 22:51:15 +0000251 // Remove the modules from the PCH chain.
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +0000252 for (auto I = First; I != Last; ++I) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000253 if (!I->isModule()) {
Fangrui Song75e74e02019-03-31 08:48:19 +0000254 PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
Richard Smith16fe4d12015-07-22 22:51:15 +0000255 break;
256 }
257 }
258
Douglas Gregor188dbef2012-11-07 17:46:15 +0000259 // Delete the modules and erase them from the various structures.
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +0000260 for (ModuleIterator victim = First; victim != Last; ++victim) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000261 Modules.erase(victim->File);
Ben Langmuirca392142014-05-19 16:13:45 +0000262
Douglas Gregor7029ce12013-03-19 00:28:20 +0000263 if (modMap) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000264 StringRef ModuleName = victim->ModuleName;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000265 if (Module *mod = modMap->findModule(ModuleName)) {
Craig Toppera13603a2014-05-22 05:54:18 +0000266 mod->setASTFile(nullptr);
Douglas Gregor7029ce12013-03-19 00:28:20 +0000267 }
268 }
Douglas Gregor188dbef2012-11-07 17:46:15 +0000269 }
270
Duncan P. N. Exon Smitha897f7c2017-01-28 22:24:01 +0000271 // Delete the modules.
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +0000272 Chain.erase(Chain.begin() + (First - begin()), Chain.end());
Douglas Gregor188dbef2012-11-07 17:46:15 +0000273}
274
Rafael Espindola5cd06f22014-08-18 19:16:31 +0000275void
276ModuleManager::addInMemoryBuffer(StringRef FileName,
277 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
Rafael Espindola5cd06f22014-08-18 19:16:31 +0000278 const FileEntry *Entry =
279 FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
280 InMemoryBuffers[Entry] = std::move(Buffer);
Douglas Gregord44252e2011-08-25 20:47:51 +0000281}
282
Douglas Gregore97cd902013-01-28 16:46:33 +0000283ModuleManager::VisitState *ModuleManager::allocateVisitState() {
284 // Fast path: if we have a cached state, use it.
285 if (FirstVisitState) {
286 VisitState *Result = FirstVisitState;
287 FirstVisitState = FirstVisitState->NextState;
Craig Toppera13603a2014-05-22 05:54:18 +0000288 Result->NextState = nullptr;
Douglas Gregore97cd902013-01-28 16:46:33 +0000289 return Result;
290 }
291
292 // Allocate and return a new state.
293 return new VisitState(size());
294}
295
296void ModuleManager::returnVisitState(VisitState *State) {
Craig Toppera13603a2014-05-22 05:54:18 +0000297 assert(State->NextState == nullptr && "Visited state is in list?");
Douglas Gregore97cd902013-01-28 16:46:33 +0000298 State->NextState = FirstVisitState;
299 FirstVisitState = State;
300}
301
Douglas Gregor7211ac12013-01-25 23:32:03 +0000302void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
303 GlobalIndex = Index;
Douglas Gregor603cd862013-03-22 18:50:14 +0000304 if (!GlobalIndex) {
305 ModulesInCommonWithGlobalIndex.clear();
306 return;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000307 }
Douglas Gregor603cd862013-03-22 18:50:14 +0000308
309 // Notify the global module index about all of the modules we've already
310 // loaded.
Duncan P. N. Exon Smitha897f7c2017-01-28 22:24:01 +0000311 for (ModuleFile &M : *this)
312 if (!GlobalIndex->loadedModuleFile(&M))
313 ModulesInCommonWithGlobalIndex.push_back(&M);
Douglas Gregor603cd862013-03-22 18:50:14 +0000314}
315
316void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
317 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
318 return;
319
320 ModulesInCommonWithGlobalIndex.push_back(MF);
Douglas Gregor7211ac12013-01-25 23:32:03 +0000321}
322
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000323ModuleManager::ModuleManager(FileManager &FileMgr,
324 InMemoryModuleCache &ModuleCache,
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000325 const PCHContainerReader &PCHContainerRdr,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000326 const HeaderSearch &HeaderSearchInfo)
327 : FileMgr(FileMgr), ModuleCache(&ModuleCache),
328 PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
Douglas Gregord44252e2011-08-25 20:47:51 +0000329
Duncan P. N. Exon Smitha897f7c2017-01-28 22:24:01 +0000330ModuleManager::~ModuleManager() { delete FirstVisitState; }
Douglas Gregord44252e2011-08-25 20:47:51 +0000331
Benjamin Kramer9a9efba2015-07-25 12:14:04 +0000332void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
333 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
Douglas Gregor7211ac12013-01-25 23:32:03 +0000334 // If the visitation order vector is the wrong size, recompute the order.
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000335 if (VisitOrder.size() != Chain.size()) {
336 unsigned N = size();
337 VisitOrder.clear();
338 VisitOrder.reserve(N);
Fangrui Song6907ce22018-07-30 19:24:48 +0000339
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000340 // Record the number of incoming edges for each module. When we
341 // encounter a module with no incoming edges, push it into the queue
342 // to seed the queue.
343 SmallVector<ModuleFile *, 4> Queue;
344 Queue.reserve(N);
345 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
Richard Smitha7c535b2015-07-22 01:28:05 +0000346 UnusedIncomingEdges.resize(size());
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000347 for (ModuleFile &M : llvm::reverse(*this)) {
348 unsigned Size = M.ImportedBy.size();
349 UnusedIncomingEdges[M.Index] = Size;
Richard Smitha7c535b2015-07-22 01:28:05 +0000350 if (!Size)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000351 Queue.push_back(&M);
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000352 }
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000353
354 // Traverse the graph, making sure to visit a module before visiting any
355 // of its dependencies.
Richard Smitha7c535b2015-07-22 01:28:05 +0000356 while (!Queue.empty()) {
357 ModuleFile *CurrentModule = Queue.pop_back_val();
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000358 VisitOrder.push_back(CurrentModule);
359
360 // For any module that this module depends on, push it on the
361 // stack (if it hasn't already been marked as visited).
Richard Smitha7c535b2015-07-22 01:28:05 +0000362 for (auto M = CurrentModule->Imports.rbegin(),
363 MEnd = CurrentModule->Imports.rend();
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000364 M != MEnd; ++M) {
365 // Remove our current module as an impediment to visiting the
366 // module we depend on. If we were the last unvisited module
367 // that depends on this particular module, push it into the
368 // queue to be visited.
369 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
370 if (NumUnusedEdges && (--NumUnusedEdges == 0))
371 Queue.push_back(*M);
372 }
373 }
374
375 assert(VisitOrder.size() == N && "Visitation order is wrong?");
Douglas Gregor7211ac12013-01-25 23:32:03 +0000376
Douglas Gregore97cd902013-01-28 16:46:33 +0000377 delete FirstVisitState;
Craig Toppera13603a2014-05-22 05:54:18 +0000378 FirstVisitState = nullptr;
Douglas Gregord44252e2011-08-25 20:47:51 +0000379 }
Douglas Gregorbdb259d2013-01-21 20:07:12 +0000380
Douglas Gregore97cd902013-01-28 16:46:33 +0000381 VisitState *State = allocateVisitState();
382 unsigned VisitNumber = State->NextVisitNumber++;
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000383
Douglas Gregor7211ac12013-01-25 23:32:03 +0000384 // If the caller has provided us with a hit-set that came from the global
385 // module index, mark every module file in common with the global module
386 // index that is *not* in that set as 'visited'.
387 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
388 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
389 {
390 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000391 if (!ModuleFilesHit->count(M))
Douglas Gregore97cd902013-01-28 16:46:33 +0000392 State->VisitNumber[M->Index] = VisitNumber;
Douglas Gregor7211ac12013-01-25 23:32:03 +0000393 }
394 }
395
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000396 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
397 ModuleFile *CurrentModule = VisitOrder[I];
398 // Should we skip this module file?
Douglas Gregore97cd902013-01-28 16:46:33 +0000399 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
Douglas Gregord44252e2011-08-25 20:47:51 +0000400 continue;
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000401
402 // Visit the module.
Douglas Gregore97cd902013-01-28 16:46:33 +0000403 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
404 State->VisitNumber[CurrentModule->Index] = VisitNumber;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +0000405 if (!Visitor(*CurrentModule))
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000406 continue;
407
408 // The visitor has requested that cut off visitation of any
409 // module that the current module depends on. To indicate this
410 // behavior, we mark all of the reachable modules as having been visited.
411 ModuleFile *NextModule = CurrentModule;
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000412 do {
413 // For any module that this module depends on, push it on the
414 // stack (if it hasn't already been marked as visited).
415 for (llvm::SetVector<ModuleFile *>::iterator
416 M = NextModule->Imports.begin(),
417 MEnd = NextModule->Imports.end();
418 M != MEnd; ++M) {
Douglas Gregore97cd902013-01-28 16:46:33 +0000419 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
420 State->Stack.push_back(*M);
421 State->VisitNumber[(*M)->Index] = VisitNumber;
Douglas Gregord44252e2011-08-25 20:47:51 +0000422 }
423 }
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000424
Douglas Gregore97cd902013-01-28 16:46:33 +0000425 if (State->Stack.empty())
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000426 break;
427
428 // Pop the next module off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000429 NextModule = State->Stack.pop_back_val();
Douglas Gregore41d7fe2013-01-25 22:25:23 +0000430 } while (true);
Douglas Gregord44252e2011-08-25 20:47:51 +0000431 }
Douglas Gregore97cd902013-01-28 16:46:33 +0000432
433 returnVisitState(State);
Douglas Gregord44252e2011-08-25 20:47:51 +0000434}
435
Douglas Gregor7029ce12013-03-19 00:28:20 +0000436bool ModuleManager::lookupModuleFile(StringRef FileName,
437 off_t ExpectedSize,
438 time_t ExpectedModTime,
439 const FileEntry *&File) {
Richard Smith3bd6d7f2016-09-02 00:18:05 +0000440 if (FileName == "-") {
441 File = nullptr;
442 return false;
443 }
444
Ben Langmuir05f82ba2014-05-01 03:33:36 +0000445 // Open the file immediately to ensure there is no race between stat'ing and
446 // opening the file.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000447 auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
448 /*CacheFailure=*/false);
449 if (!FileOrErr) {
450 File = nullptr;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000451 return false;
Harlan Haskins8d323d12019-08-01 21:31:56 +0000452 }
453 File = *FileOrErr;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000454
455 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
Ben Langmuir027731d2014-05-04 05:20:54 +0000456 (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
457 // Do not destroy File, as it may be referenced. If we need to rebuild it,
458 // it will be destroyed by removeModules.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000459 return true;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000460
461 return false;
462}
463
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000464#ifndef NDEBUG
465namespace llvm {
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000466
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000467 template<>
468 struct GraphTraits<ModuleManager> {
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000469 using NodeRef = ModuleFile *;
470 using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
471 using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
Tim Shenf2187ed2016-08-22 21:09:30 +0000472
473 static ChildIteratorType child_begin(NodeRef Node) {
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000474 return Node->Imports.begin();
475 }
476
Tim Shenf2187ed2016-08-22 21:09:30 +0000477 static ChildIteratorType child_end(NodeRef Node) {
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000478 return Node->Imports.end();
479 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000480
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000481 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000482 return nodes_iterator(Manager.begin());
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000483 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000484
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000485 static nodes_iterator nodes_end(const ModuleManager &Manager) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000486 return nodes_iterator(Manager.end());
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000487 }
488 };
Fangrui Song6907ce22018-07-30 19:24:48 +0000489
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000490 template<>
491 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
492 explicit DOTGraphTraits(bool IsSimple = false)
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000493 : DefaultDOTGraphTraits(IsSimple) {}
Fangrui Song6907ce22018-07-30 19:24:48 +0000494
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000495 static bool renderGraphFromBottomUp() { return true; }
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000496
Douglas Gregorde3ef502011-11-30 23:21:26 +0000497 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000498 return M->ModuleName;
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000499 }
500 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000501
502} // namespace llvm
Douglas Gregor9d7c1a22011-10-11 19:27:55 +0000503
504void ModuleManager::viewGraph() {
505 llvm::ViewGraph(*this, "Modules");
506}
507#endif