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