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