xref: /freebsd/contrib/llvm-project/clang/include/clang/Basic/Module.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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   struct Requirement {
288     std::string FeatureName;
289     bool RequiredState;
290   };
291 
292   /// The set of language features required to use this module.
293   ///
294   /// If any of these requirements are not available, the \c IsAvailable bit
295   /// will be false to indicate that this (sub)module is not available.
296   SmallVector<Requirement, 2> Requirements;
297 
298   /// A module with the same name that shadows this module.
299   Module *ShadowingModule = nullptr;
300 
301   /// Whether this module has declared itself unimportable, either because
302   /// it's missing a requirement from \p Requirements or because it's been
303   /// shadowed by another module.
304   LLVM_PREFERRED_TYPE(bool)
305   unsigned IsUnimportable : 1;
306 
307   /// Whether we tried and failed to load a module file for this module.
308   LLVM_PREFERRED_TYPE(bool)
309   unsigned HasIncompatibleModuleFile : 1;
310 
311   /// Whether this module is available in the current translation unit.
312   ///
313   /// If the module is missing headers or does not meet all requirements then
314   /// this bit will be 0.
315   LLVM_PREFERRED_TYPE(bool)
316   unsigned IsAvailable : 1;
317 
318   /// Whether this module was loaded from a module file.
319   LLVM_PREFERRED_TYPE(bool)
320   unsigned IsFromModuleFile : 1;
321 
322   /// Whether this is a framework module.
323   LLVM_PREFERRED_TYPE(bool)
324   unsigned IsFramework : 1;
325 
326   /// Whether this is an explicit submodule.
327   LLVM_PREFERRED_TYPE(bool)
328   unsigned IsExplicit : 1;
329 
330   /// Whether this is a "system" module (which assumes that all
331   /// headers in it are system headers).
332   LLVM_PREFERRED_TYPE(bool)
333   unsigned IsSystem : 1;
334 
335   /// Whether this is an 'extern "C"' module (which implicitly puts all
336   /// headers in it within an 'extern "C"' block, and allows the module to be
337   /// imported within such a block).
338   LLVM_PREFERRED_TYPE(bool)
339   unsigned IsExternC : 1;
340 
341   /// Whether this is an inferred submodule (module * { ... }).
342   LLVM_PREFERRED_TYPE(bool)
343   unsigned IsInferred : 1;
344 
345   /// Whether we should infer submodules for this module based on
346   /// the headers.
347   ///
348   /// Submodules can only be inferred for modules with an umbrella header.
349   LLVM_PREFERRED_TYPE(bool)
350   unsigned InferSubmodules : 1;
351 
352   /// Whether, when inferring submodules, the inferred submodules
353   /// should be explicit.
354   LLVM_PREFERRED_TYPE(bool)
355   unsigned InferExplicitSubmodules : 1;
356 
357   /// Whether, when inferring submodules, the inferr submodules should
358   /// export all modules they import (e.g., the equivalent of "export *").
359   LLVM_PREFERRED_TYPE(bool)
360   unsigned InferExportWildcard : 1;
361 
362   /// Whether the set of configuration macros is exhaustive.
363   ///
364   /// When the set of configuration macros is exhaustive, meaning
365   /// that no identifier not in this list should affect how the module is
366   /// built.
367   LLVM_PREFERRED_TYPE(bool)
368   unsigned ConfigMacrosExhaustive : 1;
369 
370   /// Whether files in this module can only include non-modular headers
371   /// and headers from used modules.
372   LLVM_PREFERRED_TYPE(bool)
373   unsigned NoUndeclaredIncludes : 1;
374 
375   /// Whether this module came from a "private" module map, found next
376   /// to a regular (public) module map.
377   LLVM_PREFERRED_TYPE(bool)
378   unsigned ModuleMapIsPrivate : 1;
379 
380   /// Whether this C++20 named modules doesn't need an initializer.
381   /// This is only meaningful for C++20 modules.
382   LLVM_PREFERRED_TYPE(bool)
383   unsigned NamedModuleHasInit : 1;
384 
385   /// Describes the visibility of the various names within a
386   /// particular module.
387   enum NameVisibilityKind {
388     /// All of the names in this module are hidden.
389     Hidden,
390     /// All of the names in this module are visible.
391     AllVisible
392   };
393 
394   /// The visibility of names within this particular module.
395   NameVisibilityKind NameVisibility;
396 
397   /// The location of the inferred submodule.
398   SourceLocation InferredSubmoduleLoc;
399 
400   /// The set of modules imported by this module, and on which this
401   /// module depends.
402   llvm::SmallSetVector<Module *, 2> Imports;
403 
404   /// The set of top-level modules that affected the compilation of this module,
405   /// but were not imported.
406   llvm::SmallSetVector<Module *, 2> AffectingClangModules;
407 
408   /// Describes an exported module.
409   ///
410   /// The pointer is the module being re-exported, while the bit will be true
411   /// to indicate that this is a wildcard export.
412   using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
413 
414   /// The set of export declarations.
415   SmallVector<ExportDecl, 2> Exports;
416 
417   /// Describes an exported module that has not yet been resolved
418   /// (perhaps because the module it refers to has not yet been loaded).
419   struct UnresolvedExportDecl {
420     /// The location of the 'export' keyword in the module map file.
421     SourceLocation ExportLoc;
422 
423     /// The name of the module.
424     ModuleId Id;
425 
426     /// Whether this export declaration ends in a wildcard, indicating
427     /// that all of its submodules should be exported (rather than the named
428     /// module itself).
429     bool Wildcard;
430   };
431 
432   /// The set of export declarations that have yet to be resolved.
433   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
434 
435   /// The directly used modules.
436   SmallVector<Module *, 2> DirectUses;
437 
438   /// The set of use declarations that have yet to be resolved.
439   SmallVector<ModuleId, 2> UnresolvedDirectUses;
440 
441   /// When \c NoUndeclaredIncludes is true, the set of modules this module tried
442   /// to import but didn't because they are not direct uses.
443   llvm::SmallSetVector<const Module *, 2> UndeclaredUses;
444 
445   /// A library or framework to link against when an entity from this
446   /// module is used.
447   struct LinkLibrary {
448     LinkLibrary() = default;
LinkLibraryLinkLibrary449     LinkLibrary(const std::string &Library, bool IsFramework)
450         : Library(Library), IsFramework(IsFramework) {}
451 
452     /// The library to link against.
453     ///
454     /// This will typically be a library or framework name, but can also
455     /// be an absolute path to the library or framework.
456     std::string Library;
457 
458     /// Whether this is a framework rather than a library.
459     bool IsFramework = false;
460   };
461 
462   /// The set of libraries or frameworks to link against when
463   /// an entity from this module is used.
464   llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
465 
466   /// Autolinking uses the framework name for linking purposes
467   /// when this is false and the export_as name otherwise.
468   bool UseExportAsModuleLinkName = false;
469 
470   /// The set of "configuration macros", which are macros that
471   /// (intentionally) change how this module is built.
472   std::vector<std::string> ConfigMacros;
473 
474   /// An unresolved conflict with another module.
475   struct UnresolvedConflict {
476     /// The (unresolved) module id.
477     ModuleId Id;
478 
479     /// The message provided to the user when there is a conflict.
480     std::string Message;
481   };
482 
483   /// The list of conflicts for which the module-id has not yet been
484   /// resolved.
485   std::vector<UnresolvedConflict> UnresolvedConflicts;
486 
487   /// A conflict between two modules.
488   struct Conflict {
489     /// The module that this module conflicts with.
490     Module *Other;
491 
492     /// The message provided to the user when there is a conflict.
493     std::string Message;
494   };
495 
496   /// The list of conflicts.
497   std::vector<Conflict> Conflicts;
498 
499   /// Construct a new module or submodule.
500   Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
501          bool IsFramework, bool IsExplicit, unsigned VisibilityID);
502 
503   ~Module();
504 
505   /// Determine whether this module has been declared unimportable.
isUnimportable()506   bool isUnimportable() const { return IsUnimportable; }
507 
508   /// Determine whether this module has been declared unimportable.
509   ///
510   /// \param LangOpts The language options used for the current
511   /// translation unit.
512   ///
513   /// \param Target The target options used for the current translation unit.
514   ///
515   /// \param Req If this module is unimportable because of a missing
516   /// requirement, this parameter will be set to one of the requirements that
517   /// is not met for use of this module.
518   ///
519   /// \param ShadowingModule If this module is unimportable because it is
520   /// shadowed, this parameter will be set to the shadowing module.
521   bool isUnimportable(const LangOptions &LangOpts, const TargetInfo &Target,
522                       Requirement &Req, Module *&ShadowingModule) const;
523 
524   /// Determine whether this module can be built in this compilation.
525   bool isForBuilding(const LangOptions &LangOpts) const;
526 
527   /// Determine whether this module is available for use within the
528   /// current translation unit.
isAvailable()529   bool isAvailable() const { return IsAvailable; }
530 
531   /// Determine whether this module is available for use within the
532   /// current translation unit.
533   ///
534   /// \param LangOpts The language options used for the current
535   /// translation unit.
536   ///
537   /// \param Target The target options used for the current translation unit.
538   ///
539   /// \param Req If this module is unavailable because of a missing requirement,
540   /// this parameter will be set to one of the requirements that is not met for
541   /// use of this module.
542   ///
543   /// \param MissingHeader If this module is unavailable because of a missing
544   /// header, this parameter will be set to one of the missing headers.
545   ///
546   /// \param ShadowingModule If this module is unavailable because it is
547   /// shadowed, this parameter will be set to the shadowing module.
548   bool isAvailable(const LangOptions &LangOpts,
549                    const TargetInfo &Target,
550                    Requirement &Req,
551                    UnresolvedHeaderDirective &MissingHeader,
552                    Module *&ShadowingModule) const;
553 
554   /// Determine whether this module is a submodule.
isSubModule()555   bool isSubModule() const { return Parent != nullptr; }
556 
557   /// Check if this module is a (possibly transitive) submodule of \p Other.
558   ///
559   /// The 'A is a submodule of B' relation is a partial order based on the
560   /// the parent-child relationship between individual modules.
561   ///
562   /// Returns \c false if \p Other is \c nullptr.
563   bool isSubModuleOf(const Module *Other) const;
564 
565   /// Determine whether this module is a part of a framework,
566   /// either because it is a framework module or because it is a submodule
567   /// of a framework module.
isPartOfFramework()568   bool isPartOfFramework() const {
569     for (const Module *Mod = this; Mod; Mod = Mod->Parent)
570       if (Mod->IsFramework)
571         return true;
572 
573     return false;
574   }
575 
576   /// Determine whether this module is a subframework of another
577   /// framework.
isSubFramework()578   bool isSubFramework() const {
579     return IsFramework && Parent && Parent->isPartOfFramework();
580   }
581 
582   /// Set the parent of this module. This should only be used if the parent
583   /// could not be set during module creation.
setParent(Module * M)584   void setParent(Module *M) {
585     assert(!Parent);
586     Parent = M;
587     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
588     Parent->SubModules.push_back(this);
589   }
590 
591   /// Is this module have similar semantics as headers.
isHeaderLikeModule()592   bool isHeaderLikeModule() const {
593     return isModuleMapModule() || isHeaderUnit();
594   }
595 
596   /// Is this a module partition.
isModulePartition()597   bool isModulePartition() const {
598     return Kind == ModulePartitionInterface ||
599            Kind == ModulePartitionImplementation;
600   }
601 
602   /// Is this a module partition implementation unit.
isModulePartitionImplementation()603   bool isModulePartitionImplementation() const {
604     return Kind == ModulePartitionImplementation;
605   }
606 
607   /// Is this a module implementation.
isModuleImplementation()608   bool isModuleImplementation() const {
609     return Kind == ModuleImplementationUnit;
610   }
611 
612   /// Is this module a header unit.
isHeaderUnit()613   bool isHeaderUnit() const { return Kind == ModuleHeaderUnit; }
614   // Is this a C++20 module interface or a partition.
isInterfaceOrPartition()615   bool isInterfaceOrPartition() const {
616     return Kind == ModuleInterfaceUnit || isModulePartition();
617   }
618 
619   /// Is this a C++20 named module unit.
isNamedModuleUnit()620   bool isNamedModuleUnit() const {
621     return isInterfaceOrPartition() || isModuleImplementation();
622   }
623 
isModuleInterfaceUnit()624   bool isModuleInterfaceUnit() const {
625     return Kind == ModuleInterfaceUnit || Kind == ModulePartitionInterface;
626   }
627 
isNamedModuleInterfaceHasInit()628   bool isNamedModuleInterfaceHasInit() const { return NamedModuleHasInit; }
629 
630   /// Get the primary module interface name from a partition.
getPrimaryModuleInterfaceName()631   StringRef getPrimaryModuleInterfaceName() const {
632     // Technically, global module fragment belongs to global module. And global
633     // module has no name: [module.unit]p6:
634     //   The global module has no name, no module interface unit, and is not
635     //   introduced by any module-declaration.
636     //
637     // <global> is the default name showed in module map.
638     if (isGlobalModule())
639       return "<global>";
640 
641     if (isModulePartition()) {
642       auto pos = Name.find(':');
643       return StringRef(Name.data(), pos);
644     }
645 
646     if (isPrivateModule())
647       return getTopLevelModuleName();
648 
649     return Name;
650   }
651 
652   /// Retrieve the full name of this module, including the path from
653   /// its top-level module.
654   /// \param AllowStringLiterals If \c true, components that might not be
655   ///        lexically valid as identifiers will be emitted as string literals.
656   std::string getFullModuleName(bool AllowStringLiterals = false) const;
657 
658   /// Whether the full name of this module is equal to joining
659   /// \p nameParts with "."s.
660   ///
661   /// This is more efficient than getFullModuleName().
662   bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
663 
664   /// Retrieve the top-level module for this (sub)module, which may
665   /// be this module.
getTopLevelModule()666   Module *getTopLevelModule() {
667     return const_cast<Module *>(
668              const_cast<const Module *>(this)->getTopLevelModule());
669   }
670 
671   /// Retrieve the top-level module for this (sub)module, which may
672   /// be this module.
673   const Module *getTopLevelModule() const;
674 
675   /// Retrieve the name of the top-level module.
getTopLevelModuleName()676   StringRef getTopLevelModuleName() const {
677     return getTopLevelModule()->Name;
678   }
679 
680   /// The serialized AST file for this module, if one was created.
getASTFile()681   OptionalFileEntryRef getASTFile() const {
682     return getTopLevelModule()->ASTFile;
683   }
684 
685   /// Set the serialized AST file for the top-level module of this module.
setASTFile(OptionalFileEntryRef File)686   void setASTFile(OptionalFileEntryRef File) {
687     assert((!getASTFile() || getASTFile() == File) && "file path changed");
688     getTopLevelModule()->ASTFile = File;
689   }
690 
691   /// Retrieve the umbrella directory as written.
getUmbrellaDirAsWritten()692   std::optional<DirectoryName> getUmbrellaDirAsWritten() const {
693     if (const auto *Dir = std::get_if<DirectoryEntryRef>(&Umbrella))
694       return DirectoryName{UmbrellaAsWritten,
695                            UmbrellaRelativeToRootModuleDirectory, *Dir};
696     return std::nullopt;
697   }
698 
699   /// Retrieve the umbrella header as written.
getUmbrellaHeaderAsWritten()700   std::optional<Header> getUmbrellaHeaderAsWritten() const {
701     if (const auto *Hdr = std::get_if<FileEntryRef>(&Umbrella))
702       return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
703                     *Hdr};
704     return std::nullopt;
705   }
706 
707   /// Get the effective umbrella directory for this module: either the one
708   /// explicitly written in the module map file, or the parent of the umbrella
709   /// header.
710   OptionalDirectoryEntryRef getEffectiveUmbrellaDir() const;
711 
712   /// Add a top-level header associated with this module.
713   void addTopHeader(FileEntryRef File);
714 
715   /// Add a top-level header filename associated with this module.
addTopHeaderFilename(StringRef Filename)716   void addTopHeaderFilename(StringRef Filename) {
717     TopHeaderNames.push_back(std::string(Filename));
718   }
719 
720   /// The top-level headers associated with this module.
721   ArrayRef<FileEntryRef> getTopHeaders(FileManager &FileMgr);
722 
723   /// Determine whether this module has declared its intention to
724   /// directly use another module.
725   bool directlyUses(const Module *Requested);
726 
727   /// Add the given feature requirement to the list of features
728   /// required by this module.
729   ///
730   /// \param Feature The feature that is required by this module (and
731   /// its submodules).
732   ///
733   /// \param RequiredState The required state of this feature: \c true
734   /// if it must be present, \c false if it must be absent.
735   ///
736   /// \param LangOpts The set of language options that will be used to
737   /// evaluate the availability of this feature.
738   ///
739   /// \param Target The target options that will be used to evaluate the
740   /// availability of this feature.
741   void addRequirement(StringRef Feature, bool RequiredState,
742                       const LangOptions &LangOpts,
743                       const TargetInfo &Target);
744 
745   /// Mark this module and all of its submodules as unavailable.
746   void markUnavailable(bool Unimportable);
747 
748   /// Find the submodule with the given name.
749   ///
750   /// \returns The submodule if found, or NULL otherwise.
751   Module *findSubmodule(StringRef Name) const;
752   Module *findOrInferSubmodule(StringRef Name);
753 
754   /// Get the Global Module Fragment (sub-module) for this module, it there is
755   /// one.
756   ///
757   /// \returns The GMF sub-module if found, or NULL otherwise.
758   Module *getGlobalModuleFragment() const;
759 
760   /// Get the Private Module Fragment (sub-module) for this module, it there is
761   /// one.
762   ///
763   /// \returns The PMF sub-module if found, or NULL otherwise.
764   Module *getPrivateModuleFragment() const;
765 
766   /// Determine whether the specified module would be visible to
767   /// a lookup at the end of this module.
768   ///
769   /// FIXME: This may return incorrect results for (submodules of) the
770   /// module currently being built, if it's queried before we see all
771   /// of its imports.
isModuleVisible(const Module * M)772   bool isModuleVisible(const Module *M) const {
773     if (VisibleModulesCache.empty())
774       buildVisibleModulesCache();
775     return VisibleModulesCache.count(M);
776   }
777 
getVisibilityID()778   unsigned getVisibilityID() const { return VisibilityID; }
779 
780   using submodule_iterator = std::vector<Module *>::iterator;
781   using submodule_const_iterator = std::vector<Module *>::const_iterator;
782 
submodules()783   llvm::iterator_range<submodule_iterator> submodules() {
784     return llvm::make_range(SubModules.begin(), SubModules.end());
785   }
submodules()786   llvm::iterator_range<submodule_const_iterator> submodules() const {
787     return llvm::make_range(SubModules.begin(), SubModules.end());
788   }
789 
790   /// Appends this module's list of exported modules to \p Exported.
791   ///
792   /// This provides a subset of immediately imported modules (the ones that are
793   /// directly exported), not the complete set of exported modules.
794   void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
795 
getModuleInputBufferName()796   static StringRef getModuleInputBufferName() {
797     return "<module-includes>";
798   }
799 
800   /// Print the module map for this module to the given stream.
801   void print(raw_ostream &OS, unsigned Indent = 0, bool Dump = false) const;
802 
803   /// Dump the contents of this module to the given output stream.
804   void dump() const;
805 
806 private:
807   void buildVisibleModulesCache() const;
808 };
809 
810 /// A set of visible modules.
811 class VisibleModuleSet {
812 public:
813   VisibleModuleSet() = default;
VisibleModuleSet(VisibleModuleSet && O)814   VisibleModuleSet(VisibleModuleSet &&O)
815       : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
816     O.ImportLocs.clear();
817     ++O.Generation;
818   }
819 
820   /// Move from another visible modules set. Guaranteed to leave the source
821   /// empty and bump the generation on both.
822   VisibleModuleSet &operator=(VisibleModuleSet &&O) {
823     ImportLocs = std::move(O.ImportLocs);
824     O.ImportLocs.clear();
825     ++O.Generation;
826     ++Generation;
827     return *this;
828   }
829 
830   /// Get the current visibility generation. Incremented each time the
831   /// set of visible modules changes in any way.
getGeneration()832   unsigned getGeneration() const { return Generation; }
833 
834   /// Determine whether a module is visible.
isVisible(const Module * M)835   bool isVisible(const Module *M) const {
836     return getImportLoc(M).isValid();
837   }
838 
839   /// Get the location at which the import of a module was triggered.
getImportLoc(const Module * M)840   SourceLocation getImportLoc(const Module *M) const {
841     return M->getVisibilityID() < ImportLocs.size()
842                ? ImportLocs[M->getVisibilityID()]
843                : SourceLocation();
844   }
845 
846   /// A callback to call when a module is made visible (directly or
847   /// indirectly) by a call to \ref setVisible.
848   using VisibleCallback = llvm::function_ref<void(Module *M)>;
849 
850   /// A callback to call when a module conflict is found. \p Path
851   /// consists of a sequence of modules from the conflicting module to the one
852   /// made visible, where each was exported by the next.
853   using ConflictCallback =
854       llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
855                          StringRef Message)>;
856 
857   /// Make a specific module visible.
858   void setVisible(Module *M, SourceLocation Loc,
859                   VisibleCallback Vis = [](Module *) {},
860                   ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
861                                            StringRef) {});
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 } // namespace clang
872 
873 #endif // LLVM_CLANG_BASIC_MODULE_H
874