ModuleManager.cpp 15 KB

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