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