1 //===- Module.h - Describe a module -----------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Defines the clang::Module class, which describes a module in the
11 /// source code.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_BASIC_MODULE_H
16 #define LLVM_CLANG_BASIC_MODULE_H
17 
18 #include "clang/Basic/DirectoryEntry.h"
19 #include "clang/Basic/FileEntry.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include <array>
32 #include <cassert>
33 #include <cstdint>
34 #include <ctime>
35 #include <iterator>
36 #include <string>
37 #include <utility>
38 #include <vector>
39 
40 namespace llvm {
41 
42 class raw_ostream;
43 
44 } // namespace llvm
45 
46 namespace clang {
47 
48 class FileManager;
49 class LangOptions;
50 class TargetInfo;
51 
52 /// Describes the name of a module.
53 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
54 
55 /// The signature of a module, which is a hash of the AST content.
56 struct ASTFileSignature : std::array<uint8_t, 20> {
57   using BaseT = std::array<uint8_t, 20>;
58 
59   static constexpr size_t size = std::tuple_size<BaseT>::value;
60 
61   ASTFileSignature(BaseT S = {{0}}) : BaseT(std::move(S)) {}
62 
63   explicit operator bool() const { return *this != BaseT({{0}}); }
64 
65   /// Returns the value truncated to the size of an uint64_t.
66   uint64_t truncatedValue() const {
67     uint64_t Value = 0;
68     static_assert(sizeof(*this) >= sizeof(uint64_t), "No need to truncate.");
69     for (unsigned I = 0; I < sizeof(uint64_t); ++I)
70       Value |= static_cast<uint64_t>((*this)[I]) << (I * 8);
71     return Value;
72   }
73 
74   static ASTFileSignature create(StringRef Bytes) {
75     return create(Bytes.bytes_begin(), Bytes.bytes_end());
76   }
77 
78   static ASTFileSignature createDISentinel() {
79     ASTFileSignature Sentinel;
80     Sentinel.fill(0xFF);
81     return Sentinel;
82   }
83 
84   template <typename InputIt>
85   static ASTFileSignature create(InputIt First, InputIt Last) {
86     assert(std::distance(First, Last) == size &&
87            "Wrong amount of bytes to create an ASTFileSignature");
88 
89     ASTFileSignature Signature;
90     std::copy(First, Last, Signature.begin());
91     return Signature;
92   }
93 };
94 
95 /// Describes a module or submodule.
96 class Module {
97 public:
98   /// The name of this module.
99   std::string Name;
100 
101   /// The location of the module definition.
102   SourceLocation DefinitionLoc;
103 
104   enum ModuleKind {
105     /// This is a module that was defined by a module map and built out
106     /// of header files.
107     ModuleMapModule,
108 
109     /// This is a C++20 module interface unit.
110     ModuleInterfaceUnit,
111 
112     /// This is a C++ 20 module partition interface.
113     ModulePartitionInterface,
114 
115     /// This is a C++ 20 module partition implementation.
116     ModulePartitionImplementation,
117 
118     /// This is a fragment of the global module within some C++ module.
119     GlobalModuleFragment,
120 
121     /// This is the private module fragment within some C++ module.
122     PrivateModuleFragment,
123   };
124 
125   /// The kind of this module.
126   ModuleKind Kind = ModuleMapModule;
127 
128   /// The parent of this module. This will be NULL for the top-level
129   /// module.
130   Module *Parent;
131 
132   /// The build directory of this module. This is the directory in
133   /// which the module is notionally built, and relative to which its headers
134   /// are found.
135   const DirectoryEntry *Directory = nullptr;
136 
137   /// The presumed file name for the module map defining this module.
138   /// Only non-empty when building from preprocessed source.
139   std::string PresumedModuleMapFile;
140 
141   /// The umbrella header or directory.
142   llvm::PointerUnion<const FileEntry *, const DirectoryEntry *> Umbrella;
143 
144   /// The module signature.
145   ASTFileSignature Signature;
146 
147   /// The name of the umbrella entry, as written in the module map.
148   std::string UmbrellaAsWritten;
149 
150   // The path to the umbrella entry relative to the root module's \c Directory.
151   std::string UmbrellaRelativeToRootModuleDirectory;
152 
153   /// The module through which entities defined in this module will
154   /// eventually be exposed, for use in "private" modules.
155   std::string ExportAsModule;
156 
157   /// Does this Module scope describe part of the purview of a named C++ module?
158   bool isModulePurview() const {
159     return Kind == ModuleInterfaceUnit || Kind == ModulePartitionInterface ||
160            Kind == ModulePartitionImplementation ||
161            Kind == PrivateModuleFragment;
162   }
163 
164   /// Does this Module scope describe a fragment of the global module within
165   /// some C++ module.
166   bool isGlobalModule() const { return Kind == GlobalModuleFragment; }
167 
168 private:
169   /// The submodules of this module, indexed by name.
170   std::vector<Module *> SubModules;
171 
172   /// A mapping from the submodule name to the index into the
173   /// \c SubModules vector at which that submodule resides.
174   llvm::StringMap<unsigned> SubModuleIndex;
175 
176   /// The AST file if this is a top-level module which has a
177   /// corresponding serialized AST file, or null otherwise.
178   Optional<FileEntryRef> ASTFile;
179 
180   /// The top-level headers associated with this module.
181   llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
182 
183   /// top-level header filenames that aren't resolved to FileEntries yet.
184   std::vector<std::string> TopHeaderNames;
185 
186   /// Cache of modules visible to lookup in this module.
187   mutable llvm::DenseSet<const Module*> VisibleModulesCache;
188 
189   /// The ID used when referencing this module within a VisibleModuleSet.
190   unsigned VisibilityID;
191 
192 public:
193   enum HeaderKind {
194     HK_Normal,
195     HK_Textual,
196     HK_Private,
197     HK_PrivateTextual,
198     HK_Excluded
199   };
200   static const int NumHeaderKinds = HK_Excluded + 1;
201 
202   /// Information about a header directive as found in the module map
203   /// file.
204   struct Header {
205     std::string NameAsWritten;
206     std::string PathRelativeToRootModuleDirectory;
207     const FileEntry *Entry;
208 
209     explicit operator bool() { return Entry; }
210   };
211 
212   /// Information about a directory name as found in the module map
213   /// file.
214   struct DirectoryName {
215     std::string NameAsWritten;
216     std::string PathRelativeToRootModuleDirectory;
217     const DirectoryEntry *Entry;
218 
219     explicit operator bool() { return Entry; }
220   };
221 
222   /// The headers that are part of this module.
223   SmallVector<Header, 2> Headers[5];
224 
225   /// Stored information about a header directive that was found in the
226   /// module map file but has not been resolved to a file.
227   struct UnresolvedHeaderDirective {
228     HeaderKind Kind = HK_Normal;
229     SourceLocation FileNameLoc;
230     std::string FileName;
231     bool IsUmbrella = false;
232     bool HasBuiltinHeader = false;
233     Optional<off_t> Size;
234     Optional<time_t> ModTime;
235   };
236 
237   /// Headers that are mentioned in the module map file but that we have not
238   /// yet attempted to resolve to a file on the file system.
239   SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
240 
241   /// Headers that are mentioned in the module map file but could not be
242   /// found on the file system.
243   SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
244 
245   /// An individual requirement: a feature name and a flag indicating
246   /// the required state of that feature.
247   using Requirement = std::pair<std::string, bool>;
248 
249   /// The set of language features required to use this module.
250   ///
251   /// If any of these requirements are not available, the \c IsAvailable bit
252   /// will be false to indicate that this (sub)module is not available.
253   SmallVector<Requirement, 2> Requirements;
254 
255   /// A module with the same name that shadows this module.
256   Module *ShadowingModule = nullptr;
257 
258   /// Whether this module has declared itself unimportable, either because
259   /// it's missing a requirement from \p Requirements or because it's been
260   /// shadowed by another module.
261   unsigned IsUnimportable : 1;
262 
263   /// Whether we tried and failed to load a module file for this module.
264   unsigned HasIncompatibleModuleFile : 1;
265 
266   /// Whether this module is available in the current translation unit.
267   ///
268   /// If the module is missing headers or does not meet all requirements then
269   /// this bit will be 0.
270   unsigned IsAvailable : 1;
271 
272   /// Whether this module was loaded from a module file.
273   unsigned IsFromModuleFile : 1;
274 
275   /// Whether this is a framework module.
276   unsigned IsFramework : 1;
277 
278   /// Whether this is an explicit submodule.
279   unsigned IsExplicit : 1;
280 
281   /// Whether this is a "system" module (which assumes that all
282   /// headers in it are system headers).
283   unsigned IsSystem : 1;
284 
285   /// Whether this is an 'extern "C"' module (which implicitly puts all
286   /// headers in it within an 'extern "C"' block, and allows the module to be
287   /// imported within such a block).
288   unsigned IsExternC : 1;
289 
290   /// Whether this is an inferred submodule (module * { ... }).
291   unsigned IsInferred : 1;
292 
293   /// Whether we should infer submodules for this module based on
294   /// the headers.
295   ///
296   /// Submodules can only be inferred for modules with an umbrella header.
297   unsigned InferSubmodules : 1;
298 
299   /// Whether, when inferring submodules, the inferred submodules
300   /// should be explicit.
301   unsigned InferExplicitSubmodules : 1;
302 
303   /// Whether, when inferring submodules, the inferr submodules should
304   /// export all modules they import (e.g., the equivalent of "export *").
305   unsigned InferExportWildcard : 1;
306 
307   /// Whether the set of configuration macros is exhaustive.
308   ///
309   /// When the set of configuration macros is exhaustive, meaning
310   /// that no identifier not in this list should affect how the module is
311   /// built.
312   unsigned ConfigMacrosExhaustive : 1;
313 
314   /// Whether files in this module can only include non-modular headers
315   /// and headers from used modules.
316   unsigned NoUndeclaredIncludes : 1;
317 
318   /// Whether this module came from a "private" module map, found next
319   /// to a regular (public) module map.
320   unsigned ModuleMapIsPrivate : 1;
321 
322   /// Describes the visibility of the various names within a
323   /// particular module.
324   enum NameVisibilityKind {
325     /// All of the names in this module are hidden.
326     Hidden,
327     /// All of the names in this module are visible.
328     AllVisible
329   };
330 
331   /// The visibility of names within this particular module.
332   NameVisibilityKind NameVisibility;
333 
334   /// The location of the inferred submodule.
335   SourceLocation InferredSubmoduleLoc;
336 
337   /// The set of modules imported by this module, and on which this
338   /// module depends.
339   llvm::SmallSetVector<Module *, 2> Imports;
340 
341   /// Describes an exported module.
342   ///
343   /// The pointer is the module being re-exported, while the bit will be true
344   /// to indicate that this is a wildcard export.
345   using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
346 
347   /// The set of export declarations.
348   SmallVector<ExportDecl, 2> Exports;
349 
350   /// Describes an exported module that has not yet been resolved
351   /// (perhaps because the module it refers to has not yet been loaded).
352   struct UnresolvedExportDecl {
353     /// The location of the 'export' keyword in the module map file.
354     SourceLocation ExportLoc;
355 
356     /// The name of the module.
357     ModuleId Id;
358 
359     /// Whether this export declaration ends in a wildcard, indicating
360     /// that all of its submodules should be exported (rather than the named
361     /// module itself).
362     bool Wildcard;
363   };
364 
365   /// The set of export declarations that have yet to be resolved.
366   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
367 
368   /// The directly used modules.
369   SmallVector<Module *, 2> DirectUses;
370 
371   /// The set of use declarations that have yet to be resolved.
372   SmallVector<ModuleId, 2> UnresolvedDirectUses;
373 
374   /// When \c NoUndeclaredIncludes is true, the set of modules this module tried
375   /// to import but didn't because they are not direct uses.
376   llvm::SmallSetVector<const Module *, 2> UndeclaredUses;
377 
378   /// A library or framework to link against when an entity from this
379   /// module is used.
380   struct LinkLibrary {
381     LinkLibrary() = default;
382     LinkLibrary(const std::string &Library, bool IsFramework)
383         : Library(Library), IsFramework(IsFramework) {}
384 
385     /// The library to link against.
386     ///
387     /// This will typically be a library or framework name, but can also
388     /// be an absolute path to the library or framework.
389     std::string Library;
390 
391     /// Whether this is a framework rather than a library.
392     bool IsFramework = false;
393   };
394 
395   /// The set of libraries or frameworks to link against when
396   /// an entity from this module is used.
397   llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
398 
399   /// Autolinking uses the framework name for linking purposes
400   /// when this is false and the export_as name otherwise.
401   bool UseExportAsModuleLinkName = false;
402 
403   /// The set of "configuration macros", which are macros that
404   /// (intentionally) change how this module is built.
405   std::vector<std::string> ConfigMacros;
406 
407   /// An unresolved conflict with another module.
408   struct UnresolvedConflict {
409     /// The (unresolved) module id.
410     ModuleId Id;
411 
412     /// The message provided to the user when there is a conflict.
413     std::string Message;
414   };
415 
416   /// The list of conflicts for which the module-id has not yet been
417   /// resolved.
418   std::vector<UnresolvedConflict> UnresolvedConflicts;
419 
420   /// A conflict between two modules.
421   struct Conflict {
422     /// The module that this module conflicts with.
423     Module *Other;
424 
425     /// The message provided to the user when there is a conflict.
426     std::string Message;
427   };
428 
429   /// The list of conflicts.
430   std::vector<Conflict> Conflicts;
431 
432   /// Construct a new module or submodule.
433   Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
434          bool IsFramework, bool IsExplicit, unsigned VisibilityID);
435 
436   ~Module();
437 
438   /// Determine whether this module has been declared unimportable.
439   bool isUnimportable() const { return IsUnimportable; }
440 
441   /// Determine whether this module has been declared unimportable.
442   ///
443   /// \param LangOpts The language options used for the current
444   /// translation unit.
445   ///
446   /// \param Target The target options used for the current translation unit.
447   ///
448   /// \param Req If this module is unimportable because of a missing
449   /// requirement, this parameter will be set to one of the requirements that
450   /// is not met for use of this module.
451   ///
452   /// \param ShadowingModule If this module is unimportable because it is
453   /// shadowed, this parameter will be set to the shadowing module.
454   bool isUnimportable(const LangOptions &LangOpts, const TargetInfo &Target,
455                       Requirement &Req, Module *&ShadowingModule) const;
456 
457   /// Determine whether this module is available for use within the
458   /// current translation unit.
459   bool isAvailable() const { return IsAvailable; }
460 
461   /// Determine whether this module is available for use within the
462   /// current translation unit.
463   ///
464   /// \param LangOpts The language options used for the current
465   /// translation unit.
466   ///
467   /// \param Target The target options used for the current translation unit.
468   ///
469   /// \param Req If this module is unavailable because of a missing requirement,
470   /// this parameter will be set to one of the requirements that is not met for
471   /// use of this module.
472   ///
473   /// \param MissingHeader If this module is unavailable because of a missing
474   /// header, this parameter will be set to one of the missing headers.
475   ///
476   /// \param ShadowingModule If this module is unavailable because it is
477   /// shadowed, this parameter will be set to the shadowing module.
478   bool isAvailable(const LangOptions &LangOpts,
479                    const TargetInfo &Target,
480                    Requirement &Req,
481                    UnresolvedHeaderDirective &MissingHeader,
482                    Module *&ShadowingModule) const;
483 
484   /// Determine whether this module is a submodule.
485   bool isSubModule() const { return Parent != nullptr; }
486 
487   /// Check if this module is a (possibly transitive) submodule of \p Other.
488   ///
489   /// The 'A is a submodule of B' relation is a partial order based on the
490   /// the parent-child relationship between individual modules.
491   ///
492   /// Returns \c false if \p Other is \c nullptr.
493   bool isSubModuleOf(const Module *Other) const;
494 
495   /// Determine whether this module is a part of a framework,
496   /// either because it is a framework module or because it is a submodule
497   /// of a framework module.
498   bool isPartOfFramework() const {
499     for (const Module *Mod = this; Mod; Mod = Mod->Parent)
500       if (Mod->IsFramework)
501         return true;
502 
503     return false;
504   }
505 
506   /// Determine whether this module is a subframework of another
507   /// framework.
508   bool isSubFramework() const {
509     return IsFramework && Parent && Parent->isPartOfFramework();
510   }
511 
512   /// Set the parent of this module. This should only be used if the parent
513   /// could not be set during module creation.
514   void setParent(Module *M) {
515     assert(!Parent);
516     Parent = M;
517     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
518     Parent->SubModules.push_back(this);
519   }
520 
521   /// Is this a module partition.
522   bool isModulePartition() const {
523     return Kind == ModulePartitionInterface ||
524            Kind == ModulePartitionImplementation;
525   }
526 
527   /// Get the primary module interface name from a partition.
528   StringRef getPrimaryModuleInterfaceName() const {
529     if (isModulePartition()) {
530       auto pos = Name.find(':');
531       return StringRef(Name.data(), pos);
532     }
533     return Name;
534   }
535 
536   /// Retrieve the full name of this module, including the path from
537   /// its top-level module.
538   /// \param AllowStringLiterals If \c true, components that might not be
539   ///        lexically valid as identifiers will be emitted as string literals.
540   std::string getFullModuleName(bool AllowStringLiterals = false) const;
541 
542   /// Whether the full name of this module is equal to joining
543   /// \p nameParts with "."s.
544   ///
545   /// This is more efficient than getFullModuleName().
546   bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
547 
548   /// Retrieve the top-level module for this (sub)module, which may
549   /// be this module.
550   Module *getTopLevelModule() {
551     return const_cast<Module *>(
552              const_cast<const Module *>(this)->getTopLevelModule());
553   }
554 
555   /// Retrieve the top-level module for this (sub)module, which may
556   /// be this module.
557   const Module *getTopLevelModule() const;
558 
559   /// Retrieve the name of the top-level module.
560   StringRef getTopLevelModuleName() const {
561     return getTopLevelModule()->Name;
562   }
563 
564   /// The serialized AST file for this module, if one was created.
565   OptionalFileEntryRefDegradesToFileEntryPtr getASTFile() const {
566     return getTopLevelModule()->ASTFile;
567   }
568 
569   /// Set the serialized AST file for the top-level module of this module.
570   void setASTFile(Optional<FileEntryRef> File) {
571     assert((!File || !getASTFile() || getASTFile() == File) &&
572            "file path changed");
573     getTopLevelModule()->ASTFile = File;
574   }
575 
576   /// Retrieve the directory for which this module serves as the
577   /// umbrella.
578   DirectoryName getUmbrellaDir() const;
579 
580   /// Retrieve the header that serves as the umbrella header for this
581   /// module.
582   Header getUmbrellaHeader() const {
583     if (auto *FE = Umbrella.dyn_cast<const FileEntry *>())
584       return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
585                     FE};
586     return Header{};
587   }
588 
589   /// Determine whether this module has an umbrella directory that is
590   /// not based on an umbrella header.
591   bool hasUmbrellaDir() const {
592     return Umbrella && Umbrella.is<const DirectoryEntry *>();
593   }
594 
595   /// Add a top-level header associated with this module.
596   void addTopHeader(const FileEntry *File);
597 
598   /// Add a top-level header filename associated with this module.
599   void addTopHeaderFilename(StringRef Filename) {
600     TopHeaderNames.push_back(std::string(Filename));
601   }
602 
603   /// The top-level headers associated with this module.
604   ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
605 
606   /// Determine whether this module has declared its intention to
607   /// directly use another module.
608   bool directlyUses(const Module *Requested);
609 
610   /// Add the given feature requirement to the list of features
611   /// required by this module.
612   ///
613   /// \param Feature The feature that is required by this module (and
614   /// its submodules).
615   ///
616   /// \param RequiredState The required state of this feature: \c true
617   /// if it must be present, \c false if it must be absent.
618   ///
619   /// \param LangOpts The set of language options that will be used to
620   /// evaluate the availability of this feature.
621   ///
622   /// \param Target The target options that will be used to evaluate the
623   /// availability of this feature.
624   void addRequirement(StringRef Feature, bool RequiredState,
625                       const LangOptions &LangOpts,
626                       const TargetInfo &Target);
627 
628   /// Mark this module and all of its submodules as unavailable.
629   void markUnavailable(bool Unimportable);
630 
631   /// Find the submodule with the given name.
632   ///
633   /// \returns The submodule if found, or NULL otherwise.
634   Module *findSubmodule(StringRef Name) const;
635   Module *findOrInferSubmodule(StringRef Name);
636 
637   /// Determine whether the specified module would be visible to
638   /// a lookup at the end of this module.
639   ///
640   /// FIXME: This may return incorrect results for (submodules of) the
641   /// module currently being built, if it's queried before we see all
642   /// of its imports.
643   bool isModuleVisible(const Module *M) const {
644     if (VisibleModulesCache.empty())
645       buildVisibleModulesCache();
646     return VisibleModulesCache.count(M);
647   }
648 
649   unsigned getVisibilityID() const { return VisibilityID; }
650 
651   using submodule_iterator = std::vector<Module *>::iterator;
652   using submodule_const_iterator = std::vector<Module *>::const_iterator;
653 
654   submodule_iterator submodule_begin() { return SubModules.begin(); }
655   submodule_const_iterator submodule_begin() const {return SubModules.begin();}
656   submodule_iterator submodule_end()   { return SubModules.end(); }
657   submodule_const_iterator submodule_end() const { return SubModules.end(); }
658 
659   llvm::iterator_range<submodule_iterator> submodules() {
660     return llvm::make_range(submodule_begin(), submodule_end());
661   }
662   llvm::iterator_range<submodule_const_iterator> submodules() const {
663     return llvm::make_range(submodule_begin(), submodule_end());
664   }
665 
666   /// Appends this module's list of exported modules to \p Exported.
667   ///
668   /// This provides a subset of immediately imported modules (the ones that are
669   /// directly exported), not the complete set of exported modules.
670   void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
671 
672   static StringRef getModuleInputBufferName() {
673     return "<module-includes>";
674   }
675 
676   /// Print the module map for this module to the given stream.
677   void print(raw_ostream &OS, unsigned Indent = 0, bool Dump = false) const;
678 
679   /// Dump the contents of this module to the given output stream.
680   void dump() const;
681 
682 private:
683   void buildVisibleModulesCache() const;
684 };
685 
686 /// A set of visible modules.
687 class VisibleModuleSet {
688 public:
689   VisibleModuleSet() = default;
690   VisibleModuleSet(VisibleModuleSet &&O)
691       : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
692     O.ImportLocs.clear();
693     ++O.Generation;
694   }
695 
696   /// Move from another visible modules set. Guaranteed to leave the source
697   /// empty and bump the generation on both.
698   VisibleModuleSet &operator=(VisibleModuleSet &&O) {
699     ImportLocs = std::move(O.ImportLocs);
700     O.ImportLocs.clear();
701     ++O.Generation;
702     ++Generation;
703     return *this;
704   }
705 
706   /// Get the current visibility generation. Incremented each time the
707   /// set of visible modules changes in any way.
708   unsigned getGeneration() const { return Generation; }
709 
710   /// Determine whether a module is visible.
711   bool isVisible(const Module *M) const {
712     return getImportLoc(M).isValid();
713   }
714 
715   /// Get the location at which the import of a module was triggered.
716   SourceLocation getImportLoc(const Module *M) const {
717     return M->getVisibilityID() < ImportLocs.size()
718                ? ImportLocs[M->getVisibilityID()]
719                : SourceLocation();
720   }
721 
722   /// A callback to call when a module is made visible (directly or
723   /// indirectly) by a call to \ref setVisible.
724   using VisibleCallback = llvm::function_ref<void(Module *M)>;
725 
726   /// A callback to call when a module conflict is found. \p Path
727   /// consists of a sequence of modules from the conflicting module to the one
728   /// made visible, where each was exported by the next.
729   using ConflictCallback =
730       llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
731                          StringRef Message)>;
732 
733   /// Make a specific module visible.
734   void setVisible(Module *M, SourceLocation Loc,
735                   VisibleCallback Vis = [](Module *) {},
736                   ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
737                                            StringRef) {});
738 
739 private:
740   /// Import locations for each visible module. Indexed by the module's
741   /// VisibilityID.
742   std::vector<SourceLocation> ImportLocs;
743 
744   /// Visibility generation, bumped every time the visibility state changes.
745   unsigned Generation = 0;
746 };
747 
748 /// Abstracts clang modules and precompiled header files and holds
749 /// everything needed to generate debug info for an imported module
750 /// or PCH.
751 class ASTSourceDescriptor {
752   StringRef PCHModuleName;
753   StringRef Path;
754   StringRef ASTFile;
755   ASTFileSignature Signature;
756   Module *ClangModule = nullptr;
757 
758 public:
759   ASTSourceDescriptor() = default;
760   ASTSourceDescriptor(StringRef Name, StringRef Path, StringRef ASTFile,
761                       ASTFileSignature Signature)
762       : PCHModuleName(std::move(Name)), Path(std::move(Path)),
763         ASTFile(std::move(ASTFile)), Signature(Signature) {}
764   ASTSourceDescriptor(Module &M);
765 
766   std::string getModuleName() const;
767   StringRef getPath() const { return Path; }
768   StringRef getASTFile() const { return ASTFile; }
769   ASTFileSignature getSignature() const { return Signature; }
770   Module *getModuleOrNull() const { return ClangModule; }
771 };
772 
773 
774 } // namespace clang
775 
776 #endif // LLVM_CLANG_BASIC_MODULE_H
777