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 {
49 virtual ~ModuleMapCallbacks() = default;
51 /// Called when a module map file has been read.
53 /// \param FileStart A SourceLocation referring to the start of the file's
55 /// \param File The file itself.
56 /// \param IsSystem Whether this is a module map from a system include path.
57 virtual void moduleMapFileRead(SourceLocation FileStart,
58 const FileEntry &File, bool IsSystem) {}
60 /// Called when a header is added during module map parsing.
62 /// \param Filename The header file itself.
63 virtual void moduleMapAddHeader(StringRef Filename) {}
65 /// Called when an umbrella header is added during module map parsing.
67 /// \param FileMgr FileManager instance
68 /// \param Header The umbrella header to collect.
69 virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
70 const FileEntry *Header) {}
74 SourceManager &SourceMgr;
75 DiagnosticsEngine &Diags;
76 const LangOptions &LangOpts;
77 const TargetInfo *Target;
78 HeaderSearch &HeaderInfo;
80 llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
82 /// The directory used for Clang-supplied, builtin include headers,
83 /// such as "stdint.h".
84 const DirectoryEntry *BuiltinIncludeDir = nullptr;
86 /// Language options used to parse the module map itself.
88 /// These are always simple C language options.
89 LangOptions MMapLangOpts;
91 /// The module that the main source file is associated with (the module
92 /// named LangOpts::CurrentModule, if we've loaded it).
93 Module *SourceModule = nullptr;
95 /// The global module for the current TU, if we still own it. (Ownership is
96 /// transferred if/when we create an enclosing module.
97 std::unique_ptr<Module> PendingGlobalModule;
99 /// The top-level modules that are known.
100 llvm::StringMap<Module *> Modules;
102 /// Shadow modules created while building this module map.
103 llvm::SmallVector<Module*, 2> ShadowModules;
105 /// The number of modules we have created in total.
106 unsigned NumCreatedModules = 0;
108 /// In case a module has a export_as entry, it might have a pending link
109 /// name to be determined if that module is imported.
110 llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
113 /// Use PendingLinkAsModule information to mark top level link names that
114 /// are going to be replaced by export_as aliases.
115 void resolveLinkAsDependencies(Module *Mod);
117 /// Make module to use export_as as the link dependency name if enough
118 /// information is available or add it to a pending list otherwise.
119 void addLinkAsDependency(Module *Mod);
121 /// Flags describing the role of a module header.
122 enum ModuleHeaderRole {
123 /// This header is normally included in the module.
126 /// This header is included but private.
129 /// This header is part of the module (for layering purposes) but
130 /// should be textually included.
133 // Caution: Adding an enumerator needs other changes.
134 // Adjust the number of bits for KnownHeader::Storage.
135 // Adjust the bitfield HeaderFileInfo::HeaderRole size.
136 // Adjust the HeaderFileInfoTrait::ReadData streaming.
137 // Adjust the HeaderFileInfoTrait::EmitData streaming.
138 // Adjust ModuleMap::addHeader.
141 /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
142 static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
144 /// Convert a header role to a kind.
145 static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
147 /// A header that is known to reside within a given module,
148 /// whether it was included or excluded.
150 llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
153 KnownHeader() : Storage(nullptr, NormalHeader) {}
154 KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
156 friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
157 return A.Storage == B.Storage;
159 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
160 return A.Storage != B.Storage;
163 /// Retrieve the module the header is stored in.
164 Module *getModule() const { return Storage.getPointer(); }
166 /// The role of this header within the module.
167 ModuleHeaderRole getRole() const { return Storage.getInt(); }
169 /// Whether this header is available in the module.
170 bool isAvailable() const {
171 return getModule()->isAvailable();
174 /// Whether this header is accessible from the specified module.
175 bool isAccessibleFrom(Module *M) const {
176 return !(getRole() & PrivateHeader) ||
177 (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
180 // Whether this known header is valid (i.e., it has an
181 // associated module).
182 explicit operator bool() const {
183 return Storage.getPointer() != nullptr;
187 using AdditionalModMapsSet = llvm::SmallPtrSet<const FileEntry *, 1>;
190 friend class ModuleMapParser;
193 llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>;
195 /// Mapping from each header to the module that owns the contents of
199 /// Map from file sizes to modules with lazy header directives of that size.
200 mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
202 /// Map from mtimes to modules with lazy header directives with those mtimes.
203 mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
204 LazyHeadersByModTime;
206 /// Mapping from directories with umbrella headers to the module
207 /// that is generated from the umbrella header.
209 /// This mapping is used to map headers that haven't explicitly been named
210 /// in the module map over to the module that includes them via its umbrella
212 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
214 /// A generation counter that is used to test whether modules of the
215 /// same name may shadow or are illegal redefinitions.
217 /// Modules from earlier scopes may shadow modules from later ones.
218 /// Modules from the same scope may not have the same name.
219 unsigned CurrentModuleScopeID = 0;
221 llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
223 /// The set of attributes that can be attached to a module.
225 /// Whether this is a system module.
226 unsigned IsSystem : 1;
228 /// Whether this is an extern "C" module.
229 unsigned IsExternC : 1;
231 /// Whether this is an exhaustive set of configuration macros.
232 unsigned IsExhaustive : 1;
234 /// Whether files in this module can only include non-modular headers
235 /// and headers from used modules.
236 unsigned NoUndeclaredIncludes : 1;
239 : IsSystem(false), IsExternC(false), IsExhaustive(false),
240 NoUndeclaredIncludes(false) {}
243 /// A directory for which framework modules can be inferred.
244 struct InferredDirectory {
245 /// Whether to infer modules from this directory.
246 unsigned InferModules : 1;
248 /// The attributes to use for inferred modules.
251 /// If \c InferModules is non-zero, the module map file that allowed
252 /// inferred modules. Otherwise, nullptr.
253 const FileEntry *ModuleMapFile;
255 /// The names of modules that cannot be inferred within this
257 SmallVector<std::string, 2> ExcludedModules;
259 InferredDirectory() : InferModules(false) {}
262 /// A mapping from directories to information about inferring
263 /// framework modules from within those directories.
264 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
266 /// A mapping from an inferred module to the module map that allowed the
268 llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
270 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
272 /// Describes whether we haved parsed a particular file as a module
274 llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
276 /// Resolve the given export declaration into an actual export
279 /// \param Mod The module in which we're resolving the export declaration.
281 /// \param Unresolved The export declaration to resolve.
283 /// \param Complain Whether this routine should complain about unresolvable
286 /// \returns The resolved export declaration, which will have a NULL pointer
287 /// if the export could not be resolved.
289 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
290 bool Complain) const;
292 /// Resolve the given module id to an actual module.
294 /// \param Id The module-id to resolve.
296 /// \param Mod The module in which we're resolving the module-id.
298 /// \param Complain Whether this routine should complain about unresolvable
301 /// \returns The resolved module, or null if the module-id could not be
303 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
305 /// Add an unresolved header to a module.
307 /// \param Mod The module in which we're adding the unresolved header
309 /// \param Header The unresolved header directive.
310 /// \param NeedsFramework If Mod is not a framework but a missing header would
311 /// be found in case Mod was, set it to true. False otherwise.
312 void addUnresolvedHeader(Module *Mod,
313 Module::UnresolvedHeaderDirective Header,
314 bool &NeedsFramework);
316 /// Look up the given header directive to find an actual header file.
318 /// \param M The module in which we're resolving the header directive.
319 /// \param Header The header directive to resolve.
320 /// \param RelativePathName Filled in with the relative path name from the
321 /// module to the resolved header.
322 /// \param NeedsFramework If M is not a framework but a missing header would
323 /// be found in case M was, set it to true. False otherwise.
324 /// \return The resolved file, if any.
325 const FileEntry *findHeader(Module *M,
326 const Module::UnresolvedHeaderDirective &Header,
327 SmallVectorImpl<char> &RelativePathName,
328 bool &NeedsFramework);
330 /// Resolve the given header directive.
332 /// \param M The module in which we're resolving the header directive.
333 /// \param Header The header directive to resolve.
334 /// \param NeedsFramework If M is not a framework but a missing header would
335 /// be found in case M was, set it to true. False otherwise.
336 void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
337 bool &NeedsFramework);
339 /// Attempt to resolve the specified header directive as naming a builtin
341 /// \return \c true if a corresponding builtin header was found.
342 bool resolveAsBuiltinHeader(Module *M,
343 const Module::UnresolvedHeaderDirective &Header);
345 /// Looks up the modules that \p File corresponds to.
347 /// If \p File represents a builtin header within Clang's builtin include
348 /// directory, this also loads all of the module maps to see if it will get
349 /// associated with a specific module (e.g. in /usr/include).
350 HeadersMap::iterator findKnownHeader(const FileEntry *File);
352 /// Searches for a module whose umbrella directory contains \p File.
354 /// \param File The header to search for.
356 /// \param IntermediateDirs On success, contains the set of directories
357 /// searched before finding \p File.
358 KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
359 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
361 /// Given that \p File is not in the Headers map, look it up within
362 /// umbrella directories and find or create a module for it.
363 KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
365 /// A convenience method to determine if \p File is (possibly nested)
366 /// in an umbrella directory.
367 bool isHeaderInUmbrellaDirs(const FileEntry *File) {
368 SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
369 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
372 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
373 Attributes Attrs, Module *Parent);
376 /// Construct a new module map.
378 /// \param SourceMgr The source manager used to find module files and headers.
379 /// This source manager should be shared with the header-search mechanism,
380 /// since they will refer to the same headers.
382 /// \param Diags A diagnostic engine used for diagnostics.
384 /// \param LangOpts Language options for this translation unit.
386 /// \param Target The target for this translation unit.
387 ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
388 const LangOptions &LangOpts, const TargetInfo *Target,
389 HeaderSearch &HeaderInfo);
391 /// Destroy the module map.
394 /// Set the target information.
395 void setTarget(const TargetInfo &Target);
397 /// Set the directory that contains Clang-supplied include
398 /// files, such as our stdarg.h or tgmath.h.
399 void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
400 BuiltinIncludeDir = Dir;
403 /// Get the directory that contains Clang-supplied include files.
404 const DirectoryEntry *getBuiltinDir() const {
405 return BuiltinIncludeDir;
408 /// Is this a compiler builtin header?
409 static bool isBuiltinHeader(StringRef FileName);
411 /// Add a module map callback.
412 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
413 Callbacks.push_back(std::move(Callback));
416 /// Retrieve the module that owns the given header file, if any.
418 /// \param File The header file that is likely to be included.
420 /// \param AllowTextual If \c true and \p File is a textual header, return
421 /// its owning module. Otherwise, no KnownHeader will be returned if the
422 /// file is only known as a textual header.
424 /// \returns The module KnownHeader, which provides the module that owns the
425 /// given header file. The KnownHeader is default constructed to indicate
426 /// that no module owns this header file.
427 KnownHeader findModuleForHeader(const FileEntry *File,
428 bool AllowTextual = false);
430 /// Retrieve all the modules that contain the given header file. This
431 /// may not include umbrella modules, nor information from external sources,
432 /// if they have not yet been inferred / loaded.
434 /// Typically, \ref findModuleForHeader should be used instead, as it picks
435 /// the preferred module for the header.
436 ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
438 /// Resolve all lazy header directives for the specified file.
440 /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
441 /// is effectively internal, but is exposed so HeaderSearch can call it.
442 void resolveHeaderDirectives(const FileEntry *File) const;
444 /// Resolve all lazy header directives for the specified module.
445 void resolveHeaderDirectives(Module *Mod) const;
447 /// Reports errors if a module must not include a specific file.
449 /// \param RequestingModule The module including a file.
451 /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
452 /// the interface of RequestingModule, \c false if it's in the
453 /// implementation of RequestingModule. Value is ignored and
454 /// meaningless if RequestingModule is nullptr.
456 /// \param FilenameLoc The location of the inclusion's filename.
458 /// \param Filename The included filename as written.
460 /// \param File The included file.
461 void diagnoseHeaderInclusion(Module *RequestingModule,
462 bool RequestingModuleIsModuleInterface,
463 SourceLocation FilenameLoc, StringRef Filename,
464 const FileEntry *File);
466 /// Determine whether the given header is part of a module
467 /// marked 'unavailable'.
468 bool isHeaderInUnavailableModule(const FileEntry *Header) const;
470 /// Determine whether the given header is unavailable as part
471 /// of the specified module.
472 bool isHeaderUnavailableInModule(const FileEntry *Header,
473 const Module *RequestingModule) const;
475 /// Retrieve a module with the given name.
477 /// \param Name The name of the module to look up.
479 /// \returns The named module, if known; otherwise, returns null.
480 Module *findModule(StringRef Name) const;
482 /// Retrieve a module with the given name using lexical name lookup,
483 /// starting at the given context.
485 /// \param Name The name of the module to look up.
487 /// \param Context The module context, from which we will perform lexical
490 /// \returns The named module, if known; otherwise, returns null.
491 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
493 /// Retrieve a module with the given name within the given context,
494 /// using direct (qualified) name lookup.
496 /// \param Name The name of the module to look up.
498 /// \param Context The module for which we will look for a submodule. If
499 /// null, we will look for a top-level module.
501 /// \returns The named submodule, if known; otherwose, returns null.
502 Module *lookupModuleQualified(StringRef Name, Module *Context) const;
504 /// Find a new module or submodule, or create it if it does not already
507 /// \param Name The name of the module to find or create.
509 /// \param Parent The module that will act as the parent of this submodule,
510 /// or nullptr to indicate that this is a top-level module.
512 /// \param IsFramework Whether this is a framework module.
514 /// \param IsExplicit Whether this is an explicit submodule.
516 /// \returns The found or newly-created module, along with a boolean value
517 /// that will be true if the module is newly-created.
518 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
522 /// Create a 'global module' for a C++ Modules TS module interface
525 /// We model the global module as a submodule of the module interface unit.
526 /// Unfortunately, we can't create the module interface unit's Module until
527 /// later, because we don't know what it will be called.
528 Module *createGlobalModuleForInterfaceUnit(SourceLocation Loc);
530 /// Create a new module for a C++ Modules TS module interface unit.
531 /// The module must not already exist, and will be configured for the current
534 /// Note that this also sets the current module to the newly-created module.
536 /// \returns The newly-created module.
537 Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name,
538 Module *GlobalModule);
540 /// Infer the contents of a framework module map from the given
541 /// framework directory.
542 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
543 bool IsSystem, Module *Parent);
545 /// Create a new top-level module that is shadowed by
546 /// \p ShadowingModule.
547 Module *createShadowedModule(StringRef Name, bool IsFramework,
548 Module *ShadowingModule);
550 /// Creates a new declaration scope for module names, allowing
551 /// previously defined modules to shadow definitions from the new scope.
553 /// \note Module names from earlier scopes will shadow names from the new
554 /// scope, which is the opposite of how shadowing works for variables.
555 void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
557 bool mayShadowNewModule(Module *ExistingModule) {
558 assert(!ExistingModule->Parent && "expected top-level module");
559 assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
560 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
563 /// Retrieve the module map file containing the definition of the given
566 /// \param Module The module whose module map file will be returned, if known.
568 /// \returns The file entry for the module map file containing the given
569 /// module, or nullptr if the module definition was inferred.
570 const FileEntry *getContainingModuleMapFile(const Module *Module) const;
572 /// Get the module map file that (along with the module name) uniquely
573 /// identifies this module.
575 /// The particular module that \c Name refers to may depend on how the module
576 /// was found in header search. However, the combination of \c Name and
577 /// this module map will be globally unique for top-level modules. In the case
578 /// of inferred modules, returns the module map that allowed the inference
579 /// (e.g. contained 'module *'). Otherwise, returns
580 /// getContainingModuleMapFile().
581 const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
583 void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap);
585 /// Get any module map files other than getModuleMapFileForUniquing(M)
586 /// that define submodules of a top-level module \p M. This is cheaper than
587 /// getting the module map file for each submodule individually, since the
588 /// expected number of results is very small.
589 AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
590 auto I = AdditionalModMaps.find(M);
591 if (I == AdditionalModMaps.end())
596 void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
597 AdditionalModMaps[M].insert(ModuleMap);
600 /// Resolve all of the unresolved exports in the given module.
602 /// \param Mod The module whose exports should be resolved.
604 /// \param Complain Whether to emit diagnostics for failures.
606 /// \returns true if any errors were encountered while resolving exports,
608 bool resolveExports(Module *Mod, bool Complain);
610 /// Resolve all of the unresolved uses in the given module.
612 /// \param Mod The module whose uses should be resolved.
614 /// \param Complain Whether to emit diagnostics for failures.
616 /// \returns true if any errors were encountered while resolving uses,
618 bool resolveUses(Module *Mod, bool Complain);
620 /// Resolve all of the unresolved conflicts in the given module.
622 /// \param Mod The module whose conflicts should be resolved.
624 /// \param Complain Whether to emit diagnostics for failures.
626 /// \returns true if any errors were encountered while resolving conflicts,
628 bool resolveConflicts(Module *Mod, bool Complain);
630 /// Sets the umbrella header of the given module to the given
632 void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
633 Twine NameAsWritten);
635 /// Sets the umbrella directory of the given module to the given
637 void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
638 Twine NameAsWritten);
640 /// Adds this header to the given module.
641 /// \param Role The role of the header wrt the module.
642 void addHeader(Module *Mod, Module::Header Header,
643 ModuleHeaderRole Role, bool Imported = false);
645 /// Marks this header as being excluded from the given module.
646 void excludeHeader(Module *Mod, Module::Header Header);
648 /// Parse the given module map file, and record any modules we
651 /// \param File The file to be parsed.
653 /// \param IsSystem Whether this module map file is in a system header
654 /// directory, and therefore should be considered a system module.
656 /// \param HomeDir The directory in which relative paths within this module
657 /// map file will be resolved.
659 /// \param ID The FileID of the file to process, if we've already entered it.
661 /// \param Offset [inout] On input the offset at which to start parsing. On
662 /// output, the offset at which the module map terminated.
664 /// \param ExternModuleLoc The location of the "extern module" declaration
665 /// that caused us to load this module map file, if any.
667 /// \returns true if an error occurred, false otherwise.
668 bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
669 const DirectoryEntry *HomeDir,
670 FileID ID = FileID(), unsigned *Offset = nullptr,
671 SourceLocation ExternModuleLoc = SourceLocation());
673 /// Dump the contents of the module map, for debugging purposes.
676 using module_iterator = llvm::StringMap<Module *>::const_iterator;
678 module_iterator module_begin() const { return Modules.begin(); }
679 module_iterator module_end() const { return Modules.end(); }
684 #endif // LLVM_CLANG_LEX_MODULEMAP_H