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/SourceLocation.h" 19 #include "llvm/ADT/ArrayRef.h" 20 #include "llvm/ADT/DenseSet.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/PointerIntPair.h" 23 #include "llvm/ADT/SetVector.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/StringMap.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/iterator_range.h" 29 #include <array> 30 #include <cassert> 31 #include <cstdint> 32 #include <ctime> 33 #include <string> 34 #include <utility> 35 #include <vector> 36 37 namespace llvm { 38 39 class raw_ostream; 40 41 } // namespace llvm 42 43 namespace clang { 44 45 class DirectoryEntry; 46 class FileEntry; 47 class FileManager; 48 class LangOptions; 49 class TargetInfo; 50 51 /// Describes the name of a module. 52 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>; 53 54 /// The signature of a module, which is a hash of the AST content. 55 struct ASTFileSignature : std::array<uint32_t, 5> { 56 ASTFileSignature(std::array<uint32_t, 5> S = {{0}}) 57 : std::array<uint32_t, 5>(std::move(S)) {} 58 59 explicit operator bool() const { 60 return *this != std::array<uint32_t, 5>({{0}}); 61 } 62 }; 63 64 /// Describes a module or submodule. 65 class Module { 66 public: 67 /// The name of this module. 68 std::string Name; 69 70 /// The location of the module definition. 71 SourceLocation DefinitionLoc; 72 73 enum ModuleKind { 74 /// This is a module that was defined by a module map and built out 75 /// of header files. 76 ModuleMapModule, 77 78 /// This is a C++ Modules TS module interface unit. 79 ModuleInterfaceUnit, 80 81 /// This is a fragment of the global module within some C++ module. 82 GlobalModuleFragment, 83 84 /// This is the private module fragment within some C++ module. 85 PrivateModuleFragment, 86 }; 87 88 /// The kind of this module. 89 ModuleKind Kind = ModuleMapModule; 90 91 /// The parent of this module. This will be NULL for the top-level 92 /// module. 93 Module *Parent; 94 95 /// The build directory of this module. This is the directory in 96 /// which the module is notionally built, and relative to which its headers 97 /// are found. 98 const DirectoryEntry *Directory = nullptr; 99 100 /// The presumed file name for the module map defining this module. 101 /// Only non-empty when building from preprocessed source. 102 std::string PresumedModuleMapFile; 103 104 /// The umbrella header or directory. 105 const void *Umbrella = nullptr; 106 107 /// The module signature. 108 ASTFileSignature Signature; 109 110 /// The name of the umbrella entry, as written in the module map. 111 std::string UmbrellaAsWritten; 112 113 /// The module through which entities defined in this module will 114 /// eventually be exposed, for use in "private" modules. 115 std::string ExportAsModule; 116 117 /// Does this Module scope describe part of the purview of a named C++ module? 118 bool isModulePurview() const { 119 return Kind == ModuleInterfaceUnit || Kind == PrivateModuleFragment; 120 } 121 122 private: 123 /// The submodules of this module, indexed by name. 124 std::vector<Module *> SubModules; 125 126 /// A mapping from the submodule name to the index into the 127 /// \c SubModules vector at which that submodule resides. 128 llvm::StringMap<unsigned> SubModuleIndex; 129 130 /// The AST file if this is a top-level module which has a 131 /// corresponding serialized AST file, or null otherwise. 132 const FileEntry *ASTFile = nullptr; 133 134 /// The top-level headers associated with this module. 135 llvm::SmallSetVector<const FileEntry *, 2> TopHeaders; 136 137 /// top-level header filenames that aren't resolved to FileEntries yet. 138 std::vector<std::string> TopHeaderNames; 139 140 /// Cache of modules visible to lookup in this module. 141 mutable llvm::DenseSet<const Module*> VisibleModulesCache; 142 143 /// The ID used when referencing this module within a VisibleModuleSet. 144 unsigned VisibilityID; 145 146 public: 147 enum HeaderKind { 148 HK_Normal, 149 HK_Textual, 150 HK_Private, 151 HK_PrivateTextual, 152 HK_Excluded 153 }; 154 static const int NumHeaderKinds = HK_Excluded + 1; 155 156 /// Information about a header directive as found in the module map 157 /// file. 158 struct Header { 159 std::string NameAsWritten; 160 const FileEntry *Entry; 161 162 explicit operator bool() { return Entry; } 163 }; 164 165 /// Information about a directory name as found in the module map 166 /// file. 167 struct DirectoryName { 168 std::string NameAsWritten; 169 const DirectoryEntry *Entry; 170 171 explicit operator bool() { return Entry; } 172 }; 173 174 /// The headers that are part of this module. 175 SmallVector<Header, 2> Headers[5]; 176 177 /// Stored information about a header directive that was found in the 178 /// module map file but has not been resolved to a file. 179 struct UnresolvedHeaderDirective { 180 HeaderKind Kind = HK_Normal; 181 SourceLocation FileNameLoc; 182 std::string FileName; 183 bool IsUmbrella = false; 184 bool HasBuiltinHeader = false; 185 Optional<off_t> Size; 186 Optional<time_t> ModTime; 187 }; 188 189 /// Headers that are mentioned in the module map file but that we have not 190 /// yet attempted to resolve to a file on the file system. 191 SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders; 192 193 /// Headers that are mentioned in the module map file but could not be 194 /// found on the file system. 195 SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders; 196 197 /// An individual requirement: a feature name and a flag indicating 198 /// the required state of that feature. 199 using Requirement = std::pair<std::string, bool>; 200 201 /// The set of language features required to use this module. 202 /// 203 /// If any of these requirements are not available, the \c IsAvailable bit 204 /// will be false to indicate that this (sub)module is not available. 205 SmallVector<Requirement, 2> Requirements; 206 207 /// A module with the same name that shadows this module. 208 Module *ShadowingModule = nullptr; 209 210 /// Whether this module is missing a feature from \c Requirements. 211 unsigned IsMissingRequirement : 1; 212 213 /// Whether we tried and failed to load a module file for this module. 214 unsigned HasIncompatibleModuleFile : 1; 215 216 /// Whether this module is available in the current translation unit. 217 /// 218 /// If the module is missing headers or does not meet all requirements then 219 /// this bit will be 0. 220 unsigned IsAvailable : 1; 221 222 /// Whether this module was loaded from a module file. 223 unsigned IsFromModuleFile : 1; 224 225 /// Whether this is a framework module. 226 unsigned IsFramework : 1; 227 228 /// Whether this is an explicit submodule. 229 unsigned IsExplicit : 1; 230 231 /// Whether this is a "system" module (which assumes that all 232 /// headers in it are system headers). 233 unsigned IsSystem : 1; 234 235 /// Whether this is an 'extern "C"' module (which implicitly puts all 236 /// headers in it within an 'extern "C"' block, and allows the module to be 237 /// imported within such a block). 238 unsigned IsExternC : 1; 239 240 /// Whether this is an inferred submodule (module * { ... }). 241 unsigned IsInferred : 1; 242 243 /// Whether we should infer submodules for this module based on 244 /// the headers. 245 /// 246 /// Submodules can only be inferred for modules with an umbrella header. 247 unsigned InferSubmodules : 1; 248 249 /// Whether, when inferring submodules, the inferred submodules 250 /// should be explicit. 251 unsigned InferExplicitSubmodules : 1; 252 253 /// Whether, when inferring submodules, the inferr submodules should 254 /// export all modules they import (e.g., the equivalent of "export *"). 255 unsigned InferExportWildcard : 1; 256 257 /// Whether the set of configuration macros is exhaustive. 258 /// 259 /// When the set of configuration macros is exhaustive, meaning 260 /// that no identifier not in this list should affect how the module is 261 /// built. 262 unsigned ConfigMacrosExhaustive : 1; 263 264 /// Whether files in this module can only include non-modular headers 265 /// and headers from used modules. 266 unsigned NoUndeclaredIncludes : 1; 267 268 /// Whether this module came from a "private" module map, found next 269 /// to a regular (public) module map. 270 unsigned ModuleMapIsPrivate : 1; 271 272 /// Whether Umbrella is a directory or header. 273 unsigned HasUmbrellaDir : 1; 274 275 /// Describes the visibility of the various names within a 276 /// particular module. 277 enum NameVisibilityKind { 278 /// All of the names in this module are hidden. 279 Hidden, 280 /// All of the names in this module are visible. 281 AllVisible 282 }; 283 284 /// The visibility of names within this particular module. 285 NameVisibilityKind NameVisibility; 286 287 /// The location of the inferred submodule. 288 SourceLocation InferredSubmoduleLoc; 289 290 /// The set of modules imported by this module, and on which this 291 /// module depends. 292 llvm::SmallSetVector<Module *, 2> Imports; 293 294 /// Describes an exported module. 295 /// 296 /// The pointer is the module being re-exported, while the bit will be true 297 /// to indicate that this is a wildcard export. 298 using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>; 299 300 /// The set of export declarations. 301 SmallVector<ExportDecl, 2> Exports; 302 303 /// Describes an exported module that has not yet been resolved 304 /// (perhaps because the module it refers to has not yet been loaded). 305 struct UnresolvedExportDecl { 306 /// The location of the 'export' keyword in the module map file. 307 SourceLocation ExportLoc; 308 309 /// The name of the module. 310 ModuleId Id; 311 312 /// Whether this export declaration ends in a wildcard, indicating 313 /// that all of its submodules should be exported (rather than the named 314 /// module itself). 315 bool Wildcard; 316 }; 317 318 /// The set of export declarations that have yet to be resolved. 319 SmallVector<UnresolvedExportDecl, 2> UnresolvedExports; 320 321 /// The directly used modules. 322 SmallVector<Module *, 2> DirectUses; 323 324 /// The set of use declarations that have yet to be resolved. 325 SmallVector<ModuleId, 2> UnresolvedDirectUses; 326 327 /// A library or framework to link against when an entity from this 328 /// module is used. 329 struct LinkLibrary { 330 LinkLibrary() = default; 331 LinkLibrary(const std::string &Library, bool IsFramework) 332 : Library(Library), IsFramework(IsFramework) {} 333 334 /// The library to link against. 335 /// 336 /// This will typically be a library or framework name, but can also 337 /// be an absolute path to the library or framework. 338 std::string Library; 339 340 /// Whether this is a framework rather than a library. 341 bool IsFramework = false; 342 }; 343 344 /// The set of libraries or frameworks to link against when 345 /// an entity from this module is used. 346 llvm::SmallVector<LinkLibrary, 2> LinkLibraries; 347 348 /// Autolinking uses the framework name for linking purposes 349 /// when this is false and the export_as name otherwise. 350 bool UseExportAsModuleLinkName = false; 351 352 /// The set of "configuration macros", which are macros that 353 /// (intentionally) change how this module is built. 354 std::vector<std::string> ConfigMacros; 355 356 /// An unresolved conflict with another module. 357 struct UnresolvedConflict { 358 /// The (unresolved) module id. 359 ModuleId Id; 360 361 /// The message provided to the user when there is a conflict. 362 std::string Message; 363 }; 364 365 /// The list of conflicts for which the module-id has not yet been 366 /// resolved. 367 std::vector<UnresolvedConflict> UnresolvedConflicts; 368 369 /// A conflict between two modules. 370 struct Conflict { 371 /// The module that this module conflicts with. 372 Module *Other; 373 374 /// The message provided to the user when there is a conflict. 375 std::string Message; 376 }; 377 378 /// The list of conflicts. 379 std::vector<Conflict> Conflicts; 380 381 /// Construct a new module or submodule. 382 Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent, 383 bool IsFramework, bool IsExplicit, unsigned VisibilityID); 384 385 ~Module(); 386 387 /// Determine whether this module is available for use within the 388 /// current translation unit. 389 bool isAvailable() const { return IsAvailable; } 390 391 /// Determine whether this module is available for use within the 392 /// current translation unit. 393 /// 394 /// \param LangOpts The language options used for the current 395 /// translation unit. 396 /// 397 /// \param Target The target options used for the current translation unit. 398 /// 399 /// \param Req If this module is unavailable because of a missing requirement, 400 /// this parameter will be set to one of the requirements that is not met for 401 /// use of this module. 402 /// 403 /// \param MissingHeader If this module is unavailable because of a missing 404 /// header, this parameter will be set to one of the missing headers. 405 /// 406 /// \param ShadowingModule If this module is unavailable because it is 407 /// shadowed, this parameter will be set to the shadowing module. 408 bool isAvailable(const LangOptions &LangOpts, 409 const TargetInfo &Target, 410 Requirement &Req, 411 UnresolvedHeaderDirective &MissingHeader, 412 Module *&ShadowingModule) const; 413 414 /// Determine whether this module is a submodule. 415 bool isSubModule() const { return Parent != nullptr; } 416 417 /// Determine whether this module is a submodule of the given other 418 /// module. 419 bool isSubModuleOf(const Module *Other) const; 420 421 /// Determine whether this module is a part of a framework, 422 /// either because it is a framework module or because it is a submodule 423 /// of a framework module. 424 bool isPartOfFramework() const { 425 for (const Module *Mod = this; Mod; Mod = Mod->Parent) 426 if (Mod->IsFramework) 427 return true; 428 429 return false; 430 } 431 432 /// Determine whether this module is a subframework of another 433 /// framework. 434 bool isSubFramework() const { 435 return IsFramework && Parent && Parent->isPartOfFramework(); 436 } 437 438 /// Set the parent of this module. This should only be used if the parent 439 /// could not be set during module creation. 440 void setParent(Module *M) { 441 assert(!Parent); 442 Parent = M; 443 Parent->SubModuleIndex[Name] = Parent->SubModules.size(); 444 Parent->SubModules.push_back(this); 445 } 446 447 /// Retrieve the full name of this module, including the path from 448 /// its top-level module. 449 /// \param AllowStringLiterals If \c true, components that might not be 450 /// lexically valid as identifiers will be emitted as string literals. 451 std::string getFullModuleName(bool AllowStringLiterals = false) const; 452 453 /// Whether the full name of this module is equal to joining 454 /// \p nameParts with "."s. 455 /// 456 /// This is more efficient than getFullModuleName(). 457 bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const; 458 459 /// Retrieve the top-level module for this (sub)module, which may 460 /// be this module. 461 Module *getTopLevelModule() { 462 return const_cast<Module *>( 463 const_cast<const Module *>(this)->getTopLevelModule()); 464 } 465 466 /// Retrieve the top-level module for this (sub)module, which may 467 /// be this module. 468 const Module *getTopLevelModule() const; 469 470 /// Retrieve the name of the top-level module. 471 StringRef getTopLevelModuleName() const { 472 return getTopLevelModule()->Name; 473 } 474 475 /// The serialized AST file for this module, if one was created. 476 const FileEntry *getASTFile() const { 477 return getTopLevelModule()->ASTFile; 478 } 479 480 /// Set the serialized AST file for the top-level module of this module. 481 void setASTFile(const FileEntry *File) { 482 assert((File == nullptr || getASTFile() == nullptr || 483 getASTFile() == File) && "file path changed"); 484 getTopLevelModule()->ASTFile = File; 485 } 486 487 /// Retrieve the directory for which this module serves as the 488 /// umbrella. 489 DirectoryName getUmbrellaDir() const; 490 491 /// Retrieve the header that serves as the umbrella header for this 492 /// module. 493 Header getUmbrellaHeader() const { 494 if (!HasUmbrellaDir) 495 return Header{UmbrellaAsWritten, 496 static_cast<const FileEntry *>(Umbrella)}; 497 return Header{}; 498 } 499 500 /// Determine whether this module has an umbrella directory that is 501 /// not based on an umbrella header. 502 bool hasUmbrellaDir() const { return Umbrella && HasUmbrellaDir; } 503 504 /// Add a top-level header associated with this module. 505 void addTopHeader(const FileEntry *File); 506 507 /// Add a top-level header filename associated with this module. 508 void addTopHeaderFilename(StringRef Filename) { 509 TopHeaderNames.push_back(std::string(Filename)); 510 } 511 512 /// The top-level headers associated with this module. 513 ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr); 514 515 /// Determine whether this module has declared its intention to 516 /// directly use another module. 517 bool directlyUses(const Module *Requested) const; 518 519 /// Add the given feature requirement to the list of features 520 /// required by this module. 521 /// 522 /// \param Feature The feature that is required by this module (and 523 /// its submodules). 524 /// 525 /// \param RequiredState The required state of this feature: \c true 526 /// if it must be present, \c false if it must be absent. 527 /// 528 /// \param LangOpts The set of language options that will be used to 529 /// evaluate the availability of this feature. 530 /// 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); 536 537 /// Mark this module and all of its submodules as unavailable. 538 void markUnavailable(bool MissingRequirement = false); 539 540 /// Find the submodule with the given name. 541 /// 542 /// \returns The submodule if found, or NULL otherwise. 543 Module *findSubmodule(StringRef Name) const; 544 Module *findOrInferSubmodule(StringRef Name); 545 546 /// Determine whether the specified module would be visible to 547 /// a lookup at the end of this module. 548 /// 549 /// FIXME: This may return incorrect results for (submodules of) the 550 /// module currently being built, if it's queried before we see all 551 /// of its imports. 552 bool isModuleVisible(const Module *M) const { 553 if (VisibleModulesCache.empty()) 554 buildVisibleModulesCache(); 555 return VisibleModulesCache.count(M); 556 } 557 558 unsigned getVisibilityID() const { return VisibilityID; } 559 560 using submodule_iterator = std::vector<Module *>::iterator; 561 using submodule_const_iterator = std::vector<Module *>::const_iterator; 562 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(); } 567 568 llvm::iterator_range<submodule_iterator> submodules() { 569 return llvm::make_range(submodule_begin(), submodule_end()); 570 } 571 llvm::iterator_range<submodule_const_iterator> submodules() const { 572 return llvm::make_range(submodule_begin(), submodule_end()); 573 } 574 575 /// Appends this module's list of exported modules to \p Exported. 576 /// 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; 580 581 static StringRef getModuleInputBufferName() { 582 return "<module-includes>"; 583 } 584 585 /// Print the module map for this module to the given stream. 586 void print(raw_ostream &OS, unsigned Indent = 0) const; 587 588 /// Dump the contents of this module to the given output stream. 589 void dump() const; 590 591 private: 592 void buildVisibleModulesCache() const; 593 }; 594 595 /// A set of visible modules. 596 class VisibleModuleSet { 597 public: 598 VisibleModuleSet() = default; 599 VisibleModuleSet(VisibleModuleSet &&O) 600 : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) { 601 O.ImportLocs.clear(); 602 ++O.Generation; 603 } 604 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(); 610 ++O.Generation; 611 ++Generation; 612 return *this; 613 } 614 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; } 618 619 /// Determine whether a module is visible. 620 bool isVisible(const Module *M) const { 621 return getImportLoc(M).isValid(); 622 } 623 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()] 628 : SourceLocation(); 629 } 630 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)>; 634 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, 640 StringRef Message)>; 641 642 /// Make a specific module visible. 643 void setVisible(Module *M, SourceLocation Loc, 644 VisibleCallback Vis = [](Module *) {}, 645 ConflictCallback Cb = [](ArrayRef<Module *>, Module *, 646 StringRef) {}); 647 648 private: 649 /// Import locations for each visible module. Indexed by the module's 650 /// VisibilityID. 651 std::vector<SourceLocation> ImportLocs; 652 653 /// Visibility generation, bumped every time the visibility state changes. 654 unsigned Generation = 0; 655 }; 656 657 /// Abstracts clang modules and precompiled header files and holds 658 /// everything needed to generate debug info for an imported module 659 /// or PCH. 660 class ASTSourceDescriptor { 661 StringRef PCHModuleName; 662 StringRef Path; 663 StringRef ASTFile; 664 ASTFileSignature Signature; 665 const Module *ClangModule = nullptr; 666 667 public: 668 ASTSourceDescriptor() = default; 669 ASTSourceDescriptor(StringRef Name, StringRef Path, StringRef ASTFile, 670 ASTFileSignature Signature) 671 : PCHModuleName(std::move(Name)), Path(std::move(Path)), 672 ASTFile(std::move(ASTFile)), Signature(Signature) {} 673 ASTSourceDescriptor(const Module &M); 674 675 std::string getModuleName() const; 676 StringRef getPath() const { return Path; } 677 StringRef getASTFile() const { return ASTFile; } 678 ASTFileSignature getSignature() const { return Signature; } 679 const Module *getModuleOrNull() const { return ClangModule; } 680 }; 681 682 683 } // namespace clang 684 685 #endif // LLVM_CLANG_BASIC_MODULE_H 686