xref: /freebsd/contrib/llvm-project/clang/include/clang/Basic/Module.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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/PointerIntPair.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include <array>
31 #include <cassert>
32 #include <cstdint>
33 #include <ctime>
34 #include <iterator>
35 #include <optional>
36 #include <string>
37 #include <utility>
38 #include <variant>
39 #include <vector>
40 
41 namespace llvm {
42 
43 class raw_ostream;
44 
45 } // namespace llvm
46 
47 namespace clang {
48 
49 class FileManager;
50 class LangOptions;
51 class ModuleMap;
52 class TargetInfo;
53 
54 /// Describes the name of a module.
55 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
56 
57 /// The signature of a module, which is a hash of the AST content.
58 struct ASTFileSignature : std::array<uint8_t, 20> {
59   using BaseT = std::array<uint8_t, 20>;
60 
61   static constexpr size_t size = std::tuple_size<BaseT>::value;
62 
BaseTASTFileSignature63   ASTFileSignature(BaseT S = {{0}}) : BaseT(std::move(S)) {}
64 
65   explicit operator bool() const { return *this != BaseT({{0}}); }
66 
67   // Support implicit cast to ArrayRef.  Note that ASTFileSignature::size
68   // prevents implicit cast to ArrayRef because one of the implicit constructors
69   // of ArrayRef requires access to BaseT::size.
70   operator ArrayRef<uint8_t>() const { return ArrayRef<uint8_t>(data(), size); }
71 
72   /// Returns the value truncated to the size of an uint64_t.
truncatedValueASTFileSignature73   uint64_t truncatedValue() const {
74     uint64_t Value = 0;
75     static_assert(sizeof(*this) >= sizeof(uint64_t), "No need to truncate.");
76     for (unsigned I = 0; I < sizeof(uint64_t); ++I)
77       Value |= static_cast<uint64_t>((*this)[I]) << (I * 8);
78     return Value;
79   }
80 
createASTFileSignature81   static ASTFileSignature create(std::array<uint8_t, 20> Bytes) {
82     return ASTFileSignature(std::move(Bytes));
83   }
84 
createDISentinelASTFileSignature85   static ASTFileSignature createDISentinel() {
86     ASTFileSignature Sentinel;
87     Sentinel.fill(0xFF);
88     return Sentinel;
89   }
90 
createDummyASTFileSignature91   static ASTFileSignature createDummy() {
92     ASTFileSignature Dummy;
93     Dummy.fill(0x00);
94     return Dummy;
95   }
96 
97   template <typename InputIt>
createASTFileSignature98   static ASTFileSignature create(InputIt First, InputIt Last) {
99     assert(std::distance(First, Last) == size &&
100            "Wrong amount of bytes to create an ASTFileSignature");
101 
102     ASTFileSignature Signature;
103     std::copy(First, Last, Signature.begin());
104     return Signature;
105   }
106 };
107 
108 /// The set of attributes that can be attached to a module.
109 struct ModuleAttributes {
110   /// Whether this is a system module.
111   LLVM_PREFERRED_TYPE(bool)
112   unsigned IsSystem : 1;
113 
114   /// Whether this is an extern "C" module.
115   LLVM_PREFERRED_TYPE(bool)
116   unsigned IsExternC : 1;
117 
118   /// Whether this is an exhaustive set of configuration macros.
119   LLVM_PREFERRED_TYPE(bool)
120   unsigned IsExhaustive : 1;
121 
122   /// Whether files in this module can only include non-modular headers
123   /// and headers from used modules.
124   LLVM_PREFERRED_TYPE(bool)
125   unsigned NoUndeclaredIncludes : 1;
126 
ModuleAttributesModuleAttributes127   ModuleAttributes()
128       : IsSystem(false), IsExternC(false), IsExhaustive(false),
129         NoUndeclaredIncludes(false) {}
130 };
131 
132 /// Required to construct a Module.
133 ///
134 /// This tag type is only constructible by ModuleMap, guaranteeing it ownership
135 /// of all Module instances.
136 class ModuleConstructorTag {
137   explicit ModuleConstructorTag() = default;
138   friend ModuleMap;
139 };
140 
141 /// Describes a module or submodule.
142 ///
143 /// Aligned to 8 bytes to allow for llvm::PointerIntPair<Module *, 3>.
144 class alignas(8) Module {
145 public:
146   /// The name of this module.
147   std::string Name;
148 
149   /// The location of the module definition.
150   SourceLocation DefinitionLoc;
151 
152   // FIXME: Consider if reducing the size of this enum (having Partition and
153   // Named modules only) then representing interface/implementation separately
154   // is more efficient.
155   enum ModuleKind {
156     /// This is a module that was defined by a module map and built out
157     /// of header files.
158     ModuleMapModule,
159 
160     /// This is a C++20 header unit.
161     ModuleHeaderUnit,
162 
163     /// This is a C++20 module interface unit.
164     ModuleInterfaceUnit,
165 
166     /// This is a C++20 module implementation unit.
167     ModuleImplementationUnit,
168 
169     /// This is a C++20 module partition interface.
170     ModulePartitionInterface,
171 
172     /// This is a C++20 module partition implementation.
173     ModulePartitionImplementation,
174 
175     /// This is the explicit Global Module Fragment of a modular TU.
176     /// As per C++ [module.global.frag].
177     ExplicitGlobalModuleFragment,
178 
179     /// This is the private module fragment within some C++ module.
180     PrivateModuleFragment,
181 
182     /// This is an implicit fragment of the global module which contains
183     /// only language linkage declarations (made in the purview of the
184     /// named module).
185     ImplicitGlobalModuleFragment,
186   };
187 
188   /// The kind of this module.
189   ModuleKind Kind = ModuleMapModule;
190 
191   /// The parent of this module. This will be NULL for the top-level
192   /// module.
193   Module *Parent;
194 
195   /// The build directory of this module. This is the directory in
196   /// which the module is notionally built, and relative to which its headers
197   /// are found.
198   OptionalDirectoryEntryRef Directory;
199 
200   /// The presumed file name for the module map defining this module.
201   /// Only non-empty when building from preprocessed source.
202   std::string PresumedModuleMapFile;
203 
204   /// The umbrella header or directory.
205   std::variant<std::monostate, FileEntryRef, DirectoryEntryRef> Umbrella;
206 
207   /// The module signature.
208   ASTFileSignature Signature;
209 
210   /// The name of the umbrella entry, as written in the module map.
211   std::string UmbrellaAsWritten;
212 
213   // The path to the umbrella entry relative to the root module's \c Directory.
214   std::string UmbrellaRelativeToRootModuleDirectory;
215 
216   /// The module through which entities defined in this module will
217   /// eventually be exposed, for use in "private" modules.
218   std::string ExportAsModule;
219 
220   /// For the debug info, the path to this module's .apinotes file, if any.
221   std::string APINotesFile;
222 
223   /// Does this Module is a named module of a standard named module?
isNamedModule()224   bool isNamedModule() const {
225     switch (Kind) {
226     case ModuleInterfaceUnit:
227     case ModuleImplementationUnit:
228     case ModulePartitionInterface:
229     case ModulePartitionImplementation:
230     case PrivateModuleFragment:
231       return true;
232     default:
233       return false;
234     }
235   }
236 
237   /// Does this Module scope describe a fragment of the global module within
238   /// some C++ module.
isGlobalModule()239   bool isGlobalModule() const {
240     return isExplicitGlobalModule() || isImplicitGlobalModule();
241   }
isExplicitGlobalModule()242   bool isExplicitGlobalModule() const {
243     return Kind == ExplicitGlobalModuleFragment;
244   }
isImplicitGlobalModule()245   bool isImplicitGlobalModule() const {
246     return Kind == ImplicitGlobalModuleFragment;
247   }
248 
isPrivateModule()249   bool isPrivateModule() const { return Kind == PrivateModuleFragment; }
250 
isModuleMapModule()251   bool isModuleMapModule() const { return Kind == ModuleMapModule; }
252 
253 private:
254   /// The submodules of this module, indexed by name.
255   std::vector<Module *> SubModules;
256 
257   /// A mapping from the submodule name to the index into the
258   /// \c SubModules vector at which that submodule resides.
259   mutable llvm::StringMap<unsigned> SubModuleIndex;
260 
261   /// The AST file if this is a top-level module which has a
262   /// corresponding serialized AST file, or null otherwise.
263   OptionalFileEntryRef ASTFile;
264 
265   /// The top-level headers associated with this module.
266   llvm::SmallSetVector<FileEntryRef, 2> TopHeaders;
267 
268   /// top-level header filenames that aren't resolved to FileEntries yet.
269   std::vector<std::string> TopHeaderNames;
270 
271   /// Cache of modules visible to lookup in this module.
272   mutable llvm::DenseSet<const Module*> VisibleModulesCache;
273 
274   /// The ID used when referencing this module within a VisibleModuleSet.
275   unsigned VisibilityID;
276 
277 public:
278   enum HeaderKind {
279     HK_Normal,
280     HK_Textual,
281     HK_Private,
282     HK_PrivateTextual,
283     HK_Excluded
284   };
285   /// Information about a header directive as found in the module map
286   /// file.
287   struct Header {
288     std::string NameAsWritten;
289     std::string PathRelativeToRootModuleDirectory;
290     FileEntryRef Entry;
291   };
292 
293 private:
294   static const int NumHeaderKinds = HK_Excluded + 1;
295   // The begin index for a HeaderKind also acts the end index of HeaderKind - 1.
296   // The extra element at the end acts as the end index of the last HeaderKind.
297   unsigned HeaderKindBeginIndex[NumHeaderKinds + 1] = {};
298   SmallVector<Header, 2> HeadersStorage;
299 
300 public:
getAllHeaders()301   ArrayRef<Header> getAllHeaders() const { return HeadersStorage; }
getHeaders(HeaderKind HK)302   ArrayRef<Header> getHeaders(HeaderKind HK) const {
303     assert(HK < NumHeaderKinds && "Invalid Module::HeaderKind");
304     auto BeginIt = HeadersStorage.begin() + HeaderKindBeginIndex[HK];
305     auto EndIt = HeadersStorage.begin() + HeaderKindBeginIndex[HK + 1];
306     return {BeginIt, EndIt};
307   }
addHeader(HeaderKind HK,Header H)308   void addHeader(HeaderKind HK, Header H) {
309     assert(HK < NumHeaderKinds && "Invalid Module::HeaderKind");
310     auto EndIt = HeadersStorage.begin() + HeaderKindBeginIndex[HK + 1];
311     HeadersStorage.insert(EndIt, std::move(H));
312     for (unsigned HKI = HK + 1; HKI != NumHeaderKinds + 1; ++HKI)
313       ++HeaderKindBeginIndex[HKI];
314   }
315 
316   /// Information about a directory name as found in the module map file.
317   struct DirectoryName {
318     std::string NameAsWritten;
319     std::string PathRelativeToRootModuleDirectory;
320     DirectoryEntryRef Entry;
321   };
322 
323   /// Stored information about a header directive that was found in the
324   /// module map file but has not been resolved to a file.
325   struct UnresolvedHeaderDirective {
326     HeaderKind Kind = HK_Normal;
327     SourceLocation FileNameLoc;
328     std::string FileName;
329     bool IsUmbrella = false;
330     bool HasBuiltinHeader = false;
331     std::optional<off_t> Size;
332     std::optional<time_t> ModTime;
333   };
334 
335   /// Headers that are mentioned in the module map file but that we have not
336   /// yet attempted to resolve to a file on the file system.
337   SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
338 
339   /// Headers that are mentioned in the module map file but could not be
340   /// found on the file system.
341   SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
342 
343   struct Requirement {
344     std::string FeatureName;
345     bool RequiredState;
346   };
347 
348   /// The set of language features required to use this module.
349   ///
350   /// If any of these requirements are not available, the \c IsAvailable bit
351   /// will be false to indicate that this (sub)module is not available.
352   SmallVector<Requirement, 2> Requirements;
353 
354   /// A module with the same name that shadows this module.
355   Module *ShadowingModule = nullptr;
356 
357   /// Whether this module has declared itself unimportable, either because
358   /// it's missing a requirement from \p Requirements or because it's been
359   /// shadowed by another module.
360   LLVM_PREFERRED_TYPE(bool)
361   unsigned IsUnimportable : 1;
362 
363   /// Whether we tried and failed to load a module file for this module.
364   LLVM_PREFERRED_TYPE(bool)
365   unsigned HasIncompatibleModuleFile : 1;
366 
367   /// Whether this module is available in the current translation unit.
368   ///
369   /// If the module is missing headers or does not meet all requirements then
370   /// this bit will be 0.
371   LLVM_PREFERRED_TYPE(bool)
372   unsigned IsAvailable : 1;
373 
374   /// Whether this module was loaded from a module file.
375   LLVM_PREFERRED_TYPE(bool)
376   unsigned IsFromModuleFile : 1;
377 
378   /// Whether this is a framework module.
379   LLVM_PREFERRED_TYPE(bool)
380   unsigned IsFramework : 1;
381 
382   /// Whether this is an explicit submodule.
383   LLVM_PREFERRED_TYPE(bool)
384   unsigned IsExplicit : 1;
385 
386   /// Whether this is a "system" module (which assumes that all
387   /// headers in it are system headers).
388   LLVM_PREFERRED_TYPE(bool)
389   unsigned IsSystem : 1;
390 
391   /// Whether this is an 'extern "C"' module (which implicitly puts all
392   /// headers in it within an 'extern "C"' block, and allows the module to be
393   /// imported within such a block).
394   LLVM_PREFERRED_TYPE(bool)
395   unsigned IsExternC : 1;
396 
397   /// Whether this is an inferred submodule (module * { ... }).
398   LLVM_PREFERRED_TYPE(bool)
399   unsigned IsInferred : 1;
400 
401   /// Whether we should infer submodules for this module based on
402   /// the headers.
403   ///
404   /// Submodules can only be inferred for modules with an umbrella header.
405   LLVM_PREFERRED_TYPE(bool)
406   unsigned InferSubmodules : 1;
407 
408   /// Whether, when inferring submodules, the inferred submodules
409   /// should be explicit.
410   LLVM_PREFERRED_TYPE(bool)
411   unsigned InferExplicitSubmodules : 1;
412 
413   /// Whether, when inferring submodules, the inferr submodules should
414   /// export all modules they import (e.g., the equivalent of "export *").
415   LLVM_PREFERRED_TYPE(bool)
416   unsigned InferExportWildcard : 1;
417 
418   /// Whether the set of configuration macros is exhaustive.
419   ///
420   /// When the set of configuration macros is exhaustive, meaning
421   /// that no identifier not in this list should affect how the module is
422   /// built.
423   LLVM_PREFERRED_TYPE(bool)
424   unsigned ConfigMacrosExhaustive : 1;
425 
426   /// Whether files in this module can only include non-modular headers
427   /// and headers from used modules.
428   LLVM_PREFERRED_TYPE(bool)
429   unsigned NoUndeclaredIncludes : 1;
430 
431   /// Whether this module came from a "private" module map, found next
432   /// to a regular (public) module map.
433   LLVM_PREFERRED_TYPE(bool)
434   unsigned ModuleMapIsPrivate : 1;
435 
436   /// Whether this C++20 named modules doesn't need an initializer.
437   /// This is only meaningful for C++20 modules.
438   LLVM_PREFERRED_TYPE(bool)
439   unsigned NamedModuleHasInit : 1;
440 
441   /// Describes the visibility of the various names within a
442   /// particular module.
443   enum NameVisibilityKind {
444     /// All of the names in this module are hidden.
445     Hidden,
446     /// All of the names in this module are visible.
447     AllVisible
448   };
449 
450   /// The visibility of names within this particular module.
451   NameVisibilityKind NameVisibility;
452 
453   /// The location of the inferred submodule.
454   SourceLocation InferredSubmoduleLoc;
455 
456   /// The set of modules imported by this module, and on which this
457   /// module depends.
458   llvm::SmallSetVector<Module *, 2> Imports;
459 
460   /// The set of top-level modules that affected the compilation of this module,
461   /// but were not imported.
462   llvm::SmallSetVector<Module *, 2> AffectingClangModules;
463 
464   /// Describes an exported module.
465   ///
466   /// The pointer is the module being re-exported, while the bit will be true
467   /// to indicate that this is a wildcard export.
468   using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
469 
470   /// The set of export declarations.
471   SmallVector<ExportDecl, 2> Exports;
472 
473   /// Describes an exported module that has not yet been resolved
474   /// (perhaps because the module it refers to has not yet been loaded).
475   struct UnresolvedExportDecl {
476     /// The location of the 'export' keyword in the module map file.
477     SourceLocation ExportLoc;
478 
479     /// The name of the module.
480     ModuleId Id;
481 
482     /// Whether this export declaration ends in a wildcard, indicating
483     /// that all of its submodules should be exported (rather than the named
484     /// module itself).
485     bool Wildcard;
486   };
487 
488   /// The set of export declarations that have yet to be resolved.
489   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
490 
491   /// The directly used modules.
492   SmallVector<Module *, 2> DirectUses;
493 
494   /// The set of use declarations that have yet to be resolved.
495   SmallVector<ModuleId, 2> UnresolvedDirectUses;
496 
497   /// When \c NoUndeclaredIncludes is true, the set of modules this module tried
498   /// to import but didn't because they are not direct uses.
499   llvm::SmallSetVector<const Module *, 2> UndeclaredUses;
500 
501   /// A library or framework to link against when an entity from this
502   /// module is used.
503   struct LinkLibrary {
504     LinkLibrary() = default;
LinkLibraryLinkLibrary505     LinkLibrary(const std::string &Library, bool IsFramework)
506         : Library(Library), IsFramework(IsFramework) {}
507 
508     /// The library to link against.
509     ///
510     /// This will typically be a library or framework name, but can also
511     /// be an absolute path to the library or framework.
512     std::string Library;
513 
514     /// Whether this is a framework rather than a library.
515     bool IsFramework = false;
516   };
517 
518   /// The set of libraries or frameworks to link against when
519   /// an entity from this module is used.
520   llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
521 
522   /// Autolinking uses the framework name for linking purposes
523   /// when this is false and the export_as name otherwise.
524   bool UseExportAsModuleLinkName = false;
525 
526   /// The set of "configuration macros", which are macros that
527   /// (intentionally) change how this module is built.
528   std::vector<std::string> ConfigMacros;
529 
530   /// An unresolved conflict with another module.
531   struct UnresolvedConflict {
532     /// The (unresolved) module id.
533     ModuleId Id;
534 
535     /// The message provided to the user when there is a conflict.
536     std::string Message;
537   };
538 
539   /// The list of conflicts for which the module-id has not yet been
540   /// resolved.
541   std::vector<UnresolvedConflict> UnresolvedConflicts;
542 
543   /// A conflict between two modules.
544   struct Conflict {
545     /// The module that this module conflicts with.
546     Module *Other;
547 
548     /// The message provided to the user when there is a conflict.
549     std::string Message;
550   };
551 
552   /// The list of conflicts.
553   std::vector<Conflict> Conflicts;
554 
555   /// Construct a new module or submodule.
556   Module(ModuleConstructorTag, StringRef Name, SourceLocation DefinitionLoc,
557          Module *Parent, bool IsFramework, bool IsExplicit,
558          unsigned VisibilityID);
559 
560   ~Module();
561 
562   /// Determine whether this module has been declared unimportable.
isUnimportable()563   bool isUnimportable() const { return IsUnimportable; }
564 
565   /// Determine whether this module has been declared unimportable.
566   ///
567   /// \param LangOpts The language options used for the current
568   /// translation unit.
569   ///
570   /// \param Target The target options used for the current translation unit.
571   ///
572   /// \param Req If this module is unimportable because of a missing
573   /// requirement, this parameter will be set to one of the requirements that
574   /// is not met for use of this module.
575   ///
576   /// \param ShadowingModule If this module is unimportable because it is
577   /// shadowed, this parameter will be set to the shadowing module.
578   bool isUnimportable(const LangOptions &LangOpts, const TargetInfo &Target,
579                       Requirement &Req, Module *&ShadowingModule) const;
580 
581   /// Determine whether this module can be built in this compilation.
582   bool isForBuilding(const LangOptions &LangOpts) const;
583 
584   /// Determine whether this module is available for use within the
585   /// current translation unit.
isAvailable()586   bool isAvailable() const { return IsAvailable; }
587 
588   /// Determine whether this module is available for use within the
589   /// current translation unit.
590   ///
591   /// \param LangOpts The language options used for the current
592   /// translation unit.
593   ///
594   /// \param Target The target options used for the current translation unit.
595   ///
596   /// \param Req If this module is unavailable because of a missing requirement,
597   /// this parameter will be set to one of the requirements that is not met for
598   /// use of this module.
599   ///
600   /// \param MissingHeader If this module is unavailable because of a missing
601   /// header, this parameter will be set to one of the missing headers.
602   ///
603   /// \param ShadowingModule If this module is unavailable because it is
604   /// shadowed, this parameter will be set to the shadowing module.
605   bool isAvailable(const LangOptions &LangOpts,
606                    const TargetInfo &Target,
607                    Requirement &Req,
608                    UnresolvedHeaderDirective &MissingHeader,
609                    Module *&ShadowingModule) const;
610 
611   /// Determine whether this module is a submodule.
isSubModule()612   bool isSubModule() const { return Parent != nullptr; }
613 
614   /// Check if this module is a (possibly transitive) submodule of \p Other.
615   ///
616   /// The 'A is a submodule of B' relation is a partial order based on the
617   /// the parent-child relationship between individual modules.
618   ///
619   /// Returns \c false if \p Other is \c nullptr.
620   bool isSubModuleOf(const Module *Other) const;
621 
622   /// Determine whether this module is a part of a framework,
623   /// either because it is a framework module or because it is a submodule
624   /// of a framework module.
isPartOfFramework()625   bool isPartOfFramework() const {
626     for (const Module *Mod = this; Mod; Mod = Mod->Parent)
627       if (Mod->IsFramework)
628         return true;
629 
630     return false;
631   }
632 
633   /// Determine whether this module is a subframework of another
634   /// framework.
isSubFramework()635   bool isSubFramework() const {
636     return IsFramework && Parent && Parent->isPartOfFramework();
637   }
638 
639   /// Set the parent of this module. This should only be used if the parent
640   /// could not be set during module creation.
setParent(Module * M)641   void setParent(Module *M) {
642     assert(!Parent);
643     Parent = M;
644     Parent->SubModules.push_back(this);
645   }
646 
647   /// Is this module have similar semantics as headers.
isHeaderLikeModule()648   bool isHeaderLikeModule() const {
649     return isModuleMapModule() || isHeaderUnit();
650   }
651 
652   /// Is this a module partition.
isModulePartition()653   bool isModulePartition() const {
654     return Kind == ModulePartitionInterface ||
655            Kind == ModulePartitionImplementation;
656   }
657 
658   /// Is this a module partition implementation unit.
isModulePartitionImplementation()659   bool isModulePartitionImplementation() const {
660     return Kind == ModulePartitionImplementation;
661   }
662 
663   /// Is this a module implementation.
isModuleImplementation()664   bool isModuleImplementation() const {
665     return Kind == ModuleImplementationUnit;
666   }
667 
668   /// Is this module a header unit.
isHeaderUnit()669   bool isHeaderUnit() const { return Kind == ModuleHeaderUnit; }
670   // Is this a C++20 module interface or a partition.
isInterfaceOrPartition()671   bool isInterfaceOrPartition() const {
672     return Kind == ModuleInterfaceUnit || isModulePartition();
673   }
674 
675   /// Is this a C++20 named module unit.
isNamedModuleUnit()676   bool isNamedModuleUnit() const {
677     return isInterfaceOrPartition() || isModuleImplementation();
678   }
679 
isModuleInterfaceUnit()680   bool isModuleInterfaceUnit() const {
681     return Kind == ModuleInterfaceUnit || Kind == ModulePartitionInterface;
682   }
683 
isNamedModuleInterfaceHasInit()684   bool isNamedModuleInterfaceHasInit() const { return NamedModuleHasInit; }
685 
686   /// Get the primary module interface name from a partition.
getPrimaryModuleInterfaceName()687   StringRef getPrimaryModuleInterfaceName() const {
688     // Technically, global module fragment belongs to global module. And global
689     // module has no name: [module.unit]p6:
690     //   The global module has no name, no module interface unit, and is not
691     //   introduced by any module-declaration.
692     //
693     // <global> is the default name showed in module map.
694     if (isGlobalModule())
695       return "<global>";
696 
697     if (isModulePartition()) {
698       auto pos = Name.find(':');
699       return StringRef(Name.data(), pos);
700     }
701 
702     if (isPrivateModule())
703       return getTopLevelModuleName();
704 
705     return Name;
706   }
707 
708   /// Retrieve the full name of this module, including the path from
709   /// its top-level module.
710   /// \param AllowStringLiterals If \c true, components that might not be
711   ///        lexically valid as identifiers will be emitted as string literals.
712   std::string getFullModuleName(bool AllowStringLiterals = false) const;
713 
714   /// Whether the full name of this module is equal to joining
715   /// \p nameParts with "."s.
716   ///
717   /// This is more efficient than getFullModuleName().
718   bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
719 
720   /// Retrieve the top-level module for this (sub)module, which may
721   /// be this module.
getTopLevelModule()722   Module *getTopLevelModule() {
723     return const_cast<Module *>(
724              const_cast<const Module *>(this)->getTopLevelModule());
725   }
726 
727   /// Retrieve the top-level module for this (sub)module, which may
728   /// be this module.
729   const Module *getTopLevelModule() const;
730 
731   /// Retrieve the name of the top-level module.
getTopLevelModuleName()732   StringRef getTopLevelModuleName() const {
733     return getTopLevelModule()->Name;
734   }
735 
736   /// The serialized AST file for this module, if one was created.
getASTFile()737   OptionalFileEntryRef getASTFile() const {
738     return getTopLevelModule()->ASTFile;
739   }
740 
741   /// Set the serialized AST file for the top-level module of this module.
setASTFile(OptionalFileEntryRef File)742   void setASTFile(OptionalFileEntryRef File) {
743     assert((!getASTFile() || getASTFile() == File) && "file path changed");
744     getTopLevelModule()->ASTFile = File;
745   }
746 
747   /// Retrieve the umbrella directory as written.
getUmbrellaDirAsWritten()748   std::optional<DirectoryName> getUmbrellaDirAsWritten() const {
749     if (const auto *Dir = std::get_if<DirectoryEntryRef>(&Umbrella))
750       return DirectoryName{UmbrellaAsWritten,
751                            UmbrellaRelativeToRootModuleDirectory, *Dir};
752     return std::nullopt;
753   }
754 
755   /// Retrieve the umbrella header as written.
getUmbrellaHeaderAsWritten()756   std::optional<Header> getUmbrellaHeaderAsWritten() const {
757     if (const auto *Hdr = std::get_if<FileEntryRef>(&Umbrella))
758       return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
759                     *Hdr};
760     return std::nullopt;
761   }
762 
763   /// Get the effective umbrella directory for this module: either the one
764   /// explicitly written in the module map file, or the parent of the umbrella
765   /// header.
766   OptionalDirectoryEntryRef getEffectiveUmbrellaDir() const;
767 
768   /// Add a top-level header associated with this module.
769   void addTopHeader(FileEntryRef File);
770 
771   /// Add a top-level header filename associated with this module.
addTopHeaderFilename(StringRef Filename)772   void addTopHeaderFilename(StringRef Filename) {
773     TopHeaderNames.push_back(std::string(Filename));
774   }
775 
776   /// The top-level headers associated with this module.
777   ArrayRef<FileEntryRef> getTopHeaders(FileManager &FileMgr);
778 
779   /// Determine whether this module has declared its intention to
780   /// directly use another module.
781   bool directlyUses(const Module *Requested);
782 
783   /// Add the given feature requirement to the list of features
784   /// required by this module.
785   ///
786   /// \param Feature The feature that is required by this module (and
787   /// its submodules).
788   ///
789   /// \param RequiredState The required state of this feature: \c true
790   /// if it must be present, \c false if it must be absent.
791   ///
792   /// \param LangOpts The set of language options that will be used to
793   /// evaluate the availability of this feature.
794   ///
795   /// \param Target The target options that will be used to evaluate the
796   /// availability of this feature.
797   void addRequirement(StringRef Feature, bool RequiredState,
798                       const LangOptions &LangOpts,
799                       const TargetInfo &Target);
800 
801   /// Mark this module and all of its submodules as unavailable.
802   void markUnavailable(bool Unimportable);
803 
804   /// Find the submodule with the given name.
805   ///
806   /// \returns The submodule if found, or NULL otherwise.
807   Module *findSubmodule(StringRef Name) const;
808 
809   /// Get the Global Module Fragment (sub-module) for this module, it there is
810   /// one.
811   ///
812   /// \returns The GMF sub-module if found, or NULL otherwise.
813   Module *getGlobalModuleFragment() const;
814 
815   /// Get the Private Module Fragment (sub-module) for this module, it there is
816   /// one.
817   ///
818   /// \returns The PMF sub-module if found, or NULL otherwise.
819   Module *getPrivateModuleFragment() const;
820 
821   /// Determine whether the specified module would be visible to
822   /// a lookup at the end of this module.
823   ///
824   /// FIXME: This may return incorrect results for (submodules of) the
825   /// module currently being built, if it's queried before we see all
826   /// of its imports.
isModuleVisible(const Module * M)827   bool isModuleVisible(const Module *M) const {
828     if (VisibleModulesCache.empty())
829       buildVisibleModulesCache();
830     return VisibleModulesCache.count(M);
831   }
832 
getVisibilityID()833   unsigned getVisibilityID() const { return VisibilityID; }
834 
835   using submodule_iterator = std::vector<Module *>::iterator;
836   using submodule_const_iterator = std::vector<Module *>::const_iterator;
837 
submodules()838   llvm::iterator_range<submodule_iterator> submodules() {
839     return llvm::make_range(SubModules.begin(), SubModules.end());
840   }
submodules()841   llvm::iterator_range<submodule_const_iterator> submodules() const {
842     return llvm::make_range(SubModules.begin(), SubModules.end());
843   }
844 
845   /// Appends this module's list of exported modules to \p Exported.
846   ///
847   /// This provides a subset of immediately imported modules (the ones that are
848   /// directly exported), not the complete set of exported modules.
849   void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
850 
getModuleInputBufferName()851   static StringRef getModuleInputBufferName() {
852     return "<module-includes>";
853   }
854 
855   /// Print the module map for this module to the given stream.
856   void print(raw_ostream &OS, unsigned Indent = 0, bool Dump = false) const;
857 
858   /// Dump the contents of this module to the given output stream.
859   void dump() const;
860 
861 private:
862   void buildVisibleModulesCache() const;
863 };
864 
865 /// A set of visible modules.
866 class VisibleModuleSet {
867 public:
868   VisibleModuleSet() = default;
VisibleModuleSet(VisibleModuleSet && O)869   VisibleModuleSet(VisibleModuleSet &&O)
870       : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
871     O.ImportLocs.clear();
872     ++O.Generation;
873   }
874 
875   /// Move from another visible modules set. Guaranteed to leave the source
876   /// empty and bump the generation on both.
877   VisibleModuleSet &operator=(VisibleModuleSet &&O) {
878     ImportLocs = std::move(O.ImportLocs);
879     O.ImportLocs.clear();
880     ++O.Generation;
881     ++Generation;
882     return *this;
883   }
884 
885   /// Get the current visibility generation. Incremented each time the
886   /// set of visible modules changes in any way.
getGeneration()887   unsigned getGeneration() const { return Generation; }
888 
889   /// Determine whether a module is visible.
isVisible(const Module * M)890   bool isVisible(const Module *M) const {
891     return getImportLoc(M).isValid();
892   }
893 
894   /// Get the location at which the import of a module was triggered.
getImportLoc(const Module * M)895   SourceLocation getImportLoc(const Module *M) const {
896     return M && M->getVisibilityID() < ImportLocs.size()
897                ? ImportLocs[M->getVisibilityID()]
898                : SourceLocation();
899   }
900 
901   /// A callback to call when a module is made visible (directly or
902   /// indirectly) by a call to \ref setVisible.
903   using VisibleCallback = llvm::function_ref<void(Module *M)>;
904 
905   /// A callback to call when a module conflict is found. \p Path
906   /// consists of a sequence of modules from the conflicting module to the one
907   /// made visible, where each was exported by the next.
908   using ConflictCallback =
909       llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
910                          StringRef Message)>;
911 
912   /// Make a specific module visible.
913   void setVisible(
914       Module *M, SourceLocation Loc, bool IncludeExports = true,
915       VisibleCallback Vis = [](Module *) {},
916       ConflictCallback Cb = [](ArrayRef<Module *>, Module *, StringRef) {});
917 
918 private:
919   /// Import locations for each visible module. Indexed by the module's
920   /// VisibilityID.
921   std::vector<SourceLocation> ImportLocs;
922 
923   /// Visibility generation, bumped every time the visibility state changes.
924   unsigned Generation = 0;
925 };
926 
927 } // namespace clang
928 
929 #endif // LLVM_CLANG_BASIC_MODULE_H
930