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