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