clang 24.0.0git
ModuleMap.h
Go to the documentation of this file.
1//===- ModuleMap.h - Describe the layout of modules -------------*- 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// This file defines the ModuleMap interface, which describes the layout of a
10// module as it relates to headers.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_MODULEMAP_H
15#define LLVM_CLANG_LEX_MODULEMAP_H
16
19#include "clang/Basic/Module.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringMap.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSet.h"
30#include "llvm/ADT/TinyPtrVector.h"
31#include "llvm/ADT/Twine.h"
32#include <ctime>
33#include <memory>
34#include <optional>
35#include <string>
36#include <utility>
37
38namespace clang {
39
41class DirectoryEntry;
42class FileEntry;
43class FileManager;
44class HeaderSearch;
45class SourceManager;
46
47/// A mechanism to observe the actions of the module map loader as it
48/// reads module map files.
50 virtual void anchor();
51
52public:
53 virtual ~ModuleMapCallbacks() = default;
54
55 /// Called when a module map file has been read.
56 ///
57 /// \param FileStart A SourceLocation referring to the start of the file's
58 /// contents.
59 /// \param File The file itself.
60 /// \param IsSystem Whether this is a module map from a system include path.
62 bool IsSystem) {}
63
64 /// Called when a header is added during module map parsing.
65 ///
66 /// \param Filename The header file itself.
67 virtual void moduleMapAddHeader(StringRef Filename) {}
68
69 /// Called when an umbrella header is added during module map parsing.
70 ///
71 /// \param Header The umbrella header to collect.
73};
74
75class ModuleMap {
76 SourceManager &SourceMgr;
77 DiagnosticsEngine &Diags;
78 const LangOptions &LangOpts;
79 const TargetInfo *Target;
80 HeaderSearch &HeaderInfo;
81
83
84 /// The directory used for Clang-supplied, builtin include headers,
85 /// such as "stdint.h".
86 OptionalDirectoryEntryRef BuiltinIncludeDir;
87
88 /// The module that the main source file is associated with (the module
89 /// named LangOpts::CurrentModule, if we've loaded it).
90 Module *SourceModule = nullptr;
91
92 /// The allocator for all (sub)modules.
93 llvm::SpecificBumpPtrAllocator<Module> ModulesAlloc;
94
95 /// Submodules of the current module that have not yet been attached to it.
96 /// (Relationship is set up if/when we create an enclosing module.)
97 llvm::SmallVector<Module *, 8> PendingSubmodules;
98
99 /// The top-level modules that are known.
100 llvm::StringMap<Module *> Modules;
101
102 /// Module loading cache that includes submodules, indexed by IdentifierInfo.
103 /// nullptr is stored for modules that are known to fail to load.
104 llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
105
106 /// The number of modules we have created in total.
107 unsigned NumCreatedModules = 0;
108
109 /// In case a module has a export_as entry, it might have a pending link
110 /// name to be determined if that module is imported.
111 llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
112
113public:
114 /// Use PendingLinkAsModule information to mark top level link names that
115 /// are going to be replaced by export_as aliases.
117
118 /// Make module to use export_as as the link dependency name if enough
119 /// information is available or add it to a pending list otherwise.
120 void addLinkAsDependency(Module *Mod);
121
122 /// Flags describing the role of a module header.
124 /// This header is normally included in the module.
126
127 /// This header is included but private.
129
130 /// This header is part of the module (for layering purposes) but
131 /// should be textually included.
133
134 /// This header is explicitly excluded from the module.
136
137 // Caution: Adding an enumerator needs other changes.
138 // Adjust the number of bits for KnownHeader::Storage.
139 // Adjust the HeaderFileInfoTrait::ReadData streaming.
140 // Adjust the HeaderFileInfoTrait::EmitData streaming.
141 // Adjust ModuleMap::addHeader.
142 };
143
144 /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
146
147 /// Convert a header role to a kind.
149
150 /// Check if the header with the given role is a modular one.
151 static bool isModular(ModuleHeaderRole Role);
152
153 /// A header that is known to reside within a given module,
154 /// whether it was included or excluded.
156 llvm::PointerIntPair<Module *, 3, ModuleHeaderRole> Storage;
157
158 public:
161
162 friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
163 return A.Storage == B.Storage;
164 }
165 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
166 return A.Storage != B.Storage;
167 }
168
169 /// Retrieve the module the header is stored in.
170 Module *getModule() const { return Storage.getPointer(); }
171
172 /// The role of this header within the module.
173 ModuleHeaderRole getRole() const { return Storage.getInt(); }
174
175 /// Whether this header is available in the module.
176 bool isAvailable() const {
177 return getRole() != ExcludedHeader && getModule()->isAvailable();
178 }
179
180 /// Whether this header is accessible from the specified module.
181 bool isAccessibleFrom(Module *M) const {
182 return !(getRole() & PrivateHeader) ||
183 (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
184 }
185
186 // Whether this known header is valid (i.e., it has an
187 // associated module).
188 explicit operator bool() const {
189 return Storage.getPointer() != nullptr;
190 }
191 };
192
193 using AdditionalModMapsSet = llvm::DenseSet<FileEntryRef>;
194
195private:
196 friend class ModuleMapLoader;
197
198 using HeadersMap = llvm::DenseMap<FileEntryRef, SmallVector<KnownHeader, 1>>;
199
200 /// Mapping from each header to the module that owns the contents of
201 /// that header.
202 HeadersMap Headers;
203
204 /// Map from file sizes to modules with lazy header directives of that size.
205 mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
206
207 /// Map from mtimes to modules with lazy header directives with those mtimes.
208 mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
209 LazyHeadersByModTime;
210
211 /// Mapping from directories with umbrella headers to the module
212 /// that is generated from the umbrella header.
213 ///
214 /// This mapping is used to map headers that haven't explicitly been named
215 /// in the module map over to the module that includes them via its umbrella
216 /// header.
217 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
218
219 /// Mapping from (header, (sub)module) pairs to the source location where
220 /// the header was added to the module (the header directive location).
221 /// TODO: Consider moving this into Module::Header and serializing it into
222 /// PCMs so that locations are available for headers deserialized from
223 /// modules. Need to evaluate size/perf overhead of adding a SourceLocation
224 /// to the serialization format for this diagnostic.
225 llvm::DenseMap<std::pair<const FileEntry *, const Module *>, SourceLocation>
226 HeaderOwnerLocs;
227
228 /// Headers for which we've already diagnosed duplicate ownership.
229 llvm::DenseSet<const FileEntry *> DiagnosedDuplicateHeaders;
230
231 /// A generation counter that is used to test whether modules of the
232 /// same name may shadow or are illegal redefinitions.
233 ///
234 /// Modules from earlier scopes may shadow modules from later ones.
235 /// Modules from the same scope may not have the same name.
236 unsigned CurrentModuleScopeID = 0;
237
238 llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
239
240 using Attributes = ModuleAttributes;
241
242 /// A directory for which framework modules can be inferred.
243 struct InferredDirectory {
244 /// Whether to infer modules from this directory.
245 LLVM_PREFERRED_TYPE(bool)
246 unsigned InferModules : 1;
247
248 /// The attributes to use for inferred modules.
249 Attributes Attrs;
250
251 /// If \c InferModules is non-zero, the module map file that allowed
252 /// inferred modules. Otherwise, invalid.
253 FileID ModuleMapFID;
254
255 /// The names of modules that cannot be inferred within this
256 /// directory.
257 SmallVector<std::string, 2> ExcludedModules;
258
259 InferredDirectory() : InferModules(false) {}
260 };
261
262 /// A mapping from directories to information about inferring
263 /// framework modules from within those directories.
264 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
265
266 /// A mapping from an inferred module to the module map that allowed the
267 /// inference.
268 llvm::DenseMap<const Module *, FileID> InferredModuleAllowedBy;
269
270 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
271
272 /// Describes whether we haved loaded a particular file as a module
273 /// map.
274 llvm::DenseMap<const FileEntry *, bool> LoadedModuleMap;
275 llvm::DenseMap<const FileEntry *, const modulemap::ModuleMapFile *>
276 ParsedModuleMap;
277
278 /// Each CompilerInstance needs its own FileID for each module map, but there
279 /// should only ever be one for each.
280 llvm::DenseMap<const FileEntry *, FileID> ModuleMapLocalFileID;
281
282 std::vector<std::unique_ptr<modulemap::ModuleMapFile>> ParsedModuleMaps;
283
284 /// Map from top level module name to a list of ModuleDecls in the order they
285 /// were discovered. This allows handling shadowing correctly and diagnosing
286 /// redefinitions.
287 llvm::StringMap<SmallVector<std::pair<const modulemap::ModuleMapFile *,
288 const modulemap::ModuleDecl *>,
289 1>>
290 ParsedModules;
291
292 /// Resolve the given export declaration into an actual export
293 /// declaration.
294 ///
295 /// \param Mod The module in which we're resolving the export declaration.
296 ///
297 /// \param Unresolved The export declaration to resolve.
298 ///
299 /// \param Complain Whether this routine should complain about unresolvable
300 /// exports.
301 ///
302 /// \returns The resolved export declaration, which will have a NULL pointer
303 /// if the export could not be resolved.
305 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
306 bool Complain) const;
307
308 /// Resolve the given module id to an actual module.
309 ///
310 /// \param Id The module-id to resolve.
311 ///
312 /// \param Mod The module in which we're resolving the module-id.
313 ///
314 /// \param Complain Whether this routine should complain about unresolvable
315 /// module-ids.
316 ///
317 /// \returns The resolved module, or null if the module-id could not be
318 /// resolved.
319 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
320
321 /// Add an unresolved header to a module.
322 ///
323 /// \param Mod The module in which we're adding the unresolved header
324 /// directive.
325 /// \param Header The unresolved header directive.
326 /// \param NeedsFramework If Mod is not a framework but a missing header would
327 /// be found in case Mod was, set it to true. False otherwise.
328 void addUnresolvedHeader(Module *Mod,
329 Module::UnresolvedHeaderDirective Header,
330 bool &NeedsFramework);
331
332 /// Look up the given header directive to find an actual header file.
333 ///
334 /// \param M The module in which we're resolving the header directive.
335 /// \param Header The header directive to resolve.
336 /// \param RelativePathName Filled in with the relative path name from the
337 /// module to the resolved header.
338 /// \param NeedsFramework If M is not a framework but a missing header would
339 /// be found in case M was, set it to true. False otherwise.
340 /// \return The resolved file, if any.
342 findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
343 SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
344
345 /// Resolve the given header directive.
346 ///
347 /// \param M The module in which we're resolving the header directive.
348 /// \param Header The header directive to resolve.
349 /// \param NeedsFramework If M is not a framework but a missing header would
350 /// be found in case M was, set it to true. False otherwise.
351 void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
352 bool &NeedsFramework);
353
354 /// Attempt to resolve the specified header directive as naming a builtin
355 /// header.
356 /// \return \c true if a corresponding builtin header was found.
357 bool resolveAsBuiltinHeader(Module *M,
358 const Module::UnresolvedHeaderDirective &Header);
359
360 /// Looks up the modules that \p File corresponds to.
361 ///
362 /// If \p File represents a builtin header within Clang's builtin include
363 /// directory, this also loads all of the module maps to see if it will get
364 /// associated with a specific module (e.g. in /usr/include).
365 HeadersMap::iterator findKnownHeader(FileEntryRef File);
366
367 /// Warn if a header is owned by multiple top-level modules.
368 void diagnoseDuplicateHeaderOwnership(SourceLocation FilenameLoc,
369 StringRef Filename, FileEntryRef File,
370 HeadersMap::iterator Known);
371
372 /// Searches for a module whose umbrella directory contains \p File.
373 ///
374 /// \param File The header to search for.
375 ///
376 /// \param IntermediateDirs On success, contains the set of directories
377 /// searched before finding \p File.
378 KnownHeader findHeaderInUmbrellaDirs(
379 FileEntryRef File, SmallVectorImpl<DirectoryEntryRef> &IntermediateDirs);
380
381 /// Given that \p File is not in the Headers map, look it up within
382 /// umbrella directories and find or create a module for it.
383 KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File);
384
385 /// A convenience method to determine if \p File is (possibly nested)
386 /// in an umbrella directory.
387 bool isHeaderInUmbrellaDirs(FileEntryRef File) {
388 SmallVector<DirectoryEntryRef, 2> IntermediateDirs;
389 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
390 }
391
392 Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, Attributes Attrs,
393 Module *Parent);
394
395public:
396 /// Construct a new module map.
397 ///
398 /// \param SourceMgr The source manager used to find module files and headers.
399 /// This source manager should be shared with the header-search mechanism,
400 /// since they will refer to the same headers.
401 ///
402 /// \param Diags A diagnostic engine used for diagnostics.
403 ///
404 /// \param LangOpts Language options for this translation unit.
405 ///
406 /// \param Target The target for this translation unit.
407 ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
408 const LangOptions &LangOpts, const TargetInfo *Target,
409 HeaderSearch &HeaderInfo);
410
411 /// Destroy the module map.
413
414 /// Set the target information.
415 void setTarget(const TargetInfo &Target);
416
417 /// Set the directory that contains Clang-supplied include files, such as our
418 /// stdarg.h or tgmath.h.
419 void setBuiltinIncludeDir(DirectoryEntryRef Dir) { BuiltinIncludeDir = Dir; }
420
421 /// Get the directory that contains Clang-supplied include files.
422 OptionalDirectoryEntryRef getBuiltinDir() const { return BuiltinIncludeDir; }
423
424 /// Is this a compiler builtin header?
426
428 Module *Module) const;
429
430 /// Add a module map callback.
431 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
432 Callbacks.push_back(std::move(Callback));
433 }
434
435 /// Retrieve the module that owns the given header file, if any. Note that
436 /// this does not implicitly load module maps, except for builtin headers,
437 /// and does not consult the external source. (Those checks are the
438 /// responsibility of \ref HeaderSearch.)
439 ///
440 /// \param File The header file that is likely to be included.
441 ///
442 /// \param AllowTextual If \c true and \p File is a textual header, return
443 /// its owning module. Otherwise, no KnownHeader will be returned if the
444 /// file is only known as a textual header.
445 ///
446 /// \returns The module KnownHeader, which provides the module that owns the
447 /// given header file. The KnownHeader is default constructed to indicate
448 /// that no module owns this header file.
449 KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual = false,
450 bool AllowExcluded = false);
451
452 /// Find the FileEntry for an umbrella header in a module as if it was written
453 /// in the module map as a header decl.
454 ///
455 /// \param M The module in which we're resolving the header directive.
456 /// \param NameAsWritten The name of the header as written in the module map.
457 /// \param[out] RelativePathName Filled in with the relative path name from
458 /// the module to the resolved header.
459 /// \return The resolved file, if any.
461 findUmbrellaHeaderForModule(Module *M, std::string NameAsWritten,
462 SmallVectorImpl<char> &RelativePathName);
463
464 /// Retrieve all the modules that contain the given header file. Note that
465 /// this does not implicitly load module maps, except for builtin headers,
466 /// and does not consult the external source. (Those checks are the
467 /// responsibility of \ref HeaderSearch.)
468 ///
469 /// Typically, \ref findModuleForHeader should be used instead, as it picks
470 /// the preferred module for the header.
472
473 /// Like \ref findAllModulesForHeader, but do not attempt to infer module
474 /// ownership from umbrella headers if we've not already done so.
476
477 /// Resolve all lazy header directives for the specified file.
478 ///
479 /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
480 /// is effectively internal, but is exposed so HeaderSearch can call it.
481 void resolveHeaderDirectives(const FileEntry *File) const;
482
483 /// Resolve lazy header directives for the specified module. If File is
484 /// provided, only headers with same size and modtime are resolved. If File
485 /// is not set, all headers are resolved.
487 std::optional<const FileEntry *> File) const;
488
489 /// Reports errors if a module must not include a specific file.
490 ///
491 /// \param RequestingModule The module including a file.
492 ///
493 /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
494 /// the interface of RequestingModule, \c false if it's in the
495 /// implementation of RequestingModule. Value is ignored and
496 /// meaningless if RequestingModule is nullptr.
497 ///
498 /// \param FilenameLoc The location of the inclusion's filename.
499 ///
500 /// \param Filename The included filename as written.
501 ///
502 /// \param File The included file.
503 void diagnoseHeaderInclusion(Module *RequestingModule,
504 bool RequestingModuleIsModuleInterface,
505 SourceLocation FilenameLoc, StringRef Filename,
507
508 /// Determine whether the given header is part of a module
509 /// marked 'unavailable'.
510 bool isHeaderInUnavailableModule(FileEntryRef Header) const;
511
512 /// Determine whether the given header is unavailable as part
513 /// of the specified module.
515 const Module *RequestingModule) const;
516
517 /// Retrieve an already loaded module with the given name.
518 ///
519 /// \param Name The name of the module to look up.
520 ///
521 /// \returns The named module, if loaded; otherwise, returns null.
522 Module *findModule(StringRef Name) const;
523
524 Module *findOrLoadModule(StringRef Name);
525
526 /// Determine if a top-level module named \p Name was loaded or parsed.
527 bool isModuleKnown(StringRef Name) const {
528 return Modules.contains(Name) || ParsedModules.contains(Name);
529 }
530
531 /// Find the module map that defines the top-level module \p Name, without
532 /// loading it.
533 /// For an inferred module, this is the module map that allows inferring it
534 /// and requires loading.
535 OptionalFileEntryRef getModuleMapFileForName(StringRef Name) const;
536
537 Module *findOrInferSubmodule(Module *Parent, StringRef Name);
538
539 /// Retrieve a module with the given name using lexical name lookup,
540 /// starting at the given context.
541 ///
542 /// \param Name The name of the module to look up.
543 ///
544 /// \param Context The module context, from which we will perform lexical
545 /// name lookup.
546 ///
547 /// \returns The named module, if known; otherwise, returns null.
548 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
549
550 /// Retrieve a module with the given name within the given context,
551 /// using direct (qualified) name lookup.
552 ///
553 /// \param Name The name of the module to look up.
554 ///
555 /// \param Context The module for which we will look for a submodule. If
556 /// null, we will look for a top-level module.
557 ///
558 /// \returns The named submodule, if known; otherwose, returns null.
559 ModuleRef lookupModuleQualified(StringRef Name, Module *Context) const;
560
561 /// Find a new module or submodule, or create it if it does not already
562 /// exist.
563 ///
564 /// \param Name The name of the module to find or create.
565 ///
566 /// \param Parent The module that will act as the parent of this submodule,
567 /// or nullptr to indicate that this is a top-level module.
568 ///
569 /// \param IsFramework Whether this is a framework module.
570 ///
571 /// \param IsExplicit Whether this is an explicit submodule.
572 ///
573 /// \returns The found or newly-created module, along with a boolean value
574 /// that will be true if the module is newly-created.
575 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
576 bool IsFramework,
577 bool IsExplicit);
578 /// Call \c ModuleMap::findOrCreateModule and throw away the information
579 /// whether the module was found or created.
580 Module *findOrCreateModuleFirst(StringRef Name, Module *Parent,
581 bool IsFramework, bool IsExplicit) {
582 return findOrCreateModule(Name, Parent, IsFramework, IsExplicit).first;
583 }
584 /// Create new submodule, assuming it does not exist. This function can only
585 /// be called when it is guaranteed that this submodule does not exist yet.
586 /// The parameters have same semantics as \c ModuleMap::findOrCreateModule.
587 Module *createModule(StringRef Name, Module *Parent, bool IsFramework,
588 bool IsExplicit);
589
590 /// Create a global module fragment for a C++ module unit.
591 ///
592 /// We model the global module fragment as a submodule of the module
593 /// interface unit. Unfortunately, we can't create the module interface
594 /// unit's Module until later, because we don't know what it will be called
595 /// usually. See C++20 [module.unit]/7.2 for the case we could know its
596 /// parent.
598 Module *Parent = nullptr);
600 Module *Parent);
601
602 /// Create a global module fragment for a C++ module interface unit.
604 SourceLocation Loc);
605
606 /// Create a new C++ module with the specified kind, and reparent any pending
607 /// global module fragment(s) to it.
609 Module::ModuleKind Kind);
610
611 /// Create a new module for a C++ module interface unit.
612 /// The module must not already exist, and will be configured for the current
613 /// compilation.
614 ///
615 /// Note that this also sets the current module to the newly-created module.
616 ///
617 /// \returns The newly-created module.
619
620 /// Create a new module for a C++ module implementation unit.
621 /// The interface module for this implementation (implicitly imported) must
622 /// exist and be loaded and present in the modules map.
623 ///
624 /// \returns The newly-created module.
626
627 /// Create a C++20 header unit.
628 Module *createHeaderUnit(SourceLocation Loc, StringRef Name,
630
631 /// Infer the contents of a framework module map from the given
632 /// framework directory.
633 Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, bool IsSystem,
634 Module *Parent);
635
636 /// Create a new top-level module that is shadowed by
637 /// \p ShadowingModule.
638 Module *createShadowedModule(StringRef Name, bool IsFramework,
639 Module *ShadowingModule);
640
641 /// Creates a new declaration scope for module names, allowing
642 /// previously defined modules to shadow definitions from the new scope.
643 ///
644 /// \note Module names from earlier scopes will shadow names from the new
645 /// scope, which is the opposite of how shadowing works for variables.
646 void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
647
648 bool mayShadowNewModule(Module *ExistingModule) {
649 assert(!ExistingModule->Parent && "expected top-level module");
650 assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
651 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
652 }
653
654 /// Check whether a framework module can be inferred in the given directory.
656 auto It = InferredDirectories.find(Dir);
657 return It != InferredDirectories.end() && It->getSecond().InferModules;
658 }
659
660 /// Retrieve the module map file containing the definition of the given
661 /// module.
662 ///
663 /// \param Module The module whose module map file will be returned, if known.
664 ///
665 /// \returns The FileID for the module map file containing the given module,
666 /// invalid if the module definition was inferred.
669
670 /// Get the module map file that (along with the module name) uniquely
671 /// identifies this module.
672 ///
673 /// The particular module that \c Name refers to may depend on how the module
674 /// was found in header search. However, the combination of \c Name and
675 /// this module map will be globally unique for top-level modules. In the case
676 /// of inferred modules, returns the module map that allowed the inference
677 /// (e.g. contained 'module *'). Otherwise, returns
678 /// getContainingModuleMapFile().
681
682 void setInferredModuleAllowedBy(Module *M, FileID ModMapFID);
683
684 /// Canonicalize \p Path in a manner suitable for a module map file. In
685 /// particular, this canonicalizes the parent directory separately from the
686 /// filename so that it does not affect header resolution relative to the
687 /// modulemap.
688 ///
689 /// \returns an error code if any filesystem operations failed. In this case
690 /// \p Path is not modified.
692
693 /// Get any module map files other than getModuleMapFileForUniquing(M)
694 /// that define submodules of a top-level module \p M. This is cheaper than
695 /// getting the module map file for each submodule individually, since the
696 /// expected number of results is very small.
698 auto I = AdditionalModMaps.find(M);
699 if (I == AdditionalModMaps.end())
700 return nullptr;
701 return &I->second;
702 }
703
705
706 /// Resolve all of the unresolved exports in the given module.
707 ///
708 /// \param Mod The module whose exports should be resolved.
709 ///
710 /// \param Complain Whether to emit diagnostics for failures.
711 ///
712 /// \returns true if any errors were encountered while resolving exports,
713 /// false otherwise.
714 bool resolveExports(Module *Mod, bool Complain);
715
716 /// Resolve all of the unresolved uses in the given module.
717 ///
718 /// \param Mod The module whose uses should be resolved.
719 ///
720 /// \param Complain Whether to emit diagnostics for failures.
721 ///
722 /// \returns true if any errors were encountered while resolving uses,
723 /// false otherwise.
724 bool resolveUses(Module *Mod, bool Complain);
725
726 /// Resolve all of the unresolved conflicts in the given module.
727 ///
728 /// \param Mod The module whose conflicts should be resolved.
729 ///
730 /// \param Complain Whether to emit diagnostics for failures.
731 ///
732 /// \returns true if any errors were encountered while resolving conflicts,
733 /// false otherwise.
734 bool resolveConflicts(Module *Mod, bool Complain);
735
736 /// Sets the umbrella header of the given module to the given header.
737 void
739 const Twine &NameAsWritten,
740 const Twine &PathRelativeToRootModuleDirectory,
742
743 /// Record that \p Mod depends on the listing of \p Dir. \p Dir is a VFS path.
744 void recordDirectoryDependencies(Module *Mod, StringRef Dir);
745
746 /// Spell \p Path the way directory dependencies are recorded: absolute, with
747 /// dots removed.
750
751 /// Sets the umbrella directory of the given module to the given directory.
752 void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir,
753 const Twine &NameAsWritten,
754 const Twine &PathRelativeToRootModuleDirectory,
756
757 /// Adds this header to the given module.
758 /// \param Role The role of the header wrt the module.
760 bool Imported = false, SourceLocation Loc = SourceLocation());
761
762 /// Parse a module map without creating `clang::Module` instances.
763 bool parseModuleMapFile(FileEntryRef File, bool IsSystem,
764 bool ImplicitlyDiscovered, DirectoryEntryRef Dir,
765 FileID ID = FileID(),
766 SourceLocation ExternModuleLoc = SourceLocation());
767
769
770 /// Load the given module map file, and record any modules we
771 /// encounter.
772 ///
773 /// \param File The file to be loaded.
774 ///
775 /// \param IsSystem Whether this module map file is in a system header
776 /// directory, and therefore should be considered a system module.
777 ///
778 /// \param ImplicitlyDiscovered Whether this module map file was found via
779 /// module map search.
780 ///
781 /// \param HomeDir The directory in which relative paths within this module
782 /// map file will be resolved.
783 ///
784 /// \param ID The FileID of the file to process, if we've already entered it.
785 ///
786 /// \param Offset [inout] On input the offset at which to start parsing. On
787 /// output, the offset at which the module map terminated.
788 ///
789 /// \param ExternModuleLoc The location of the "extern module" declaration
790 /// that caused us to load this module map file, if any.
791 ///
792 /// \returns true if an error occurred, false otherwise.
793 bool
795 bool ImplicitlyDiscovered,
796 DirectoryEntryRef HomeDir, FileID ID = FileID(),
797 unsigned *Offset = nullptr,
798 SourceLocation ExternModuleLoc = SourceLocation());
799
800 /// Get the ModuleMapFile for a FileEntry previously parsed with
801 /// parseModuleMapFile.
803 auto It = ParsedModuleMap.find(File);
804 if (It == ParsedModuleMap.end())
805 return nullptr;
806 return It->second;
807 }
808
809 /// Dump the contents of the module map, for debugging purposes.
810 void dump();
811
812 using module_iterator = llvm::StringMap<Module *>::const_iterator;
813
814 module_iterator module_begin() const { return Modules.begin(); }
815 module_iterator module_end() const { return Modules.end(); }
816 llvm::iterator_range<module_iterator> modules() const {
817 return {module_begin(), module_end()};
818 }
819
820 /// Cache a module load. M might be nullptr.
822 CachedModuleLoads[&II] = M;
823 }
824
825 /// Return a cached module load.
826 std::optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
827 auto I = CachedModuleLoads.find(&II);
828 if (I == CachedModuleLoads.end())
829 return std::nullopt;
830 return I->second;
831 }
832};
833
834} // namespace clang
835
836#endif // LLVM_CLANG_LEX_MODULEMAP_H
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines the clang::LangOptions interface.
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::SourceLocation class and associated facilities.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
Cached information about one directory (either on disk or in the virtual file system).
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:273
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:57
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
One of these records is kept for each identifier that is lexed.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A mechanism to observe the actions of the module map loader as it reads module map files.
Definition ModuleMap.h:49
virtual void moduleMapFileRead(SourceLocation FileStart, FileEntryRef File, bool IsSystem)
Called when a module map file has been read.
Definition ModuleMap.h:61
virtual ~ModuleMapCallbacks()=default
virtual void moduleMapAddHeader(StringRef Filename)
Called when a header is added during module map parsing.
Definition ModuleMap.h:67
virtual void moduleMapAddUmbrellaHeader(FileEntryRef Header)
Called when an umbrella header is added during module map parsing.
Definition ModuleMap.h:72
KnownHeader(Module *M, ModuleHeaderRole Role)
Definition ModuleMap.h:160
bool isAccessibleFrom(Module *M) const
Whether this header is accessible from the specified module.
Definition ModuleMap.h:181
ModuleHeaderRole getRole() const
The role of this header within the module.
Definition ModuleMap.h:173
friend bool operator!=(const KnownHeader &A, const KnownHeader &B)
Definition ModuleMap.h:165
friend bool operator==(const KnownHeader &A, const KnownHeader &B)
Definition ModuleMap.h:162
Module * getModule() const
Retrieve the module the header is stored in.
Definition ModuleMap.h:170
bool isAvailable() const
Whether this header is available in the module.
Definition ModuleMap.h:176
Module * createShadowedModule(StringRef Name, bool IsFramework, Module *ShadowingModule)
Create a new top-level module that is shadowed by ShadowingModule.
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition ModuleMap.cpp:64
friend class ModuleMapLoader
Definition ModuleMap.h:196
bool parseModuleMapFile(FileEntryRef File, bool IsSystem, bool ImplicitlyDiscovered, DirectoryEntryRef Dir, FileID ID=FileID(), SourceLocation ExternModuleLoc=SourceLocation())
Parse a module map without creating clang::Module instances.
void dump()
Dump the contents of the module map, for debugging purposes.
std::pair< Module *, bool > findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Find a new module or submodule, or create it if it does not already exist.
llvm::StringMap< Module * >::const_iterator module_iterator
Definition ModuleMap.h:812
void diagnoseHeaderInclusion(Module *RequestingModule, bool RequestingModuleIsModuleInterface, SourceLocation FilenameLoc, StringRef Filename, FileEntryRef File)
Reports errors if a module must not include a specific file.
void addAdditionalModuleMapFile(const Module *M, FileEntryRef ModuleMap)
ModuleRef lookupModuleQualified(StringRef Name, Module *Context) const
Retrieve a module with the given name within the given context, using direct (qualified) name lookup.
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role)
Convert a header role to a kind.
Definition ModuleMap.cpp:71
Module * findModule(StringRef Name) const
Retrieve an already loaded module with the given name.
void finishModuleDeclarationScope()
Creates a new declaration scope for module names, allowing previously defined modules to shadow defin...
Definition ModuleMap.h:646
bool canInferFrameworkModule(const DirectoryEntry *Dir) const
Check whether a framework module can be inferred in the given directory.
Definition ModuleMap.h:655
bool mayShadowNewModule(Module *ExistingModule)
Definition ModuleMap.h:648
KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual=false, bool AllowExcluded=false)
Retrieve the module that owns the given header file, if any.
Module * createHeaderUnit(SourceLocation Loc, StringRef Name, Module::Header H)
Create a C++20 header unit.
bool isModuleKnown(StringRef Name) const
Determine if a top-level module named Name was loaded or parsed.
Definition ModuleMap.h:527
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella header of the given module to the given header.
void addModuleMapCallbacks(std::unique_ptr< ModuleMapCallbacks > Callback)
Add a module map callback.
Definition ModuleMap.h:431
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false, SourceLocation Loc=SourceLocation())
Adds this header to the given module.
void setBuiltinIncludeDir(DirectoryEntryRef Dir)
Set the directory that contains Clang-supplied include files, such as our stdarg.h or tgmath....
Definition ModuleMap.h:419
void recordDirectoryDependencies(Module *Mod, StringRef Dir)
Record that Mod depends on the listing of Dir. Dir is a VFS path.
OptionalFileEntryRef getModuleMapFileForName(StringRef Name) const
Find the module map that defines the top-level module Name, without loading it.
static bool isModular(ModuleHeaderRole Role)
Check if the header with the given role is a modular one.
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
bool isHeaderUnavailableInModule(FileEntryRef Header, const Module *RequestingModule) const
Determine whether the given header is unavailable as part of the specified module.
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
module_iterator module_begin() const
Definition ModuleMap.h:814
ArrayRef< KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
bool shouldImportRelativeToBuiltinIncludeDir(StringRef FileName, Module *Module) const
bool parseAndLoadModuleMapFile(FileEntryRef File, bool IsSystem, bool ImplicitlyDiscovered, DirectoryEntryRef HomeDir, FileID ID=FileID(), unsigned *Offset=nullptr, SourceLocation ExternModuleLoc=SourceLocation())
Load the given module map file, and record any modules we encounter.
Module * createModuleForImplementationUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module implementation unit.
ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target, HeaderSearch &HeaderInfo)
Construct a new module map.
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition ModuleMap.h:826
std::error_code canonicalizeModuleMapPath(SmallVectorImpl< char > &Path)
Canonicalize Path in a manner suitable for a module map file.
OptionalFileEntryRef findUmbrellaHeaderForModule(Module *M, std::string NameAsWritten, SmallVectorImpl< char > &RelativePathName)
Find the FileEntry for an umbrella header in a module as if it was written in the module map as a hea...
FileID getModuleMapFileIDForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella directory of the given module to the given directory.
llvm::DenseSet< FileEntryRef > AdditionalModMapsSet
Definition ModuleMap.h:193
Module * findOrCreateModuleFirst(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Call ModuleMap::findOrCreateModule and throw away the information whether the module was found or cre...
Definition ModuleMap.h:580
Module * lookupModuleUnqualified(StringRef Name, Module *Context) const
Retrieve a module with the given name using lexical name lookup, starting at the given context.
bool isBuiltinHeader(FileEntryRef File)
Is this a compiler builtin header?
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
static void canonicalizeDirectoryDependency(const FileManager &FileMgr, SmallVectorImpl< char > &Path)
Spell Path the way directory dependencies are recorded: absolute, with dots removed.
module_iterator module_end() const
Definition ModuleMap.h:815
AdditionalModMapsSet * getAdditionalModuleMapFiles(const Module *M)
Get any module map files other than getModuleMapFileForUniquing(M) that define submodules of a top-le...
Definition ModuleMap.h:697
const modulemap::ModuleMapFile * getParsedModuleMap(FileEntryRef File) const
Get the ModuleMapFile for a FileEntry previously parsed with parseModuleMapFile.
Definition ModuleMap.h:802
bool isHeaderInUnavailableModule(FileEntryRef Header) const
Determine whether the given header is part of a module marked 'unavailable'.
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
OptionalDirectoryEntryRef getBuiltinDir() const
Get the directory that contains Clang-supplied include files.
Definition ModuleMap.h:422
~ModuleMap()
Destroy the module map.
Module * createGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent=nullptr)
Create a global module fragment for a C++ module unit.
void setTarget(const TargetInfo &Target)
Set the target information.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition ModuleMap.cpp:53
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
Definition ModuleMap.h:821
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:123
@ PrivateHeader
This header is included but private.
Definition ModuleMap.h:128
@ ExcludedHeader
This header is explicitly excluded from the module.
Definition ModuleMap.h:135
@ NormalHeader
This header is normally included in the module.
Definition ModuleMap.h:125
@ TextualHeader
This header is part of the module (for layering purposes) but should be textually included.
Definition ModuleMap.h:132
Module * createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module interface unit.
Module * createPrivateModuleFragmentForInterfaceUnit(Module *Parent, SourceLocation Loc)
Create a global module fragment for a C++ module interface unit.
Module * findOrInferSubmodule(Module *Parent, StringRef Name)
ArrayRef< KnownHeader > findAllModulesForHeader(FileEntryRef File)
Retrieve all the modules that contain the given header file.
Module * createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent)
void loadAllParsedModules()
Module * createModuleUnitWithKind(SourceLocation Loc, StringRef Name, Module::ModuleKind Kind)
Create a new C++ module with the specified kind, and reparent any pending global module fragment(s) t...
Module * findOrLoadModule(StringRef Name)
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind)
Convert a header kind to a role. Requires Kind to not be HK_Excluded.
Definition ModuleMap.cpp:88
llvm::iterator_range< module_iterator > modules() const
Definition ModuleMap.h:816
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Reference to a module that consists of either an existing/materialized Module object,...
Definition Module.h:275
Describes a module or submodule.
Definition Module.h:340
std::pair< ModuleRef, bool > ExportDecl
Describes an exported module.
Definition Module.h:671
Module * Parent
The parent of this module.
Definition Module.h:389
bool isAvailable() const
Determine whether this module is available for use within the current translation unit.
Definition Module.h:789
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Exposes information about the current target.
Definition TargetInfo.h:228
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
SmallVector< std::pair< std::string, SourceLocation >, 2 > ModuleId
Describes the name of a module.
Definition Module.h:63
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
CustomizableOptional< DirectoryEntryRef > OptionalDirectoryEntryRef
#define false
Definition stdbool.h:26
The set of attributes that can be attached to a module.
Definition Module.h:249
Information about a header directive as found in the module map file.
Definition Module.h:490
Represents the parsed form of a module map file.