ModuleManager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
  97. if (ec)
  98. ErrorStr = ec.message();
  99. } else
  100. New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
  101. if (!New->Buffer)
  102. return Missing;
  103. }
  104. // Initialize the stream
  105. New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
  106. (const unsigned char *)New->Buffer->getBufferEnd());
  107. }
  108. if (ImportedBy) {
  109. ModuleEntry->ImportedBy.insert(ImportedBy);
  110. ImportedBy->Imports.insert(ModuleEntry);
  111. } else {
  112. if (!ModuleEntry->DirectlyImported)
  113. ModuleEntry->ImportLoc = ImportLoc;
  114. ModuleEntry->DirectlyImported = true;
  115. }
  116. Module = ModuleEntry;
  117. return NewModule? NewlyLoaded : AlreadyLoaded;
  118. }
  119. static void getModuleFileAncestors(
  120. ModuleFile *F,
  121. llvm::SmallPtrSetImpl<ModuleFile *> &Ancestors) {
  122. Ancestors.insert(F);
  123. for (ModuleFile *Importer : F->ImportedBy)
  124. getModuleFileAncestors(Importer, Ancestors);
  125. }
  126. void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
  127. ModuleMap *modMap) {
  128. if (first == last)
  129. return;
  130. // Collect the set of module file pointers that we'll be removing.
  131. llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
  132. // The last module file caused the load failure, so it and its ancestors in
  133. // the module dependency tree will be rebuilt (or there was an error), so
  134. // there should be no references to them. Collect the files to remove from
  135. // the cache below, since rebuilding them will create new files at the old
  136. // locations.
  137. llvm::SmallPtrSet<ModuleFile *, 4> Ancestors;
  138. getModuleFileAncestors(*(last-1), Ancestors);
  139. assert(Ancestors.count(*first) && "non-dependent module loaded");
  140. // Remove any references to the now-destroyed modules.
  141. for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
  142. Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
  143. return victimSet.count(MF);
  144. });
  145. }
  146. // Delete the modules and erase them from the various structures.
  147. for (ModuleIterator victim = first; victim != last; ++victim) {
  148. Modules.erase((*victim)->File);
  149. if (modMap) {
  150. StringRef ModuleName = (*victim)->ModuleName;
  151. if (Module *mod = modMap->findModule(ModuleName)) {
  152. mod->setASTFile(nullptr);
  153. }
  154. }
  155. if (Ancestors.count(*victim))
  156. FileMgr.invalidateCache((*victim)->File);
  157. delete *victim;
  158. }
  159. // Remove the modules from the chain.
  160. Chain.erase(first, last);
  161. }
  162. void ModuleManager::addInMemoryBuffer(StringRef FileName,
  163. llvm::MemoryBuffer *Buffer) {
  164. const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
  165. Buffer->getBufferSize(), 0);
  166. InMemoryBuffers[Entry] = Buffer;
  167. }
  168. ModuleManager::VisitState *ModuleManager::allocateVisitState() {
  169. // Fast path: if we have a cached state, use it.
  170. if (FirstVisitState) {
  171. VisitState *Result = FirstVisitState;
  172. FirstVisitState = FirstVisitState->NextState;
  173. Result->NextState = nullptr;
  174. return Result;
  175. }
  176. // Allocate and return a new state.
  177. return new VisitState(size());
  178. }
  179. void ModuleManager::returnVisitState(VisitState *State) {
  180. assert(State->NextState == nullptr && "Visited state is in list?");
  181. State->NextState = FirstVisitState;
  182. FirstVisitState = State;
  183. }
  184. void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
  185. GlobalIndex = Index;
  186. if (!GlobalIndex) {
  187. ModulesInCommonWithGlobalIndex.clear();
  188. return;
  189. }
  190. // Notify the global module index about all of the modules we've already
  191. // loaded.
  192. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  193. if (!GlobalIndex->loadedModuleFile(Chain[I])) {
  194. ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
  195. }
  196. }
  197. }
  198. void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
  199. if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
  200. return;
  201. ModulesInCommonWithGlobalIndex.push_back(MF);
  202. }
  203. ModuleManager::ModuleManager(FileManager &FileMgr)
  204. : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(nullptr) {}
  205. ModuleManager::~ModuleManager() {
  206. for (unsigned i = 0, e = Chain.size(); i != e; ++i)
  207. delete Chain[e - i - 1];
  208. delete FirstVisitState;
  209. }
  210. void
  211. ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
  212. void *UserData,
  213. llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
  214. // If the visitation order vector is the wrong size, recompute the order.
  215. if (VisitOrder.size() != Chain.size()) {
  216. unsigned N = size();
  217. VisitOrder.clear();
  218. VisitOrder.reserve(N);
  219. // Record the number of incoming edges for each module. When we
  220. // encounter a module with no incoming edges, push it into the queue
  221. // to seed the queue.
  222. SmallVector<ModuleFile *, 4> Queue;
  223. Queue.reserve(N);
  224. llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
  225. UnusedIncomingEdges.reserve(size());
  226. for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
  227. if (unsigned Size = (*M)->ImportedBy.size())
  228. UnusedIncomingEdges.push_back(Size);
  229. else {
  230. UnusedIncomingEdges.push_back(0);
  231. Queue.push_back(*M);
  232. }
  233. }
  234. // Traverse the graph, making sure to visit a module before visiting any
  235. // of its dependencies.
  236. unsigned QueueStart = 0;
  237. while (QueueStart < Queue.size()) {
  238. ModuleFile *CurrentModule = Queue[QueueStart++];
  239. VisitOrder.push_back(CurrentModule);
  240. // For any module that this module depends on, push it on the
  241. // stack (if it hasn't already been marked as visited).
  242. for (llvm::SetVector<ModuleFile *>::iterator
  243. M = CurrentModule->Imports.begin(),
  244. MEnd = CurrentModule->Imports.end();
  245. M != MEnd; ++M) {
  246. // Remove our current module as an impediment to visiting the
  247. // module we depend on. If we were the last unvisited module
  248. // that depends on this particular module, push it into the
  249. // queue to be visited.
  250. unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
  251. if (NumUnusedEdges && (--NumUnusedEdges == 0))
  252. Queue.push_back(*M);
  253. }
  254. }
  255. assert(VisitOrder.size() == N && "Visitation order is wrong?");
  256. delete FirstVisitState;
  257. FirstVisitState = nullptr;
  258. }
  259. VisitState *State = allocateVisitState();
  260. unsigned VisitNumber = State->NextVisitNumber++;
  261. // If the caller has provided us with a hit-set that came from the global
  262. // module index, mark every module file in common with the global module
  263. // index that is *not* in that set as 'visited'.
  264. if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
  265. for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
  266. {
  267. ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
  268. if (!ModuleFilesHit->count(M))
  269. State->VisitNumber[M->Index] = VisitNumber;
  270. }
  271. }
  272. for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
  273. ModuleFile *CurrentModule = VisitOrder[I];
  274. // Should we skip this module file?
  275. if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
  276. continue;
  277. // Visit the module.
  278. assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
  279. State->VisitNumber[CurrentModule->Index] = VisitNumber;
  280. if (!Visitor(*CurrentModule, UserData))
  281. continue;
  282. // The visitor has requested that cut off visitation of any
  283. // module that the current module depends on. To indicate this
  284. // behavior, we mark all of the reachable modules as having been visited.
  285. ModuleFile *NextModule = CurrentModule;
  286. do {
  287. // For any module that this module depends on, push it on the
  288. // stack (if it hasn't already been marked as visited).
  289. for (llvm::SetVector<ModuleFile *>::iterator
  290. M = NextModule->Imports.begin(),
  291. MEnd = NextModule->Imports.end();
  292. M != MEnd; ++M) {
  293. if (State->VisitNumber[(*M)->Index] != VisitNumber) {
  294. State->Stack.push_back(*M);
  295. State->VisitNumber[(*M)->Index] = VisitNumber;
  296. }
  297. }
  298. if (State->Stack.empty())
  299. break;
  300. // Pop the next module off the stack.
  301. NextModule = State->Stack.pop_back_val();
  302. } while (true);
  303. }
  304. returnVisitState(State);
  305. }
  306. /// \brief Perform a depth-first visit of the current module.
  307. static bool visitDepthFirst(ModuleFile &M,
  308. bool (*Visitor)(ModuleFile &M, bool Preorder,
  309. void *UserData),
  310. void *UserData,
  311. SmallVectorImpl<bool> &Visited) {
  312. // Preorder visitation
  313. if (Visitor(M, /*Preorder=*/true, UserData))
  314. return true;
  315. // Visit children
  316. for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
  317. IMEnd = M.Imports.end();
  318. IM != IMEnd; ++IM) {
  319. if (Visited[(*IM)->Index])
  320. continue;
  321. Visited[(*IM)->Index] = true;
  322. if (visitDepthFirst(**IM, Visitor, UserData, Visited))
  323. return true;
  324. }
  325. // Postorder visitation
  326. return Visitor(M, /*Preorder=*/false, UserData);
  327. }
  328. void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
  329. void *UserData),
  330. void *UserData) {
  331. SmallVector<bool, 16> Visited(size(), false);
  332. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  333. if (Visited[Chain[I]->Index])
  334. continue;
  335. Visited[Chain[I]->Index] = true;
  336. if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
  337. return;
  338. }
  339. }
  340. bool ModuleManager::lookupModuleFile(StringRef FileName,
  341. off_t ExpectedSize,
  342. time_t ExpectedModTime,
  343. const FileEntry *&File) {
  344. // Open the file immediately to ensure there is no race between stat'ing and
  345. // opening the file.
  346. File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
  347. if (!File && FileName != "-") {
  348. return false;
  349. }
  350. if ((ExpectedSize && ExpectedSize != File->getSize()) ||
  351. (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
  352. // Do not destroy File, as it may be referenced. If we need to rebuild it,
  353. // it will be destroyed by removeModules.
  354. return true;
  355. return false;
  356. }
  357. #ifndef NDEBUG
  358. namespace llvm {
  359. template<>
  360. struct GraphTraits<ModuleManager> {
  361. typedef ModuleFile NodeType;
  362. typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
  363. typedef ModuleManager::ModuleConstIterator nodes_iterator;
  364. static ChildIteratorType child_begin(NodeType *Node) {
  365. return Node->Imports.begin();
  366. }
  367. static ChildIteratorType child_end(NodeType *Node) {
  368. return Node->Imports.end();
  369. }
  370. static nodes_iterator nodes_begin(const ModuleManager &Manager) {
  371. return Manager.begin();
  372. }
  373. static nodes_iterator nodes_end(const ModuleManager &Manager) {
  374. return Manager.end();
  375. }
  376. };
  377. template<>
  378. struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
  379. explicit DOTGraphTraits(bool IsSimple = false)
  380. : DefaultDOTGraphTraits(IsSimple) { }
  381. static bool renderGraphFromBottomUp() {
  382. return true;
  383. }
  384. std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
  385. return M->ModuleName;
  386. }
  387. };
  388. }
  389. void ModuleManager::viewGraph() {
  390. llvm::ViewGraph(*this, "Modules");
  391. }
  392. #endif