ModuleManager.cpp 17 KB

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