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