1 //===- Module.h - Describe a module -----------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// Defines the clang::Module class, which describes a module in the
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_BASIC_MODULE_H
16 #define LLVM_CLANG_BASIC_MODULE_H
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/PointerUnion.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/iterator_range.h"
50 /// Describes the name of a module.
51 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
53 /// The signature of a module, which is a hash of the AST content.
54 struct ASTFileSignature : std::array<uint32_t, 5> {
55 ASTFileSignature(std::array<uint32_t, 5> S = {{0}})
56 : std::array<uint32_t, 5>(std::move(S)) {}
58 explicit operator bool() const {
59 return *this != std::array<uint32_t, 5>({{0}});
63 /// Describes a module or submodule.
66 /// The name of this module.
69 /// The location of the module definition.
70 SourceLocation DefinitionLoc;
73 /// This is a module that was defined by a module map and built out
77 /// This is a C++ Modules TS module interface unit.
80 /// This is a fragment of the global module within some C++ module.
83 /// This is the private module fragment within some C++ module.
84 PrivateModuleFragment,
87 /// The kind of this module.
88 ModuleKind Kind = ModuleMapModule;
90 /// The parent of this module. This will be NULL for the top-level
94 /// The build directory of this module. This is the directory in
95 /// which the module is notionally built, and relative to which its headers
97 const DirectoryEntry *Directory = nullptr;
99 /// The presumed file name for the module map defining this module.
100 /// Only non-empty when building from preprocessed source.
101 std::string PresumedModuleMapFile;
103 /// The umbrella header or directory.
104 llvm::PointerUnion<const DirectoryEntry *, const FileEntry *> Umbrella;
106 /// The module signature.
107 ASTFileSignature Signature;
109 /// The name of the umbrella entry, as written in the module map.
110 std::string UmbrellaAsWritten;
112 /// The module through which entities defined in this module will
113 /// eventually be exposed, for use in "private" modules.
114 std::string ExportAsModule;
116 /// Does this Module scope describe part of the purview of a named C++ module?
117 bool isModulePurview() const {
118 return Kind == ModuleInterfaceUnit || Kind == PrivateModuleFragment;
122 /// The submodules of this module, indexed by name.
123 std::vector<Module *> SubModules;
125 /// A mapping from the submodule name to the index into the
126 /// \c SubModules vector at which that submodule resides.
127 llvm::StringMap<unsigned> SubModuleIndex;
129 /// The AST file if this is a top-level module which has a
130 /// corresponding serialized AST file, or null otherwise.
131 const FileEntry *ASTFile = nullptr;
133 /// The top-level headers associated with this module.
134 llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
136 /// top-level header filenames that aren't resolved to FileEntries yet.
137 std::vector<std::string> TopHeaderNames;
139 /// Cache of modules visible to lookup in this module.
140 mutable llvm::DenseSet<const Module*> VisibleModulesCache;
142 /// The ID used when referencing this module within a VisibleModuleSet.
143 unsigned VisibilityID;
153 static const int NumHeaderKinds = HK_Excluded + 1;
155 /// Information about a header directive as found in the module map
158 std::string NameAsWritten;
159 const FileEntry *Entry;
161 explicit operator bool() { return Entry; }
164 /// Information about a directory name as found in the module map
166 struct DirectoryName {
167 std::string NameAsWritten;
168 const DirectoryEntry *Entry;
170 explicit operator bool() { return Entry; }
173 /// The headers that are part of this module.
174 SmallVector<Header, 2> Headers[5];
176 /// Stored information about a header directive that was found in the
177 /// module map file but has not been resolved to a file.
178 struct UnresolvedHeaderDirective {
179 HeaderKind Kind = HK_Normal;
180 SourceLocation FileNameLoc;
181 std::string FileName;
182 bool IsUmbrella = false;
183 bool HasBuiltinHeader = false;
184 Optional<off_t> Size;
185 Optional<time_t> ModTime;
188 /// Headers that are mentioned in the module map file but that we have not
189 /// yet attempted to resolve to a file on the file system.
190 SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
192 /// Headers that are mentioned in the module map file but could not be
193 /// found on the file system.
194 SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
196 /// An individual requirement: a feature name and a flag indicating
197 /// the required state of that feature.
198 using Requirement = std::pair<std::string, bool>;
200 /// The set of language features required to use this module.
202 /// If any of these requirements are not available, the \c IsAvailable bit
203 /// will be false to indicate that this (sub)module is not available.
204 SmallVector<Requirement, 2> Requirements;
206 /// A module with the same name that shadows this module.
207 Module *ShadowingModule = nullptr;
209 /// Whether this module is missing a feature from \c Requirements.
210 unsigned IsMissingRequirement : 1;
212 /// Whether we tried and failed to load a module file for this module.
213 unsigned HasIncompatibleModuleFile : 1;
215 /// Whether this module is available in the current translation unit.
217 /// If the module is missing headers or does not meet all requirements then
218 /// this bit will be 0.
219 unsigned IsAvailable : 1;
221 /// Whether this module was loaded from a module file.
222 unsigned IsFromModuleFile : 1;
224 /// Whether this is a framework module.
225 unsigned IsFramework : 1;
227 /// Whether this is an explicit submodule.
228 unsigned IsExplicit : 1;
230 /// Whether this is a "system" module (which assumes that all
231 /// headers in it are system headers).
232 unsigned IsSystem : 1;
234 /// Whether this is an 'extern "C"' module (which implicitly puts all
235 /// headers in it within an 'extern "C"' block, and allows the module to be
236 /// imported within such a block).
237 unsigned IsExternC : 1;
239 /// Whether this is an inferred submodule (module * { ... }).
240 unsigned IsInferred : 1;
242 /// Whether we should infer submodules for this module based on
245 /// Submodules can only be inferred for modules with an umbrella header.
246 unsigned InferSubmodules : 1;
248 /// Whether, when inferring submodules, the inferred submodules
249 /// should be explicit.
250 unsigned InferExplicitSubmodules : 1;
252 /// Whether, when inferring submodules, the inferr submodules should
253 /// export all modules they import (e.g., the equivalent of "export *").
254 unsigned InferExportWildcard : 1;
256 /// Whether the set of configuration macros is exhaustive.
258 /// When the set of configuration macros is exhaustive, meaning
259 /// that no identifier not in this list should affect how the module is
261 unsigned ConfigMacrosExhaustive : 1;
263 /// Whether files in this module can only include non-modular headers
264 /// and headers from used modules.
265 unsigned NoUndeclaredIncludes : 1;
267 /// Whether this module came from a "private" module map, found next
268 /// to a regular (public) module map.
269 unsigned ModuleMapIsPrivate : 1;
271 /// Describes the visibility of the various names within a
272 /// particular module.
273 enum NameVisibilityKind {
274 /// All of the names in this module are hidden.
276 /// All of the names in this module are visible.
280 /// The visibility of names within this particular module.
281 NameVisibilityKind NameVisibility;
283 /// The location of the inferred submodule.
284 SourceLocation InferredSubmoduleLoc;
286 /// The set of modules imported by this module, and on which this
288 llvm::SmallSetVector<Module *, 2> Imports;
290 /// Describes an exported module.
292 /// The pointer is the module being re-exported, while the bit will be true
293 /// to indicate that this is a wildcard export.
294 using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
296 /// The set of export declarations.
297 SmallVector<ExportDecl, 2> Exports;
299 /// Describes an exported module that has not yet been resolved
300 /// (perhaps because the module it refers to has not yet been loaded).
301 struct UnresolvedExportDecl {
302 /// The location of the 'export' keyword in the module map file.
303 SourceLocation ExportLoc;
305 /// The name of the module.
308 /// Whether this export declaration ends in a wildcard, indicating
309 /// that all of its submodules should be exported (rather than the named
314 /// The set of export declarations that have yet to be resolved.
315 SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
317 /// The directly used modules.
318 SmallVector<Module *, 2> DirectUses;
320 /// The set of use declarations that have yet to be resolved.
321 SmallVector<ModuleId, 2> UnresolvedDirectUses;
323 /// A library or framework to link against when an entity from this
326 LinkLibrary() = default;
327 LinkLibrary(const std::string &Library, bool IsFramework)
328 : Library(Library), IsFramework(IsFramework) {}
330 /// The library to link against.
332 /// This will typically be a library or framework name, but can also
333 /// be an absolute path to the library or framework.
336 /// Whether this is a framework rather than a library.
337 bool IsFramework = false;
340 /// The set of libraries or frameworks to link against when
341 /// an entity from this module is used.
342 llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
344 /// Autolinking uses the framework name for linking purposes
345 /// when this is false and the export_as name otherwise.
346 bool UseExportAsModuleLinkName = false;
348 /// The set of "configuration macros", which are macros that
349 /// (intentionally) change how this module is built.
350 std::vector<std::string> ConfigMacros;
352 /// An unresolved conflict with another module.
353 struct UnresolvedConflict {
354 /// The (unresolved) module id.
357 /// The message provided to the user when there is a conflict.
361 /// The list of conflicts for which the module-id has not yet been
363 std::vector<UnresolvedConflict> UnresolvedConflicts;
365 /// A conflict between two modules.
367 /// The module that this module conflicts with.
370 /// The message provided to the user when there is a conflict.
374 /// The list of conflicts.
375 std::vector<Conflict> Conflicts;
377 /// Construct a new module or submodule.
378 Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
379 bool IsFramework, bool IsExplicit, unsigned VisibilityID);
383 /// Determine whether this module is available for use within the
384 /// current translation unit.
385 bool isAvailable() const { return IsAvailable; }
387 /// Determine whether this module is available for use within the
388 /// current translation unit.
390 /// \param LangOpts The language options used for the current
391 /// translation unit.
393 /// \param Target The target options used for the current translation unit.
395 /// \param Req If this module is unavailable because of a missing requirement,
396 /// this parameter will be set to one of the requirements that is not met for
397 /// use of this module.
399 /// \param MissingHeader If this module is unavailable because of a missing
400 /// header, this parameter will be set to one of the missing headers.
402 /// \param ShadowingModule If this module is unavailable because it is
403 /// shadowed, this parameter will be set to the shadowing module.
404 bool isAvailable(const LangOptions &LangOpts,
405 const TargetInfo &Target,
407 UnresolvedHeaderDirective &MissingHeader,
408 Module *&ShadowingModule) const;
410 /// Determine whether this module is a submodule.
411 bool isSubModule() const { return Parent != nullptr; }
413 /// Determine whether this module is a submodule of the given other
415 bool isSubModuleOf(const Module *Other) const;
417 /// Determine whether this module is a part of a framework,
418 /// either because it is a framework module or because it is a submodule
419 /// of a framework module.
420 bool isPartOfFramework() const {
421 for (const Module *Mod = this; Mod; Mod = Mod->Parent)
422 if (Mod->IsFramework)
428 /// Determine whether this module is a subframework of another
430 bool isSubFramework() const {
431 return IsFramework && Parent && Parent->isPartOfFramework();
434 /// Set the parent of this module. This should only be used if the parent
435 /// could not be set during module creation.
436 void setParent(Module *M) {
439 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
440 Parent->SubModules.push_back(this);
443 /// Retrieve the full name of this module, including the path from
444 /// its top-level module.
445 /// \param AllowStringLiterals If \c true, components that might not be
446 /// lexically valid as identifiers will be emitted as string literals.
447 std::string getFullModuleName(bool AllowStringLiterals = false) const;
449 /// Whether the full name of this module is equal to joining
450 /// \p nameParts with "."s.
452 /// This is more efficient than getFullModuleName().
453 bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
455 /// Retrieve the top-level module for this (sub)module, which may
457 Module *getTopLevelModule() {
458 return const_cast<Module *>(
459 const_cast<const Module *>(this)->getTopLevelModule());
462 /// Retrieve the top-level module for this (sub)module, which may
464 const Module *getTopLevelModule() const;
466 /// Retrieve the name of the top-level module.
467 StringRef getTopLevelModuleName() const {
468 return getTopLevelModule()->Name;
471 /// The serialized AST file for this module, if one was created.
472 const FileEntry *getASTFile() const {
473 return getTopLevelModule()->ASTFile;
476 /// Set the serialized AST file for the top-level module of this module.
477 void setASTFile(const FileEntry *File) {
478 assert((File == nullptr || getASTFile() == nullptr ||
479 getASTFile() == File) && "file path changed");
480 getTopLevelModule()->ASTFile = File;
483 /// Retrieve the directory for which this module serves as the
485 DirectoryName getUmbrellaDir() const;
487 /// Retrieve the header that serves as the umbrella header for this
489 Header getUmbrellaHeader() const {
490 if (auto *E = Umbrella.dyn_cast<const FileEntry *>())
491 return Header{UmbrellaAsWritten, E};
495 /// Determine whether this module has an umbrella directory that is
496 /// not based on an umbrella header.
497 bool hasUmbrellaDir() const {
498 return Umbrella && Umbrella.is<const DirectoryEntry *>();
501 /// Add a top-level header associated with this module.
502 void addTopHeader(const FileEntry *File) {
504 TopHeaders.insert(File);
507 /// Add a top-level header filename associated with this module.
508 void addTopHeaderFilename(StringRef Filename) {
509 TopHeaderNames.push_back(Filename);
512 /// The top-level headers associated with this module.
513 ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
515 /// Determine whether this module has declared its intention to
516 /// directly use another module.
517 bool directlyUses(const Module *Requested) const;
519 /// Add the given feature requirement to the list of features
520 /// required by this module.
522 /// \param Feature The feature that is required by this module (and
525 /// \param RequiredState The required state of this feature: \c true
526 /// if it must be present, \c false if it must be absent.
528 /// \param LangOpts The set of language options that will be used to
529 /// evaluate the availability of this feature.
531 /// \param Target The target options that will be used to evaluate the
532 /// availability of this feature.
533 void addRequirement(StringRef Feature, bool RequiredState,
534 const LangOptions &LangOpts,
535 const TargetInfo &Target);
537 /// Mark this module and all of its submodules as unavailable.
538 void markUnavailable(bool MissingRequirement = false);
540 /// Find the submodule with the given name.
542 /// \returns The submodule if found, or NULL otherwise.
543 Module *findSubmodule(StringRef Name) const;
544 Module *findOrInferSubmodule(StringRef Name);
546 /// Determine whether the specified module would be visible to
547 /// a lookup at the end of this module.
549 /// FIXME: This may return incorrect results for (submodules of) the
550 /// module currently being built, if it's queried before we see all
552 bool isModuleVisible(const Module *M) const {
553 if (VisibleModulesCache.empty())
554 buildVisibleModulesCache();
555 return VisibleModulesCache.count(M);
558 unsigned getVisibilityID() const { return VisibilityID; }
560 using submodule_iterator = std::vector<Module *>::iterator;
561 using submodule_const_iterator = std::vector<Module *>::const_iterator;
563 submodule_iterator submodule_begin() { return SubModules.begin(); }
564 submodule_const_iterator submodule_begin() const {return SubModules.begin();}
565 submodule_iterator submodule_end() { return SubModules.end(); }
566 submodule_const_iterator submodule_end() const { return SubModules.end(); }
568 llvm::iterator_range<submodule_iterator> submodules() {
569 return llvm::make_range(submodule_begin(), submodule_end());
571 llvm::iterator_range<submodule_const_iterator> submodules() const {
572 return llvm::make_range(submodule_begin(), submodule_end());
575 /// Appends this module's list of exported modules to \p Exported.
577 /// This provides a subset of immediately imported modules (the ones that are
578 /// directly exported), not the complete set of exported modules.
579 void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
581 static StringRef getModuleInputBufferName() {
582 return "<module-includes>";
585 /// Print the module map for this module to the given stream.
586 void print(raw_ostream &OS, unsigned Indent = 0) const;
588 /// Dump the contents of this module to the given output stream.
592 void buildVisibleModulesCache() const;
595 /// A set of visible modules.
596 class VisibleModuleSet {
598 VisibleModuleSet() = default;
599 VisibleModuleSet(VisibleModuleSet &&O)
600 : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
601 O.ImportLocs.clear();
605 /// Move from another visible modules set. Guaranteed to leave the source
606 /// empty and bump the generation on both.
607 VisibleModuleSet &operator=(VisibleModuleSet &&O) {
608 ImportLocs = std::move(O.ImportLocs);
609 O.ImportLocs.clear();
615 /// Get the current visibility generation. Incremented each time the
616 /// set of visible modules changes in any way.
617 unsigned getGeneration() const { return Generation; }
619 /// Determine whether a module is visible.
620 bool isVisible(const Module *M) const {
621 return getImportLoc(M).isValid();
624 /// Get the location at which the import of a module was triggered.
625 SourceLocation getImportLoc(const Module *M) const {
626 return M->getVisibilityID() < ImportLocs.size()
627 ? ImportLocs[M->getVisibilityID()]
631 /// A callback to call when a module is made visible (directly or
632 /// indirectly) by a call to \ref setVisible.
633 using VisibleCallback = llvm::function_ref<void(Module *M)>;
635 /// A callback to call when a module conflict is found. \p Path
636 /// consists of a sequence of modules from the conflicting module to the one
637 /// made visible, where each was exported by the next.
638 using ConflictCallback =
639 llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
642 /// Make a specific module visible.
643 void setVisible(Module *M, SourceLocation Loc,
644 VisibleCallback Vis = [](Module *) {},
645 ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
649 /// Import locations for each visible module. Indexed by the module's
651 std::vector<SourceLocation> ImportLocs;
653 /// Visibility generation, bumped every time the visibility state changes.
654 unsigned Generation = 0;
659 #endif // LLVM_CLANG_BASIC_MODULE_H