ModuleManager.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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(llvm::find(PCHChain, &*I), PCHChain.end());
  224. break;
  225. }
  226. }
  227. // Delete the modules and erase them from the various structures.
  228. for (ModuleIterator victim = First; victim != Last; ++victim) {
  229. Modules.erase(victim->File);
  230. if (modMap) {
  231. StringRef ModuleName = victim->ModuleName;
  232. if (Module *mod = modMap->findModule(ModuleName)) {
  233. mod->setASTFile(nullptr);
  234. }
  235. }
  236. }
  237. // Delete the modules.
  238. Chain.erase(Chain.begin() + (First - begin()), Chain.end());
  239. }
  240. void
  241. ModuleManager::addInMemoryBuffer(StringRef FileName,
  242. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  243. const FileEntry *Entry =
  244. FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
  245. InMemoryBuffers[Entry] = std::move(Buffer);
  246. }
  247. ModuleManager::VisitState *ModuleManager::allocateVisitState() {
  248. // Fast path: if we have a cached state, use it.
  249. if (FirstVisitState) {
  250. VisitState *Result = FirstVisitState;
  251. FirstVisitState = FirstVisitState->NextState;
  252. Result->NextState = nullptr;
  253. return Result;
  254. }
  255. // Allocate and return a new state.
  256. return new VisitState(size());
  257. }
  258. void ModuleManager::returnVisitState(VisitState *State) {
  259. assert(State->NextState == nullptr && "Visited state is in list?");
  260. State->NextState = FirstVisitState;
  261. FirstVisitState = State;
  262. }
  263. void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
  264. GlobalIndex = Index;
  265. if (!GlobalIndex) {
  266. ModulesInCommonWithGlobalIndex.clear();
  267. return;
  268. }
  269. // Notify the global module index about all of the modules we've already
  270. // loaded.
  271. for (ModuleFile &M : *this)
  272. if (!GlobalIndex->loadedModuleFile(&M))
  273. ModulesInCommonWithGlobalIndex.push_back(&M);
  274. }
  275. void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
  276. if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
  277. return;
  278. ModulesInCommonWithGlobalIndex.push_back(MF);
  279. }
  280. ModuleManager::ModuleManager(FileManager &FileMgr,
  281. InMemoryModuleCache &ModuleCache,
  282. const PCHContainerReader &PCHContainerRdr,
  283. const HeaderSearch &HeaderSearchInfo)
  284. : FileMgr(FileMgr), ModuleCache(&ModuleCache),
  285. PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
  286. ModuleManager::~ModuleManager() { delete FirstVisitState; }
  287. void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
  288. llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
  289. // If the visitation order vector is the wrong size, recompute the order.
  290. if (VisitOrder.size() != Chain.size()) {
  291. unsigned N = size();
  292. VisitOrder.clear();
  293. VisitOrder.reserve(N);
  294. // Record the number of incoming edges for each module. When we
  295. // encounter a module with no incoming edges, push it into the queue
  296. // to seed the queue.
  297. SmallVector<ModuleFile *, 4> Queue;
  298. Queue.reserve(N);
  299. llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
  300. UnusedIncomingEdges.resize(size());
  301. for (ModuleFile &M : llvm::reverse(*this)) {
  302. unsigned Size = M.ImportedBy.size();
  303. UnusedIncomingEdges[M.Index] = Size;
  304. if (!Size)
  305. Queue.push_back(&M);
  306. }
  307. // Traverse the graph, making sure to visit a module before visiting any
  308. // of its dependencies.
  309. while (!Queue.empty()) {
  310. ModuleFile *CurrentModule = Queue.pop_back_val();
  311. VisitOrder.push_back(CurrentModule);
  312. // For any module that this module depends on, push it on the
  313. // stack (if it hasn't already been marked as visited).
  314. for (auto M = CurrentModule->Imports.rbegin(),
  315. MEnd = CurrentModule->Imports.rend();
  316. M != MEnd; ++M) {
  317. // Remove our current module as an impediment to visiting the
  318. // module we depend on. If we were the last unvisited module
  319. // that depends on this particular module, push it into the
  320. // queue to be visited.
  321. unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
  322. if (NumUnusedEdges && (--NumUnusedEdges == 0))
  323. Queue.push_back(*M);
  324. }
  325. }
  326. assert(VisitOrder.size() == N && "Visitation order is wrong?");
  327. delete FirstVisitState;
  328. FirstVisitState = nullptr;
  329. }
  330. VisitState *State = allocateVisitState();
  331. unsigned VisitNumber = State->NextVisitNumber++;
  332. // If the caller has provided us with a hit-set that came from the global
  333. // module index, mark every module file in common with the global module
  334. // index that is *not* in that set as 'visited'.
  335. if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
  336. for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
  337. {
  338. ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
  339. if (!ModuleFilesHit->count(M))
  340. State->VisitNumber[M->Index] = VisitNumber;
  341. }
  342. }
  343. for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
  344. ModuleFile *CurrentModule = VisitOrder[I];
  345. // Should we skip this module file?
  346. if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
  347. continue;
  348. // Visit the module.
  349. assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
  350. State->VisitNumber[CurrentModule->Index] = VisitNumber;
  351. if (!Visitor(*CurrentModule))
  352. continue;
  353. // The visitor has requested that cut off visitation of any
  354. // module that the current module depends on. To indicate this
  355. // behavior, we mark all of the reachable modules as having been visited.
  356. ModuleFile *NextModule = CurrentModule;
  357. do {
  358. // For any module that this module depends on, push it on the
  359. // stack (if it hasn't already been marked as visited).
  360. for (llvm::SetVector<ModuleFile *>::iterator
  361. M = NextModule->Imports.begin(),
  362. MEnd = NextModule->Imports.end();
  363. M != MEnd; ++M) {
  364. if (State->VisitNumber[(*M)->Index] != VisitNumber) {
  365. State->Stack.push_back(*M);
  366. State->VisitNumber[(*M)->Index] = VisitNumber;
  367. }
  368. }
  369. if (State->Stack.empty())
  370. break;
  371. // Pop the next module off the stack.
  372. NextModule = State->Stack.pop_back_val();
  373. } while (true);
  374. }
  375. returnVisitState(State);
  376. }
  377. bool ModuleManager::lookupModuleFile(StringRef FileName,
  378. off_t ExpectedSize,
  379. time_t ExpectedModTime,
  380. const FileEntry *&File) {
  381. if (FileName == "-") {
  382. File = nullptr;
  383. return false;
  384. }
  385. // Open the file immediately to ensure there is no race between stat'ing and
  386. // opening the file.
  387. File = FileMgr.getFile(FileName, /*OpenFile=*/true, /*CacheFailure=*/false);
  388. if (!File)
  389. return false;
  390. if ((ExpectedSize && ExpectedSize != File->getSize()) ||
  391. (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
  392. // Do not destroy File, as it may be referenced. If we need to rebuild it,
  393. // it will be destroyed by removeModules.
  394. return true;
  395. return false;
  396. }
  397. #ifndef NDEBUG
  398. namespace llvm {
  399. template<>
  400. struct GraphTraits<ModuleManager> {
  401. using NodeRef = ModuleFile *;
  402. using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
  403. using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
  404. static ChildIteratorType child_begin(NodeRef Node) {
  405. return Node->Imports.begin();
  406. }
  407. static ChildIteratorType child_end(NodeRef Node) {
  408. return Node->Imports.end();
  409. }
  410. static nodes_iterator nodes_begin(const ModuleManager &Manager) {
  411. return nodes_iterator(Manager.begin());
  412. }
  413. static nodes_iterator nodes_end(const ModuleManager &Manager) {
  414. return nodes_iterator(Manager.end());
  415. }
  416. };
  417. template<>
  418. struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
  419. explicit DOTGraphTraits(bool IsSimple = false)
  420. : DefaultDOTGraphTraits(IsSimple) {}
  421. static bool renderGraphFromBottomUp() { return true; }
  422. std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
  423. return M->ModuleName;
  424. }
  425. };
  426. } // namespace llvm
  427. void ModuleManager::viewGraph() {
  428. llvm::ViewGraph(*this, "Modules");
  429. }
  430. #endif