ModuleManager.cpp 17 KB

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