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