1 //===- ModuleManager.cpp - Module Manager ---------------------------------===// 2 // 3 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the ModuleManager class, which manages a set of loaded 10 // modules for the ASTReader. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Serialization/ModuleManager.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/LLVM.h" 17 #include "clang/Lex/HeaderSearch.h" 18 #include "clang/Lex/ModuleMap.h" 19 #include "clang/Serialization/GlobalModuleIndex.h" 20 #include "clang/Serialization/InMemoryModuleCache.h" 21 #include "clang/Serialization/Module.h" 22 #include "clang/Serialization/PCHContainerOperations.h" 23 #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" 32 #include "llvm/Support/GraphWriter.h" 33 #include "llvm/Support/MemoryBuffer.h" 34 #include "llvm/Support/VirtualFileSystem.h" 35 #include <algorithm> 36 #include <cassert> 37 #include <memory> 38 #include <string> 39 #include <system_error> 40 41 using namespace clang; 42 using namespace serialization; 43 44 ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const { 45 auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false, 46 /*CacheFailure=*/false); 47 if (Entry) 48 return lookup(*Entry); 49 50 return nullptr; 51 } 52 53 ModuleFile *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 61 ModuleFile *ModuleManager::lookup(const FileEntry *File) const { 62 auto Known = Modules.find(File); 63 if (Known == Modules.end()) 64 return nullptr; 65 66 return Known->second; 67 } 68 69 std::unique_ptr<llvm::MemoryBuffer> 70 ModuleManager::lookupBuffer(StringRef Name) { 71 auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false, 72 /*CacheFailure=*/false); 73 if (!Entry) 74 return nullptr; 75 return std::move(InMemoryBuffers[*Entry]); 76 } 77 78 static 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 89 static 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 102 ModuleManager::AddModuleResult 103 ModuleManager::addModule(StringRef FileName, ModuleKind Type, 104 SourceLocation ImportLoc, ModuleFile *ImportedBy, 105 unsigned Generation, 106 off_t ExpectedSize, time_t ExpectedModTime, 107 ASTFileSignature ExpectedSignature, 108 ASTFileSignatureReader ReadSignature, 109 ModuleFile *&Module, 110 std::string &ErrorStr) { 111 Module = nullptr; 112 113 // Look for the file entry. This only fails if the expected size or 114 // modification time differ. 115 const FileEntry *Entry; 116 if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) { 117 // 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 } 123 // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule 124 // when using an ASTFileSignature. 125 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) { 126 ErrorStr = "module file out of date"; 127 return OutOfDate; 128 } 129 130 if (!Entry && FileName != "-") { 131 ErrorStr = "module file not found"; 132 return Missing; 133 } 134 135 // Check whether we already loaded this module, before 136 if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) { 137 // Check the stored signature. 138 if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr)) 139 return OutOfDate; 140 141 Module = ModuleEntry; 142 updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc); 143 return AlreadyLoaded; 144 } 145 146 // Allocate a new module. 147 auto NewModule = std::make_unique<ModuleFile>(Type, Generation); 148 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(); 156 llvm::vfs::Status Status; 157 // 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. 166 NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer)); 167 // 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(); 171 } else if (llvm::MemoryBuffer *Buffer = 172 getModuleCache().lookupPCM(FileName)) { 173 NewModule->Buffer = Buffer; 174 // As above, the file descriptor is no longer needed. 175 Entry->closeFile(); 176 } 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; 181 } 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 { 187 // Get a buffer of the file and close the file descriptor when done. 188 Buf = FileMgr.getBufferForFile(NewModule->File, 189 /*isVolatile=*/false, 190 /*ShouldClose=*/true); 191 } 192 193 if (!Buf) { 194 ErrorStr = Buf.getError().message(); 195 return Missing; 196 } 197 198 NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf)); 199 } 200 201 // Initialize the stream. 202 NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer); 203 204 // 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), 207 ExpectedSignature, ErrorStr)) 208 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()); 219 220 Chain.push_back(std::move(NewModule)); 221 return NewlyLoaded; 222 } 223 224 void ModuleManager::removeModules( 225 ModuleIterator First, 226 llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully, 227 ModuleMap *modMap) { 228 auto Last = end(); 229 if (First == Last) 230 return; 231 232 // Explicitly clear VisitOrder since we might not notice it is stale. 233 VisitOrder.clear(); 234 235 // Collect the set of module file pointers that we'll be removing. 236 llvm::SmallPtrSet<ModuleFile *, 4> victimSet( 237 (llvm::pointer_iterator<ModuleIterator>(First)), 238 (llvm::pointer_iterator<ModuleIterator>(Last))); 239 240 auto IsVictim = [&](ModuleFile *MF) { 241 return victimSet.count(MF); 242 }; 243 // Remove any references to the now-destroyed modules. 244 for (auto I = begin(); I != First; ++I) { 245 I->Imports.remove_if(IsVictim); 246 I->ImportedBy.remove_if(IsVictim); 247 } 248 Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim), 249 Roots.end()); 250 251 // Remove the modules from the PCH chain. 252 for (auto I = First; I != Last; ++I) { 253 if (!I->isModule()) { 254 PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end()); 255 break; 256 } 257 } 258 259 // Delete the modules and erase them from the various structures. 260 for (ModuleIterator victim = First; victim != Last; ++victim) { 261 Modules.erase(victim->File); 262 263 if (modMap) { 264 StringRef ModuleName = victim->ModuleName; 265 if (Module *mod = modMap->findModule(ModuleName)) { 266 mod->setASTFile(nullptr); 267 } 268 } 269 } 270 271 // Delete the modules. 272 Chain.erase(Chain.begin() + (First - begin()), Chain.end()); 273 } 274 275 void 276 ModuleManager::addInMemoryBuffer(StringRef FileName, 277 std::unique_ptr<llvm::MemoryBuffer> Buffer) { 278 const FileEntry *Entry = 279 FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0); 280 InMemoryBuffers[Entry] = std::move(Buffer); 281 } 282 283 ModuleManager::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; 288 Result->NextState = nullptr; 289 return Result; 290 } 291 292 // Allocate and return a new state. 293 return new VisitState(size()); 294 } 295 296 void ModuleManager::returnVisitState(VisitState *State) { 297 assert(State->NextState == nullptr && "Visited state is in list?"); 298 State->NextState = FirstVisitState; 299 FirstVisitState = State; 300 } 301 302 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) { 303 GlobalIndex = Index; 304 if (!GlobalIndex) { 305 ModulesInCommonWithGlobalIndex.clear(); 306 return; 307 } 308 309 // Notify the global module index about all of the modules we've already 310 // loaded. 311 for (ModuleFile &M : *this) 312 if (!GlobalIndex->loadedModuleFile(&M)) 313 ModulesInCommonWithGlobalIndex.push_back(&M); 314 } 315 316 void ModuleManager::moduleFileAccepted(ModuleFile *MF) { 317 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF)) 318 return; 319 320 ModulesInCommonWithGlobalIndex.push_back(MF); 321 } 322 323 ModuleManager::ModuleManager(FileManager &FileMgr, 324 InMemoryModuleCache &ModuleCache, 325 const PCHContainerReader &PCHContainerRdr, 326 const HeaderSearch &HeaderSearchInfo) 327 : FileMgr(FileMgr), ModuleCache(&ModuleCache), 328 PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {} 329 330 ModuleManager::~ModuleManager() { delete FirstVisitState; } 331 332 void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor, 333 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) { 334 // If the visitation order vector is the wrong size, recompute the order. 335 if (VisitOrder.size() != Chain.size()) { 336 unsigned N = size(); 337 VisitOrder.clear(); 338 VisitOrder.reserve(N); 339 340 // 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; 346 UnusedIncomingEdges.resize(size()); 347 for (ModuleFile &M : llvm::reverse(*this)) { 348 unsigned Size = M.ImportedBy.size(); 349 UnusedIncomingEdges[M.Index] = Size; 350 if (!Size) 351 Queue.push_back(&M); 352 } 353 354 // Traverse the graph, making sure to visit a module before visiting any 355 // of its dependencies. 356 while (!Queue.empty()) { 357 ModuleFile *CurrentModule = Queue.pop_back_val(); 358 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). 362 for (auto M = CurrentModule->Imports.rbegin(), 363 MEnd = CurrentModule->Imports.rend(); 364 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?"); 376 377 delete FirstVisitState; 378 FirstVisitState = nullptr; 379 } 380 381 VisitState *State = allocateVisitState(); 382 unsigned VisitNumber = State->NextVisitNumber++; 383 384 // 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]; 391 if (!ModuleFilesHit->count(M)) 392 State->VisitNumber[M->Index] = VisitNumber; 393 } 394 } 395 396 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) { 397 ModuleFile *CurrentModule = VisitOrder[I]; 398 // Should we skip this module file? 399 if (State->VisitNumber[CurrentModule->Index] == VisitNumber) 400 continue; 401 402 // Visit the module. 403 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1); 404 State->VisitNumber[CurrentModule->Index] = VisitNumber; 405 if (!Visitor(*CurrentModule)) 406 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; 412 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) { 419 if (State->VisitNumber[(*M)->Index] != VisitNumber) { 420 State->Stack.push_back(*M); 421 State->VisitNumber[(*M)->Index] = VisitNumber; 422 } 423 } 424 425 if (State->Stack.empty()) 426 break; 427 428 // Pop the next module off the stack. 429 NextModule = State->Stack.pop_back_val(); 430 } while (true); 431 } 432 433 returnVisitState(State); 434 } 435 436 bool ModuleManager::lookupModuleFile(StringRef FileName, 437 off_t ExpectedSize, 438 time_t ExpectedModTime, 439 const FileEntry *&File) { 440 if (FileName == "-") { 441 File = nullptr; 442 return false; 443 } 444 445 // Open the file immediately to ensure there is no race between stat'ing and 446 // opening the file. 447 auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true, 448 /*CacheFailure=*/false); 449 if (!FileOrErr) { 450 File = nullptr; 451 return false; 452 } 453 File = *FileOrErr; 454 455 if ((ExpectedSize && ExpectedSize != File->getSize()) || 456 (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. 459 return true; 460 461 return false; 462 } 463 464 #ifndef NDEBUG 465 namespace llvm { 466 467 template<> 468 struct GraphTraits<ModuleManager> { 469 using NodeRef = ModuleFile *; 470 using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator; 471 using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>; 472 473 static ChildIteratorType child_begin(NodeRef Node) { 474 return Node->Imports.begin(); 475 } 476 477 static ChildIteratorType child_end(NodeRef Node) { 478 return Node->Imports.end(); 479 } 480 481 static nodes_iterator nodes_begin(const ModuleManager &Manager) { 482 return nodes_iterator(Manager.begin()); 483 } 484 485 static nodes_iterator nodes_end(const ModuleManager &Manager) { 486 return nodes_iterator(Manager.end()); 487 } 488 }; 489 490 template<> 491 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits { 492 explicit DOTGraphTraits(bool IsSimple = false) 493 : DefaultDOTGraphTraits(IsSimple) {} 494 495 static bool renderGraphFromBottomUp() { return true; } 496 497 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) { 498 return M->ModuleName; 499 } 500 }; 501 502 } // namespace llvm 503 504 void ModuleManager::viewGraph() { 505 llvm::ViewGraph(*this, "Modules"); 506 } 507 #endif 508