1 //===- ModuleMap.h - Describe the layout of modules -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ModuleMap interface, which describes the layout of a
11 // module as it relates to headers.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_LEX_MODULEMAP_H
16 #define LLVM_CLANG_LEX_MODULEMAP_H
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/Module.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/TinyPtrVector.h"
30 #include "llvm/ADT/Twine.h"
38 class DiagnosticsEngine;
45 /// A mechanism to observe the actions of the module map parser as it
46 /// reads module map files.
47 class ModuleMapCallbacks {
48 virtual void anchor();
51 virtual ~ModuleMapCallbacks() = default;
53 /// Called when a module map file has been read.
55 /// \param FileStart A SourceLocation referring to the start of the file's
57 /// \param File The file itself.
58 /// \param IsSystem Whether this is a module map from a system include path.
59 virtual void moduleMapFileRead(SourceLocation FileStart,
60 const FileEntry &File, bool IsSystem) {}
62 /// Called when a header is added during module map parsing.
64 /// \param Filename The header file itself.
65 virtual void moduleMapAddHeader(StringRef Filename) {}
67 /// Called when an umbrella header is added during module map parsing.
69 /// \param FileMgr FileManager instance
70 /// \param Header The umbrella header to collect.
71 virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
72 const FileEntry *Header) {}
76 SourceManager &SourceMgr;
77 DiagnosticsEngine &Diags;
78 const LangOptions &LangOpts;
79 const TargetInfo *Target;
80 HeaderSearch &HeaderInfo;
82 llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
84 /// The directory used for Clang-supplied, builtin include headers,
85 /// such as "stdint.h".
86 const DirectoryEntry *BuiltinIncludeDir = nullptr;
88 /// Language options used to parse the module map itself.
90 /// These are always simple C language options.
91 LangOptions MMapLangOpts;
93 /// The module that the main source file is associated with (the module
94 /// named LangOpts::CurrentModule, if we've loaded it).
95 Module *SourceModule = nullptr;
97 /// Submodules of the current module that have not yet been attached to it.
98 /// (Ownership is transferred if/when we create an enclosing module.)
99 llvm::SmallVector<std::unique_ptr<Module>, 8> PendingSubmodules;
101 /// The top-level modules that are known.
102 llvm::StringMap<Module *> Modules;
104 /// Shadow modules created while building this module map.
105 llvm::SmallVector<Module*, 2> ShadowModules;
107 /// The number of modules we have created in total.
108 unsigned NumCreatedModules = 0;
110 /// In case a module has a export_as entry, it might have a pending link
111 /// name to be determined if that module is imported.
112 llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
115 /// Use PendingLinkAsModule information to mark top level link names that
116 /// are going to be replaced by export_as aliases.
117 void resolveLinkAsDependencies(Module *Mod);
119 /// Make module to use export_as as the link dependency name if enough
120 /// information is available or add it to a pending list otherwise.
121 void addLinkAsDependency(Module *Mod);
123 /// Flags describing the role of a module header.
124 enum ModuleHeaderRole {
125 /// This header is normally included in the module.
128 /// This header is included but private.
131 /// This header is part of the module (for layering purposes) but
132 /// should be textually included.
135 // Caution: Adding an enumerator needs other changes.
136 // Adjust the number of bits for KnownHeader::Storage.
137 // Adjust the bitfield HeaderFileInfo::HeaderRole size.
138 // Adjust the HeaderFileInfoTrait::ReadData streaming.
139 // Adjust the HeaderFileInfoTrait::EmitData streaming.
140 // Adjust ModuleMap::addHeader.
143 /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
144 static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
146 /// Convert a header role to a kind.
147 static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
149 /// A header that is known to reside within a given module,
150 /// whether it was included or excluded.
152 llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
155 KnownHeader() : Storage(nullptr, NormalHeader) {}
156 KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
158 friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
159 return A.Storage == B.Storage;
161 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
162 return A.Storage != B.Storage;
165 /// Retrieve the module the header is stored in.
166 Module *getModule() const { return Storage.getPointer(); }
168 /// The role of this header within the module.
169 ModuleHeaderRole getRole() const { return Storage.getInt(); }
171 /// Whether this header is available in the module.
172 bool isAvailable() const {
173 return getModule()->isAvailable();
176 /// Whether this header is accessible from the specified module.
177 bool isAccessibleFrom(Module *M) const {
178 return !(getRole() & PrivateHeader) ||
179 (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
182 // Whether this known header is valid (i.e., it has an
183 // associated module).
184 explicit operator bool() const {
185 return Storage.getPointer() != nullptr;
189 using AdditionalModMapsSet = llvm::SmallPtrSet<const FileEntry *, 1>;
192 friend class ModuleMapParser;
195 llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>;
197 /// Mapping from each header to the module that owns the contents of
201 /// Map from file sizes to modules with lazy header directives of that size.
202 mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
204 /// Map from mtimes to modules with lazy header directives with those mtimes.
205 mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
206 LazyHeadersByModTime;
208 /// Mapping from directories with umbrella headers to the module
209 /// that is generated from the umbrella header.
211 /// This mapping is used to map headers that haven't explicitly been named
212 /// in the module map over to the module that includes them via its umbrella
214 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
216 /// A generation counter that is used to test whether modules of the
217 /// same name may shadow or are illegal redefinitions.
219 /// Modules from earlier scopes may shadow modules from later ones.
220 /// Modules from the same scope may not have the same name.
221 unsigned CurrentModuleScopeID = 0;
223 llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
225 /// The set of attributes that can be attached to a module.
227 /// Whether this is a system module.
228 unsigned IsSystem : 1;
230 /// Whether this is an extern "C" module.
231 unsigned IsExternC : 1;
233 /// Whether this is an exhaustive set of configuration macros.
234 unsigned IsExhaustive : 1;
236 /// Whether files in this module can only include non-modular headers
237 /// and headers from used modules.
238 unsigned NoUndeclaredIncludes : 1;
241 : IsSystem(false), IsExternC(false), IsExhaustive(false),
242 NoUndeclaredIncludes(false) {}
245 /// A directory for which framework modules can be inferred.
246 struct InferredDirectory {
247 /// Whether to infer modules from this directory.
248 unsigned InferModules : 1;
250 /// The attributes to use for inferred modules.
253 /// If \c InferModules is non-zero, the module map file that allowed
254 /// inferred modules. Otherwise, nullptr.
255 const FileEntry *ModuleMapFile;
257 /// The names of modules that cannot be inferred within this
259 SmallVector<std::string, 2> ExcludedModules;
261 InferredDirectory() : InferModules(false) {}
264 /// A mapping from directories to information about inferring
265 /// framework modules from within those directories.
266 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
268 /// A mapping from an inferred module to the module map that allowed the
270 llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
272 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
274 /// Describes whether we haved parsed a particular file as a module
276 llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
278 /// Resolve the given export declaration into an actual export
281 /// \param Mod The module in which we're resolving the export declaration.
283 /// \param Unresolved The export declaration to resolve.
285 /// \param Complain Whether this routine should complain about unresolvable
288 /// \returns The resolved export declaration, which will have a NULL pointer
289 /// if the export could not be resolved.
291 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
292 bool Complain) const;
294 /// Resolve the given module id to an actual module.
296 /// \param Id The module-id to resolve.
298 /// \param Mod The module in which we're resolving the module-id.
300 /// \param Complain Whether this routine should complain about unresolvable
303 /// \returns The resolved module, or null if the module-id could not be
305 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
307 /// Add an unresolved header to a module.
309 /// \param Mod The module in which we're adding the unresolved header
311 /// \param Header The unresolved header directive.
312 /// \param NeedsFramework If Mod is not a framework but a missing header would
313 /// be found in case Mod was, set it to true. False otherwise.
314 void addUnresolvedHeader(Module *Mod,
315 Module::UnresolvedHeaderDirective Header,
316 bool &NeedsFramework);
318 /// Look up the given header directive to find an actual header file.
320 /// \param M The module in which we're resolving the header directive.
321 /// \param Header The header directive to resolve.
322 /// \param RelativePathName Filled in with the relative path name from the
323 /// module to the resolved header.
324 /// \param NeedsFramework If M is not a framework but a missing header would
325 /// be found in case M was, set it to true. False otherwise.
326 /// \return The resolved file, if any.
327 const FileEntry *findHeader(Module *M,
328 const Module::UnresolvedHeaderDirective &Header,
329 SmallVectorImpl<char> &RelativePathName,
330 bool &NeedsFramework);
332 /// Resolve the given header directive.
334 /// \param M The module in which we're resolving the header directive.
335 /// \param Header The header directive to resolve.
336 /// \param NeedsFramework If M is not a framework but a missing header would
337 /// be found in case M was, set it to true. False otherwise.
338 void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
339 bool &NeedsFramework);
341 /// Attempt to resolve the specified header directive as naming a builtin
343 /// \return \c true if a corresponding builtin header was found.
344 bool resolveAsBuiltinHeader(Module *M,
345 const Module::UnresolvedHeaderDirective &Header);
347 /// Looks up the modules that \p File corresponds to.
349 /// If \p File represents a builtin header within Clang's builtin include
350 /// directory, this also loads all of the module maps to see if it will get
351 /// associated with a specific module (e.g. in /usr/include).
352 HeadersMap::iterator findKnownHeader(const FileEntry *File);
354 /// Searches for a module whose umbrella directory contains \p File.
356 /// \param File The header to search for.
358 /// \param IntermediateDirs On success, contains the set of directories
359 /// searched before finding \p File.
360 KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
361 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
363 /// Given that \p File is not in the Headers map, look it up within
364 /// umbrella directories and find or create a module for it.
365 KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
367 /// A convenience method to determine if \p File is (possibly nested)
368 /// in an umbrella directory.
369 bool isHeaderInUmbrellaDirs(const FileEntry *File) {
370 SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
371 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
374 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
375 Attributes Attrs, Module *Parent);
378 /// Construct a new module map.
380 /// \param SourceMgr The source manager used to find module files and headers.
381 /// This source manager should be shared with the header-search mechanism,
382 /// since they will refer to the same headers.
384 /// \param Diags A diagnostic engine used for diagnostics.
386 /// \param LangOpts Language options for this translation unit.
388 /// \param Target The target for this translation unit.
389 ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
390 const LangOptions &LangOpts, const TargetInfo *Target,
391 HeaderSearch &HeaderInfo);
393 /// Destroy the module map.
396 /// Set the target information.
397 void setTarget(const TargetInfo &Target);
399 /// Set the directory that contains Clang-supplied include
400 /// files, such as our stdarg.h or tgmath.h.
401 void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
402 BuiltinIncludeDir = Dir;
405 /// Get the directory that contains Clang-supplied include files.
406 const DirectoryEntry *getBuiltinDir() const {
407 return BuiltinIncludeDir;
410 /// Is this a compiler builtin header?
411 static bool isBuiltinHeader(StringRef FileName);
413 /// Add a module map callback.
414 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
415 Callbacks.push_back(std::move(Callback));
418 /// Retrieve the module that owns the given header file, if any.
420 /// \param File The header file that is likely to be included.
422 /// \param AllowTextual If \c true and \p File is a textual header, return
423 /// its owning module. Otherwise, no KnownHeader will be returned if the
424 /// file is only known as a textual header.
426 /// \returns The module KnownHeader, which provides the module that owns the
427 /// given header file. The KnownHeader is default constructed to indicate
428 /// that no module owns this header file.
429 KnownHeader findModuleForHeader(const FileEntry *File,
430 bool AllowTextual = false);
432 /// Retrieve all the modules that contain the given header file. This
433 /// may not include umbrella modules, nor information from external sources,
434 /// if they have not yet been inferred / loaded.
436 /// Typically, \ref findModuleForHeader should be used instead, as it picks
437 /// the preferred module for the header.
438 ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
440 /// Resolve all lazy header directives for the specified file.
442 /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
443 /// is effectively internal, but is exposed so HeaderSearch can call it.
444 void resolveHeaderDirectives(const FileEntry *File) const;
446 /// Resolve all lazy header directives for the specified module.
447 void resolveHeaderDirectives(Module *Mod) const;
449 /// Reports errors if a module must not include a specific file.
451 /// \param RequestingModule The module including a file.
453 /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
454 /// the interface of RequestingModule, \c false if it's in the
455 /// implementation of RequestingModule. Value is ignored and
456 /// meaningless if RequestingModule is nullptr.
458 /// \param FilenameLoc The location of the inclusion's filename.
460 /// \param Filename The included filename as written.
462 /// \param File The included file.
463 void diagnoseHeaderInclusion(Module *RequestingModule,
464 bool RequestingModuleIsModuleInterface,
465 SourceLocation FilenameLoc, StringRef Filename,
466 const FileEntry *File);
468 /// Determine whether the given header is part of a module
469 /// marked 'unavailable'.
470 bool isHeaderInUnavailableModule(const FileEntry *Header) const;
472 /// Determine whether the given header is unavailable as part
473 /// of the specified module.
474 bool isHeaderUnavailableInModule(const FileEntry *Header,
475 const Module *RequestingModule) const;
477 /// Retrieve a module with the given name.
479 /// \param Name The name of the module to look up.
481 /// \returns The named module, if known; otherwise, returns null.
482 Module *findModule(StringRef Name) const;
484 /// Retrieve a module with the given name using lexical name lookup,
485 /// starting at the given context.
487 /// \param Name The name of the module to look up.
489 /// \param Context The module context, from which we will perform lexical
492 /// \returns The named module, if known; otherwise, returns null.
493 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
495 /// Retrieve a module with the given name within the given context,
496 /// using direct (qualified) name lookup.
498 /// \param Name The name of the module to look up.
500 /// \param Context The module for which we will look for a submodule. If
501 /// null, we will look for a top-level module.
503 /// \returns The named submodule, if known; otherwose, returns null.
504 Module *lookupModuleQualified(StringRef Name, Module *Context) const;
506 /// Find a new module or submodule, or create it if it does not already
509 /// \param Name The name of the module to find or create.
511 /// \param Parent The module that will act as the parent of this submodule,
512 /// or nullptr to indicate that this is a top-level module.
514 /// \param IsFramework Whether this is a framework module.
516 /// \param IsExplicit Whether this is an explicit submodule.
518 /// \returns The found or newly-created module, along with a boolean value
519 /// that will be true if the module is newly-created.
520 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
524 /// Create a 'global module' for a C++ Modules TS module interface unit.
526 /// We model the global module as a submodule of the module interface unit.
527 /// Unfortunately, we can't create the module interface unit's Module until
528 /// later, because we don't know what it will be called.
529 Module *createGlobalModuleForInterfaceUnit(SourceLocation Loc);
531 /// Create a new module for a C++ Modules TS module interface unit.
532 /// The module must not already exist, and will be configured for the current
535 /// Note that this also sets the current module to the newly-created module.
537 /// \returns The newly-created module.
538 Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name,
539 Module *GlobalModule);
541 /// Create a header module from the specified list of headers.
542 Module *createHeaderModule(StringRef Name, ArrayRef<Module::Header> Headers);
544 /// Infer the contents of a framework module map from the given
545 /// framework directory.
546 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
547 bool IsSystem, Module *Parent);
549 /// Create a new top-level module that is shadowed by
550 /// \p ShadowingModule.
551 Module *createShadowedModule(StringRef Name, bool IsFramework,
552 Module *ShadowingModule);
554 /// Creates a new declaration scope for module names, allowing
555 /// previously defined modules to shadow definitions from the new scope.
557 /// \note Module names from earlier scopes will shadow names from the new
558 /// scope, which is the opposite of how shadowing works for variables.
559 void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
561 bool mayShadowNewModule(Module *ExistingModule) {
562 assert(!ExistingModule->Parent && "expected top-level module");
563 assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
564 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
567 /// Retrieve the module map file containing the definition of the given
570 /// \param Module The module whose module map file will be returned, if known.
572 /// \returns The file entry for the module map file containing the given
573 /// module, or nullptr if the module definition was inferred.
574 const FileEntry *getContainingModuleMapFile(const Module *Module) const;
576 /// Get the module map file that (along with the module name) uniquely
577 /// identifies this module.
579 /// The particular module that \c Name refers to may depend on how the module
580 /// was found in header search. However, the combination of \c Name and
581 /// this module map will be globally unique for top-level modules. In the case
582 /// of inferred modules, returns the module map that allowed the inference
583 /// (e.g. contained 'module *'). Otherwise, returns
584 /// getContainingModuleMapFile().
585 const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
587 void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap);
589 /// Get any module map files other than getModuleMapFileForUniquing(M)
590 /// that define submodules of a top-level module \p M. This is cheaper than
591 /// getting the module map file for each submodule individually, since the
592 /// expected number of results is very small.
593 AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
594 auto I = AdditionalModMaps.find(M);
595 if (I == AdditionalModMaps.end())
600 void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
601 AdditionalModMaps[M].insert(ModuleMap);
604 /// Resolve all of the unresolved exports in the given module.
606 /// \param Mod The module whose exports should be resolved.
608 /// \param Complain Whether to emit diagnostics for failures.
610 /// \returns true if any errors were encountered while resolving exports,
612 bool resolveExports(Module *Mod, bool Complain);
614 /// Resolve all of the unresolved uses in the given module.
616 /// \param Mod The module whose uses should be resolved.
618 /// \param Complain Whether to emit diagnostics for failures.
620 /// \returns true if any errors were encountered while resolving uses,
622 bool resolveUses(Module *Mod, bool Complain);
624 /// Resolve all of the unresolved conflicts in the given module.
626 /// \param Mod The module whose conflicts should be resolved.
628 /// \param Complain Whether to emit diagnostics for failures.
630 /// \returns true if any errors were encountered while resolving conflicts,
632 bool resolveConflicts(Module *Mod, bool Complain);
634 /// Sets the umbrella header of the given module to the given
636 void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
637 Twine NameAsWritten);
639 /// Sets the umbrella directory of the given module to the given
641 void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
642 Twine NameAsWritten);
644 /// Adds this header to the given module.
645 /// \param Role The role of the header wrt the module.
646 void addHeader(Module *Mod, Module::Header Header,
647 ModuleHeaderRole Role, bool Imported = false);
649 /// Marks this header as being excluded from the given module.
650 void excludeHeader(Module *Mod, Module::Header Header);
652 /// Parse the given module map file, and record any modules we
655 /// \param File The file to be parsed.
657 /// \param IsSystem Whether this module map file is in a system header
658 /// directory, and therefore should be considered a system module.
660 /// \param HomeDir The directory in which relative paths within this module
661 /// map file will be resolved.
663 /// \param ID The FileID of the file to process, if we've already entered it.
665 /// \param Offset [inout] On input the offset at which to start parsing. On
666 /// output, the offset at which the module map terminated.
668 /// \param ExternModuleLoc The location of the "extern module" declaration
669 /// that caused us to load this module map file, if any.
671 /// \returns true if an error occurred, false otherwise.
672 bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
673 const DirectoryEntry *HomeDir,
674 FileID ID = FileID(), unsigned *Offset = nullptr,
675 SourceLocation ExternModuleLoc = SourceLocation());
677 /// Dump the contents of the module map, for debugging purposes.
680 using module_iterator = llvm::StringMap<Module *>::const_iterator;
682 module_iterator module_begin() const { return Modules.begin(); }
683 module_iterator module_end() const { return Modules.end(); }
688 #endif // LLVM_CLANG_LEX_MODULEMAP_H