ModuleManager.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. #include "clang/Serialization/ModuleManager.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/LLVM.h"
  16. #include "clang/Lex/HeaderSearch.h"
  17. #include "clang/Lex/ModuleMap.h"
  18. #include "clang/Serialization/GlobalModuleIndex.h"
  19. #include "clang/Serialization/InMemoryModuleCache.h"
  20. #include "clang/Serialization/Module.h"
  21. #include "clang/Serialization/PCHContainerOperations.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/iterator.h"
  28. #include "llvm/Support/Chrono.h"
  29. #include "llvm/Support/DOTGraphTraits.h"
  30. #include "llvm/Support/ErrorOr.h"
  31. #include "llvm/Support/GraphWriter.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/VirtualFileSystem.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <memory>
  37. #include <string>
  38. #include <system_error>
  39. using namespace clang;
  40. using namespace serialization;
  41. ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
  42. const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
  43. /*cacheFailure=*/false);
  44. if (Entry)
  45. return lookup(Entry);
  46. return nullptr;
  47. }
  48. ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
  49. if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
  50. if (const FileEntry *File = Mod->getASTFile())
  51. return lookup(File);
  52. return nullptr;
  53. }
  54. ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
  55. auto Known = Modules.find(File);
  56. if (Known == Modules.end())
  57. return nullptr;
  58. return Known->second;
  59. }
  60. std::unique_ptr<llvm::MemoryBuffer>
  61. ModuleManager::lookupBuffer(StringRef Name) {
  62. const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
  63. /*cacheFailure=*/false);
  64. return std::move(InMemoryBuffers[Entry]);
  65. }
  66. static bool checkSignature(ASTFileSignature Signature,
  67. ASTFileSignature ExpectedSignature,
  68. std::string &ErrorStr) {
  69. if (!ExpectedSignature || Signature == ExpectedSignature)
  70. return false;
  71. ErrorStr =
  72. Signature ? "signature mismatch" : "could not read module signature";
  73. return true;
  74. }
  75. static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
  76. SourceLocation ImportLoc) {
  77. if (ImportedBy) {
  78. MF.ImportedBy.insert(ImportedBy);
  79. ImportedBy->Imports.insert(&MF);
  80. } else {
  81. if (!MF.DirectlyImported)
  82. MF.ImportLoc = ImportLoc;
  83. MF.DirectlyImported = true;
  84. }
  85. }
  86. ModuleManager::AddModuleResult
  87. ModuleManager::addModule(StringRef FileName, ModuleKind Type,
  88. SourceLocation ImportLoc, ModuleFile *ImportedBy,
  89. unsigned Generation,
  90. off_t ExpectedSize, time_t ExpectedModTime,
  91. ASTFileSignature ExpectedSignature,
  92. ASTFileSignatureReader ReadSignature,
  93. ModuleFile *&Module,
  94. std::string &ErrorStr) {
  95. Module = nullptr;
  96. // Look for the file entry. This only fails if the expected size or
  97. // modification time differ.
  98. const FileEntry *Entry;
  99. if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
  100. // If we're not expecting to pull this file out of the module cache, it
  101. // might have a different mtime due to being moved across filesystems in
  102. // a distributed build. The size must still match, though. (As must the
  103. // contents, but we can't check that.)
  104. ExpectedModTime = 0;
  105. }
  106. // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule
  107. // when using an ASTFileSignature.
  108. if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
  109. ErrorStr = "module file out of date";
  110. return OutOfDate;
  111. }
  112. if (!Entry && FileName != "-") {
  113. ErrorStr = "module file not found";
  114. return Missing;
  115. }
  116. // Check whether we already loaded this module, before
  117. if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
  118. // Check the stored signature.
  119. if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
  120. return OutOfDate;
  121. Module = ModuleEntry;
  122. updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
  123. return AlreadyLoaded;
  124. }
  125. // Allocate a new module.
  126. auto NewModule = llvm::make_unique<ModuleFile>(Type, Generation);
  127. NewModule->Index = Chain.size();
  128. NewModule->FileName = FileName.str();
  129. NewModule->File = Entry;
  130. NewModule->ImportLoc = ImportLoc;
  131. NewModule->InputFilesValidationTimestamp = 0;
  132. if (NewModule->Kind == MK_ImplicitModule) {
  133. std::string TimestampFilename = NewModule->getTimestampFilename();
  134. llvm::vfs::Status Status;
  135. // A cached stat value would be fine as well.
  136. if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
  137. NewModule->InputFilesValidationTimestamp =
  138. llvm::sys::toTimeT(Status.getLastModificationTime());
  139. }
  140. // Load the contents of the module
  141. if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
  142. // The buffer was already provided for us.
  143. NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer));
  144. // Since the cached buffer is reused, it is safe to close the file
  145. // descriptor that was opened while stat()ing the PCM in
  146. // lookupModuleFile() above, it won't be needed any longer.
  147. Entry->closeFile();
  148. } else if (llvm::MemoryBuffer *Buffer =
  149. getModuleCache().lookupPCM(FileName)) {
  150. NewModule->Buffer = Buffer;
  151. // As above, the file descriptor is no longer needed.
  152. Entry->closeFile();
  153. } else if (getModuleCache().shouldBuildPCM(FileName)) {
  154. // Report that the module is out of date, since we tried (and failed) to
  155. // import it earlier.
  156. Entry->closeFile();
  157. return OutOfDate;
  158. } else {
  159. // Open the AST file.
  160. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
  161. if (FileName == "-") {
  162. Buf = llvm::MemoryBuffer::getSTDIN();
  163. } else {
  164. // Get a buffer of the file and close the file descriptor when done.
  165. Buf = FileMgr.getBufferForFile(NewModule->File,
  166. /*IsVolatile=*/false,
  167. /*ShouldClose=*/true);
  168. }
  169. if (!Buf) {
  170. ErrorStr = Buf.getError().message();
  171. return Missing;
  172. }
  173. NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf));
  174. }
  175. // Initialize the stream.
  176. NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
  177. // Read the signature eagerly now so that we can check it. Avoid calling
  178. // ReadSignature unless there's something to check though.
  179. if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
  180. ExpectedSignature, ErrorStr)) {
  181. // Try to remove the buffer. If it can't be removed, then it was already
  182. // validated by this process.
  183. if (!getModuleCache().tryToDropPCM(NewModule->FileName))
  184. FileMgr.invalidateCache(NewModule->File);
  185. return OutOfDate;
  186. }
  187. // We're keeping this module. Store it everywhere.
  188. Module = Modules[Entry] = NewModule.get();
  189. updateModuleImports(*NewModule, ImportedBy, ImportLoc);
  190. if (!NewModule->isModule())
  191. PCHChain.push_back(NewModule.get());
  192. if (!ImportedBy)
  193. Roots.push_back(NewModule.get());
  194. Chain.push_back(std::move(NewModule));
  195. return NewlyLoaded;
  196. }
  197. void ModuleManager::removeModules(
  198. ModuleIterator First,
  199. llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
  200. ModuleMap *modMap) {
  201. auto Last = end();
  202. if (First == Last)
  203. return;
  204. // Explicitly clear VisitOrder since we might not notice it is stale.
  205. VisitOrder.clear();
  206. // Collect the set of module file pointers that we'll be removing.
  207. llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
  208. (llvm::pointer_iterator<ModuleIterator>(First)),
  209. (llvm::pointer_iterator<ModuleIterator>(Last)));
  210. auto IsVictim = [&](ModuleFile *MF) {
  211. return victimSet.count(MF);
  212. };
  213. // Remove any references to the now-destroyed modules.
  214. for (auto I = begin(); I != First; ++I) {
  215. I->Imports.remove_if(IsVictim);
  216. I->ImportedBy.remove_if(IsVictim);
  217. }
  218. Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
  219. Roots.end());
  220. // Remove the modules from the PCH chain.
  221. for (auto I = First; I != Last; ++I) {
  222. if (!I->isModule()) {
  223. PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),
  224. PCHChain.end());
  225. break;
  226. }
  227. }
  228. // Delete the modules and erase them from the various structures.
  229. for (ModuleIterator victim = First; victim != Last; ++victim) {
  230. Modules.erase(victim->File);
  231. if (modMap) {
  232. StringRef ModuleName = victim->ModuleName;
  233. if (Module *mod = modMap->findModule(ModuleName)) {
  234. mod->setASTFile(nullptr);
  235. }
  236. }
  237. }
  238. // Delete the modules.
  239. Chain.erase(Chain.begin() + (First - begin()), Chain.end());
  240. }
  241. void
  242. ModuleManager::addInMemoryBuffer(StringRef FileName,
  243. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  244. const FileEntry *Entry =
  245. FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
  246. InMemoryBuffers[Entry] = std::move(Buffer);
  247. }
  248. ModuleManager::VisitState *ModuleManager::allocateVisitState() {
  249. // Fast path: if we have a cached state, use it.
  250. if (FirstVisitState) {
  251. VisitState *Result = FirstVisitState;
  252. FirstVisitState = FirstVisitState->NextState;
  253. Result->NextState = nullptr;
  254. return Result;
  255. }
  256. // Allocate and return a new state.
  257. return new VisitState(size());
  258. }
  259. void ModuleManager::returnVisitState(VisitState *State) {
  260. assert(State->NextState == nullptr && "Visited state is in list?");
  261. State->NextState = FirstVisitState;
  262. FirstVisitState = State;
  263. }
  264. void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
  265. GlobalIndex = Index;
  266. if (!GlobalIndex) {
  267. ModulesInCommonWithGlobalIndex.clear();
  268. return;
  269. }
  270. // Notify the global module index about all of the modules we've already
  271. // loaded.
  272. for (ModuleFile &M : *this)
  273. if (!GlobalIndex->loadedModuleFile(&M))
  274. ModulesInCommonWithGlobalIndex.push_back(&M);
  275. }
  276. void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
  277. if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
  278. return;
  279. ModulesInCommonWithGlobalIndex.push_back(MF);
  280. }
  281. ModuleManager::ModuleManager(FileManager &FileMgr,
  282. InMemoryModuleCache &ModuleCache,
  283. const PCHContainerReader &PCHContainerRdr,
  284. const HeaderSearch &HeaderSearchInfo)
  285. : FileMgr(FileMgr), ModuleCache(&ModuleCache),
  286. PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
  287. ModuleManager::~ModuleManager() { delete FirstVisitState; }
  288. void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
  289. llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
  290. // If the visitation order vector is the wrong size, recompute the order.
  291. if (VisitOrder.size() != Chain.size()) {
  292. unsigned N = size();
  293. VisitOrder.clear();
  294. VisitOrder.reserve(N);
  295. // Record the number of incoming edges for each module. When we
  296. // encounter a module with no incoming edges, push it into the queue
  297. // to seed the queue.
  298. SmallVector<ModuleFile *, 4> Queue;
  299. Queue.reserve(N);
  300. llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
  301. UnusedIncomingEdges.resize(size());
  302. for (ModuleFile &M : llvm::reverse(*this)) {
  303. unsigned Size = M.ImportedBy.size();
  304. UnusedIncomingEdges[M.Index] = Size;
  305. if (!Size)
  306. Queue.push_back(&M);
  307. }
  308. // Traverse the graph, making sure to visit a module before visiting any
  309. // of its dependencies.
  310. while (!Queue.empty()) {
  311. ModuleFile *CurrentModule = Queue.pop_back_val();
  312. VisitOrder.push_back(CurrentModule);
  313. // For any module that this module depends on, push it on the
  314. // stack (if it hasn't already been marked as visited).
  315. for (auto M = CurrentModule->Imports.rbegin(),
  316. MEnd = CurrentModule->Imports.rend();
  317. M != MEnd; ++M) {
  318. // Remove our current module as an impediment to visiting the
  319. // module we depend on. If we were the last unvisited module
  320. // that depends on this particular module, push it into the
  321. // queue to be visited.
  322. unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
  323. if (NumUnusedEdges && (--NumUnusedEdges == 0))
  324. Queue.push_back(*M);
  325. }
  326. }
  327. assert(VisitOrder.size() == N && "Visitation order is wrong?");
  328. delete FirstVisitState;
  329. FirstVisitState = nullptr;
  330. }
  331. VisitState *State = allocateVisitState();
  332. unsigned VisitNumber = State->NextVisitNumber++;
  333. // If the caller has provided us with a hit-set that came from the global
  334. // module index, mark every module file in common with the global module
  335. // index that is *not* in that set as 'visited'.
  336. if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
  337. for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
  338. {
  339. ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
  340. if (!ModuleFilesHit->count(M))
  341. State->VisitNumber[M->Index] = VisitNumber;
  342. }
  343. }
  344. for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
  345. ModuleFile *CurrentModule = VisitOrder[I];
  346. // Should we skip this module file?
  347. if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
  348. continue;
  349. // Visit the module.
  350. assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
  351. State->VisitNumber[CurrentModule->Index] = VisitNumber;
  352. if (!Visitor(*CurrentModule))
  353. continue;
  354. // The visitor has requested that cut off visitation of any
  355. // module that the current module depends on. To indicate this
  356. // behavior, we mark all of the reachable modules as having been visited.
  357. ModuleFile *NextModule = CurrentModule;
  358. do {
  359. // For any module that this module depends on, push it on the
  360. // stack (if it hasn't already been marked as visited).
  361. for (llvm::SetVector<ModuleFile *>::iterator
  362. M = NextModule->Imports.begin(),
  363. MEnd = NextModule->Imports.end();
  364. M != MEnd; ++M) {
  365. if (State->VisitNumber[(*M)->Index] != VisitNumber) {
  366. State->Stack.push_back(*M);
  367. State->VisitNumber[(*M)->Index] = VisitNumber;
  368. }
  369. }
  370. if (State->Stack.empty())
  371. break;
  372. // Pop the next module off the stack.
  373. NextModule = State->Stack.pop_back_val();
  374. } while (true);
  375. }
  376. returnVisitState(State);
  377. }
  378. bool ModuleManager::lookupModuleFile(StringRef FileName,
  379. off_t ExpectedSize,
  380. time_t ExpectedModTime,
  381. const FileEntry *&File) {
  382. if (FileName == "-") {
  383. File = nullptr;
  384. return false;
  385. }
  386. // Open the file immediately to ensure there is no race between stat'ing and
  387. // opening the file.
  388. File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
  389. if (!File)
  390. return false;
  391. if ((ExpectedSize && ExpectedSize != File->getSize()) ||
  392. (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
  393. // Do not destroy File, as it may be referenced. If we need to rebuild it,
  394. // it will be destroyed by removeModules.
  395. return true;
  396. return false;
  397. }
  398. #ifndef NDEBUG
  399. namespace llvm {
  400. template<>
  401. struct GraphTraits<ModuleManager> {
  402. using NodeRef = ModuleFile *;
  403. using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
  404. using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
  405. static ChildIteratorType child_begin(NodeRef Node) {
  406. return Node->Imports.begin();
  407. }
  408. static ChildIteratorType child_end(NodeRef Node) {
  409. return Node->Imports.end();
  410. }
  411. static nodes_iterator nodes_begin(const ModuleManager &Manager) {
  412. return nodes_iterator(Manager.begin());
  413. }
  414. static nodes_iterator nodes_end(const ModuleManager &Manager) {
  415. return nodes_iterator(Manager.end());
  416. }
  417. };
  418. template<>
  419. struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
  420. explicit DOTGraphTraits(bool IsSimple = false)
  421. : DefaultDOTGraphTraits(IsSimple) {}
  422. static bool renderGraphFromBottomUp() { return true; }
  423. std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
  424. return M->ModuleName;
  425. }
  426. };
  427. } // namespace llvm
  428. void ModuleManager::viewGraph() {
  429. llvm::ViewGraph(*this, "Modules");
  430. }
  431. #endif