ModuleManager.cpp 14 KB

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