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