ModuleManager.cpp 18 KB

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