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