ModuleManager.h revision fa69fc19121da3fc5673ccc00d4e8afa5b540a4f
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
15#ifndef LLVM_CLANG_SERIALIZATION_MODULE_MANAGER_H
16#define LLVM_CLANG_SERIALIZATION_MODULE_MANAGER_H
17
18#include "clang/Basic/FileManager.h"
19#include "clang/Serialization/Module.h"
20#include "llvm/ADT/DenseMap.h"
21
22namespace clang {
23
24class GlobalModuleIndex;
25class ModuleMap;
26
27namespace serialization {
28
29/// \brief Manages the set of modules loaded by an AST reader.
30class ModuleManager {
31  /// \brief The chain of AST files. The first entry is the one named by the
32  /// user, the last one is the one that doesn't depend on anything further.
33  SmallVector<ModuleFile *, 2> Chain;
34
35  /// \brief All loaded modules, indexed by name.
36  llvm::DenseMap<const FileEntry *, ModuleFile *> Modules;
37
38  /// \brief FileManager that handles translating between filenames and
39  /// FileEntry *.
40  FileManager &FileMgr;
41
42  /// \brief A lookup of in-memory (virtual file) buffers
43  llvm::DenseMap<const FileEntry *, llvm::MemoryBuffer *> InMemoryBuffers;
44
45  /// \brief The visitation order.
46  SmallVector<ModuleFile *, 4> VisitOrder;
47
48  /// \brief The list of module files that both we and the global module index
49  /// know about.
50  ///
51  /// Either the global index or the module manager may have modules that the
52  /// other does not know about, because the global index can be out-of-date
53  /// (in which case the module manager could have modules it does not) and
54  /// this particular translation unit might not have loaded all of the modules
55  /// known to the global index.
56  SmallVector<ModuleFile *, 4> ModulesInCommonWithGlobalIndex;
57
58  /// \brief The global module index, if one is attached.
59  ///
60  /// The global module index will actually be owned by the ASTReader; this is
61  /// just an non-owning pointer.
62  GlobalModuleIndex *GlobalIndex;
63
64  /// \brief State used by the "visit" operation to avoid malloc traffic in
65  /// calls to visit().
66  struct VisitState {
67    explicit VisitState(unsigned N)
68      : VisitNumber(N, 0), NextVisitNumber(1), NextState(0)
69    {
70      Stack.reserve(N);
71    }
72
73    ~VisitState() {
74      delete NextState;
75    }
76
77    /// \brief The stack used when marking the imports of a particular module
78    /// as not-to-be-visited.
79    SmallVector<ModuleFile *, 4> Stack;
80
81    /// \brief The visit number of each module file, which indicates when
82    /// this module file was last visited.
83    SmallVector<unsigned, 4> VisitNumber;
84
85    /// \brief The next visit number to use to mark visited module files.
86    unsigned NextVisitNumber;
87
88    /// \brief The next visit state.
89    VisitState *NextState;
90  };
91
92  /// \brief The first visit() state in the chain.
93  VisitState *FirstVisitState;
94
95  VisitState *allocateVisitState();
96  void returnVisitState(VisitState *State);
97
98public:
99  typedef SmallVector<ModuleFile*, 2>::iterator ModuleIterator;
100  typedef SmallVector<ModuleFile*, 2>::const_iterator ModuleConstIterator;
101  typedef SmallVector<ModuleFile*, 2>::reverse_iterator ModuleReverseIterator;
102  typedef std::pair<uint32_t, StringRef> ModuleOffset;
103
104  explicit ModuleManager(FileManager &FileMgr);
105  ~ModuleManager();
106
107  /// \brief Forward iterator to traverse all loaded modules.  This is reverse
108  /// source-order.
109  ModuleIterator begin() { return Chain.begin(); }
110  /// \brief Forward iterator end-point to traverse all loaded modules
111  ModuleIterator end() { return Chain.end(); }
112
113  /// \brief Const forward iterator to traverse all loaded modules.  This is
114  /// in reverse source-order.
115  ModuleConstIterator begin() const { return Chain.begin(); }
116  /// \brief Const forward iterator end-point to traverse all loaded modules
117  ModuleConstIterator end() const { return Chain.end(); }
118
119  /// \brief Reverse iterator to traverse all loaded modules.  This is in
120  /// source order.
121  ModuleReverseIterator rbegin() { return Chain.rbegin(); }
122  /// \brief Reverse iterator end-point to traverse all loaded modules.
123  ModuleReverseIterator rend() { return Chain.rend(); }
124
125  /// \brief Returns the primary module associated with the manager, that is,
126  /// the first module loaded
127  ModuleFile &getPrimaryModule() { return *Chain[0]; }
128
129  /// \brief Returns the primary module associated with the manager, that is,
130  /// the first module loaded.
131  ModuleFile &getPrimaryModule() const { return *Chain[0]; }
132
133  /// \brief Returns the module associated with the given index
134  ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; }
135
136  /// \brief Returns the module associated with the given name
137  ModuleFile *lookup(StringRef Name);
138
139  /// \brief Returns the in-memory (virtual file) buffer with the given name
140  llvm::MemoryBuffer *lookupBuffer(StringRef Name);
141
142  /// \brief Number of modules loaded
143  unsigned size() const { return Chain.size(); }
144
145  /// \brief The result of attempting to add a new module.
146  enum AddModuleResult {
147    /// \brief The module file had already been loaded.
148    AlreadyLoaded,
149    /// \brief The module file was just loaded in response to this call.
150    NewlyLoaded,
151    /// \brief The module file is missing.
152    Missing,
153    /// \brief The module file is out-of-date.
154    OutOfDate
155  };
156
157  /// \brief Attempts to create a new module and add it to the list of known
158  /// modules.
159  ///
160  /// \param FileName The file name of the module to be loaded.
161  ///
162  /// \param Type The kind of module being loaded.
163  ///
164  /// \param ImportLoc The location at which the module is imported.
165  ///
166  /// \param ImportedBy The module that is importing this module, or NULL if
167  /// this module is imported directly by the user.
168  ///
169  /// \param Generation The generation in which this module was loaded.
170  ///
171  /// \param ExpectedSize The expected size of the module file, used for
172  /// validation. This will be zero if unknown.
173  ///
174  /// \param ExpectedModTime The expected modification time of the module
175  /// file, used for validation. This will be zero if unknown.
176  ///
177  /// \param Module A pointer to the module file if the module was successfully
178  /// loaded.
179  ///
180  /// \param ErrorStr Will be set to a non-empty string if any errors occurred
181  /// while trying to load the module.
182  ///
183  /// \return A pointer to the module that corresponds to this file name,
184  /// and a value indicating whether the module was loaded.
185  AddModuleResult addModule(StringRef FileName, ModuleKind Type,
186                            SourceLocation ImportLoc,
187                            ModuleFile *ImportedBy, unsigned Generation,
188                            off_t ExpectedSize, time_t ExpectedModTime,
189                            ModuleFile *&Module,
190                            std::string &ErrorStr);
191
192  /// \brief Remove the given set of modules.
193  void removeModules(ModuleIterator first, ModuleIterator last,
194                     ModuleMap *modMap);
195
196  /// \brief Add an in-memory buffer the list of known buffers
197  void addInMemoryBuffer(StringRef FileName, llvm::MemoryBuffer *Buffer);
198
199  /// \brief Set the global module index.
200  void setGlobalIndex(GlobalModuleIndex *Index);
201
202  /// \brief Notification from the AST reader that the given module file
203  /// has been "accepted", and will not (can not) be unloaded.
204  void moduleFileAccepted(ModuleFile *MF);
205
206  /// \brief Visit each of the modules.
207  ///
208  /// This routine visits each of the modules, starting with the
209  /// "root" modules that no other loaded modules depend on, and
210  /// proceeding to the leaf modules, visiting each module only once
211  /// during the traversal.
212  ///
213  /// This traversal is intended to support various "lookup"
214  /// operations that can find data in any of the loaded modules.
215  ///
216  /// \param Visitor A visitor function that will be invoked with each
217  /// module and the given user data pointer. The return value must be
218  /// convertible to bool; when false, the visitation continues to
219  /// modules that the current module depends on. When true, the
220  /// visitation skips any modules that the current module depends on.
221  ///
222  /// \param UserData User data associated with the visitor object, which
223  /// will be passed along to the visitor.
224  ///
225  /// \param ModuleFilesHit If non-NULL, contains the set of module files
226  /// that we know we need to visit because the global module index told us to.
227  /// Any module that is known to both the global module index and the module
228  /// manager that is *not* in this set can be skipped.
229  void visit(bool (*Visitor)(ModuleFile &M, void *UserData), void *UserData,
230             llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit = 0);
231
232  /// \brief Visit each of the modules with a depth-first traversal.
233  ///
234  /// This routine visits each of the modules known to the module
235  /// manager using a depth-first search, starting with the first
236  /// loaded module. The traversal invokes the callback both before
237  /// traversing the children (preorder traversal) and after
238  /// traversing the children (postorder traversal).
239  ///
240  /// \param Visitor A visitor function that will be invoked with each
241  /// module and given a \c Preorder flag that indicates whether we're
242  /// visiting the module before or after visiting its children.  The
243  /// visitor may return true at any time to abort the depth-first
244  /// visitation.
245  ///
246  /// \param UserData User data ssociated with the visitor object,
247  /// which will be passed along to the user.
248  void visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
249                                       void *UserData),
250                       void *UserData);
251
252  /// \brief Attempt to resolve the given module file name to a file entry.
253  ///
254  /// \param FileName The name of the module file.
255  ///
256  /// \param ExpectedSize The size that the module file is expected to have.
257  /// If the actual size differs, the resolver should return \c true.
258  ///
259  /// \param ExpectedModTime The modification time that the module file is
260  /// expected to have. If the actual modification time differs, the resolver
261  /// should return \c true.
262  ///
263  /// \param File Will be set to the file if there is one, or null
264  /// otherwise.
265  ///
266  /// \returns True if a file exists but does not meet the size/
267  /// modification time criteria, false if the file is either available and
268  /// suitable, or is missing.
269  bool lookupModuleFile(StringRef FileName,
270                        off_t ExpectedSize,
271                        time_t ExpectedModTime,
272                        const FileEntry *&File);
273
274  /// \brief View the graphviz representation of the module graph.
275  void viewGraph();
276};
277
278} } // end namespace clang::serialization
279
280#endif
281