• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #include "clang/Basic/FileEntry.h"
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/Module.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/PointerIntPair.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/StringSet.h"
30 #include "llvm/ADT/TinyPtrVector.h"
31 #include "llvm/ADT/Twine.h"
32 #include <ctime>
33 #include <memory>
34 #include <string>
35 #include <utility>
36 
37 namespace clang {
38 
39 class DiagnosticsEngine;
40 class DirectoryEntry;
41 class FileManager;
42 class HeaderSearch;
43 class SourceManager;
44 
45 /// A mechanism to observe the actions of the module map parser as it
46 /// reads module map files.
47 class ModuleMapCallbacks {
48   virtual void anchor();
49 
50 public:
51   virtual ~ModuleMapCallbacks() = default;
52 
53   /// Called when a module map file has been read.
54   ///
55   /// \param FileStart A SourceLocation referring to the start of the file's
56   /// contents.
57   /// \param File The file itself.
58   /// \param IsSystem Whether this is a module map from a system include path.
moduleMapFileRead(SourceLocation FileStart,const FileEntry & File,bool IsSystem)59   virtual void moduleMapFileRead(SourceLocation FileStart,
60                                  const FileEntry &File, bool IsSystem) {}
61 
62   /// Called when a header is added during module map parsing.
63   ///
64   /// \param Filename The header file itself.
moduleMapAddHeader(StringRef Filename)65   virtual void moduleMapAddHeader(StringRef Filename) {}
66 
67   /// Called when an umbrella header is added during module map parsing.
68   ///
69   /// \param FileMgr FileManager instance
70   /// \param Header The umbrella header to collect.
moduleMapAddUmbrellaHeader(FileManager * FileMgr,const FileEntry * Header)71   virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
72                                           const FileEntry *Header) {}
73 };
74 
75 class ModuleMap {
76   SourceManager &SourceMgr;
77   DiagnosticsEngine &Diags;
78   const LangOptions &LangOpts;
79   const TargetInfo *Target;
80   HeaderSearch &HeaderInfo;
81 
82   llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
83 
84   /// The directory used for Clang-supplied, builtin include headers,
85   /// such as "stdint.h".
86   const DirectoryEntry *BuiltinIncludeDir = nullptr;
87 
88   /// Language options used to parse the module map itself.
89   ///
90   /// These are always simple C language options.
91   LangOptions MMapLangOpts;
92 
93   /// The module that the main source file is associated with (the module
94   /// named LangOpts::CurrentModule, if we've loaded it).
95   Module *SourceModule = nullptr;
96 
97   /// Submodules of the current module that have not yet been attached to it.
98   /// (Ownership is transferred if/when we create an enclosing module.)
99   llvm::SmallVector<std::unique_ptr<Module>, 8> PendingSubmodules;
100 
101   /// The top-level modules that are known.
102   llvm::StringMap<Module *> Modules;
103 
104   /// Module loading cache that includes submodules, indexed by IdentifierInfo.
105   /// nullptr is stored for modules that are known to fail to load.
106   llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
107 
108   /// Shadow modules created while building this module map.
109   llvm::SmallVector<Module*, 2> ShadowModules;
110 
111   /// The number of modules we have created in total.
112   unsigned NumCreatedModules = 0;
113 
114   /// In case a module has a export_as entry, it might have a pending link
115   /// name to be determined if that module is imported.
116   llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
117 
118 public:
119   /// Use PendingLinkAsModule information to mark top level link names that
120   /// are going to be replaced by export_as aliases.
121   void resolveLinkAsDependencies(Module *Mod);
122 
123   /// Make module to use export_as as the link dependency name if enough
124   /// information is available or add it to a pending list otherwise.
125   void addLinkAsDependency(Module *Mod);
126 
127   /// Flags describing the role of a module header.
128   enum ModuleHeaderRole {
129     /// This header is normally included in the module.
130     NormalHeader  = 0x0,
131 
132     /// This header is included but private.
133     PrivateHeader = 0x1,
134 
135     /// This header is part of the module (for layering purposes) but
136     /// should be textually included.
137     TextualHeader = 0x2,
138 
139     // Caution: Adding an enumerator needs other changes.
140     // Adjust the number of bits for KnownHeader::Storage.
141     // Adjust the bitfield HeaderFileInfo::HeaderRole size.
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.
148   static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
149 
150   /// Convert a header role to a kind.
151   static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
152 
153   /// A header that is known to reside within a given module,
154   /// whether it was included or excluded.
155   class KnownHeader {
156     llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
157 
158   public:
KnownHeader()159     KnownHeader() : Storage(nullptr, NormalHeader) {}
KnownHeader(Module * M,ModuleHeaderRole Role)160     KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
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.
getModule()170     Module *getModule() const { return Storage.getPointer(); }
171 
172     /// The role of this header within the module.
getRole()173     ModuleHeaderRole getRole() const { return Storage.getInt(); }
174 
175     /// Whether this header is available in the module.
isAvailable()176     bool isAvailable() const {
177       return getModule()->isAvailable();
178     }
179 
180     /// Whether this header is accessible from the specified module.
isAccessibleFrom(Module * M)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::SmallPtrSet<const FileEntry *, 1>;
194 
195 private:
196   friend class ModuleMapParser;
197 
198   using HeadersMap =
199       llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>;
200 
201   /// Mapping from each header to the module that owns the contents of
202   /// that header.
203   HeadersMap Headers;
204 
205   /// Map from file sizes to modules with lazy header directives of that size.
206   mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
207 
208   /// Map from mtimes to modules with lazy header directives with those mtimes.
209   mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
210               LazyHeadersByModTime;
211 
212   /// Mapping from directories with umbrella headers to the module
213   /// that is generated from the umbrella header.
214   ///
215   /// This mapping is used to map headers that haven't explicitly been named
216   /// in the module map over to the module that includes them via its umbrella
217   /// header.
218   llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
219 
220   /// A generation counter that is used to test whether modules of the
221   /// same name may shadow or are illegal redefinitions.
222   ///
223   /// Modules from earlier scopes may shadow modules from later ones.
224   /// Modules from the same scope may not have the same name.
225   unsigned CurrentModuleScopeID = 0;
226 
227   llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
228 
229   /// The set of attributes that can be attached to a module.
230   struct Attributes {
231     /// Whether this is a system module.
232     unsigned IsSystem : 1;
233 
234     /// Whether this is an extern "C" module.
235     unsigned IsExternC : 1;
236 
237     /// Whether this is an exhaustive set of configuration macros.
238     unsigned IsExhaustive : 1;
239 
240     /// Whether files in this module can only include non-modular headers
241     /// and headers from used modules.
242     unsigned NoUndeclaredIncludes : 1;
243 
AttributesAttributes244     Attributes()
245         : IsSystem(false), IsExternC(false), IsExhaustive(false),
246           NoUndeclaredIncludes(false) {}
247   };
248 
249   /// A directory for which framework modules can be inferred.
250   struct InferredDirectory {
251     /// Whether to infer modules from this directory.
252     unsigned InferModules : 1;
253 
254     /// The attributes to use for inferred modules.
255     Attributes Attrs;
256 
257     /// If \c InferModules is non-zero, the module map file that allowed
258     /// inferred modules.  Otherwise, nullptr.
259     const FileEntry *ModuleMapFile;
260 
261     /// The names of modules that cannot be inferred within this
262     /// directory.
263     SmallVector<std::string, 2> ExcludedModules;
264 
InferredDirectoryInferredDirectory265     InferredDirectory() : InferModules(false) {}
266   };
267 
268   /// A mapping from directories to information about inferring
269   /// framework modules from within those directories.
270   llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
271 
272   /// A mapping from an inferred module to the module map that allowed the
273   /// inference.
274   llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
275 
276   llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
277 
278   /// Describes whether we haved parsed a particular file as a module
279   /// map.
280   llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
281 
282   /// Resolve the given export declaration into an actual export
283   /// declaration.
284   ///
285   /// \param Mod The module in which we're resolving the export declaration.
286   ///
287   /// \param Unresolved The export declaration to resolve.
288   ///
289   /// \param Complain Whether this routine should complain about unresolvable
290   /// exports.
291   ///
292   /// \returns The resolved export declaration, which will have a NULL pointer
293   /// if the export could not be resolved.
294   Module::ExportDecl
295   resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
296                 bool Complain) const;
297 
298   /// Resolve the given module id to an actual module.
299   ///
300   /// \param Id The module-id to resolve.
301   ///
302   /// \param Mod The module in which we're resolving the module-id.
303   ///
304   /// \param Complain Whether this routine should complain about unresolvable
305   /// module-ids.
306   ///
307   /// \returns The resolved module, or null if the module-id could not be
308   /// resolved.
309   Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
310 
311   /// Add an unresolved header to a module.
312   ///
313   /// \param Mod The module in which we're adding the unresolved header
314   ///        directive.
315   /// \param Header The unresolved header directive.
316   /// \param NeedsFramework If Mod is not a framework but a missing header would
317   ///        be found in case Mod was, set it to true. False otherwise.
318   void addUnresolvedHeader(Module *Mod,
319                            Module::UnresolvedHeaderDirective Header,
320                            bool &NeedsFramework);
321 
322   /// Look up the given header directive to find an actual header file.
323   ///
324   /// \param M The module in which we're resolving the header directive.
325   /// \param Header The header directive to resolve.
326   /// \param RelativePathName Filled in with the relative path name from the
327   ///        module to the resolved header.
328   /// \param NeedsFramework If M is not a framework but a missing header would
329   ///        be found in case M was, set it to true. False otherwise.
330   /// \return The resolved file, if any.
331   Optional<FileEntryRef>
332   findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
333              SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
334 
335   /// Resolve the given header directive.
336   ///
337   /// \param M The module in which we're resolving the header directive.
338   /// \param Header The header directive to resolve.
339   /// \param NeedsFramework If M is not a framework but a missing header would
340   ///        be found in case M was, set it to true. False otherwise.
341   void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
342                      bool &NeedsFramework);
343 
344   /// Attempt to resolve the specified header directive as naming a builtin
345   /// header.
346   /// \return \c true if a corresponding builtin header was found.
347   bool resolveAsBuiltinHeader(Module *M,
348                               const Module::UnresolvedHeaderDirective &Header);
349 
350   /// Looks up the modules that \p File corresponds to.
351   ///
352   /// If \p File represents a builtin header within Clang's builtin include
353   /// directory, this also loads all of the module maps to see if it will get
354   /// associated with a specific module (e.g. in /usr/include).
355   HeadersMap::iterator findKnownHeader(const FileEntry *File);
356 
357   /// Searches for a module whose umbrella directory contains \p File.
358   ///
359   /// \param File The header to search for.
360   ///
361   /// \param IntermediateDirs On success, contains the set of directories
362   /// searched before finding \p File.
363   KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
364                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
365 
366   /// Given that \p File is not in the Headers map, look it up within
367   /// umbrella directories and find or create a module for it.
368   KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
369 
370   /// A convenience method to determine if \p File is (possibly nested)
371   /// in an umbrella directory.
isHeaderInUmbrellaDirs(const FileEntry * File)372   bool isHeaderInUmbrellaDirs(const FileEntry *File) {
373     SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
374     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
375   }
376 
377   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
378                                Attributes Attrs, Module *Parent);
379 
380 public:
381   /// Construct a new module map.
382   ///
383   /// \param SourceMgr The source manager used to find module files and headers.
384   /// This source manager should be shared with the header-search mechanism,
385   /// since they will refer to the same headers.
386   ///
387   /// \param Diags A diagnostic engine used for diagnostics.
388   ///
389   /// \param LangOpts Language options for this translation unit.
390   ///
391   /// \param Target The target for this translation unit.
392   ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
393             const LangOptions &LangOpts, const TargetInfo *Target,
394             HeaderSearch &HeaderInfo);
395 
396   /// Destroy the module map.
397   ~ModuleMap();
398 
399   /// Set the target information.
400   void setTarget(const TargetInfo &Target);
401 
402   /// Set the directory that contains Clang-supplied include
403   /// files, such as our stdarg.h or tgmath.h.
setBuiltinIncludeDir(const DirectoryEntry * Dir)404   void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
405     BuiltinIncludeDir = Dir;
406   }
407 
408   /// Get the directory that contains Clang-supplied include files.
getBuiltinDir()409   const DirectoryEntry *getBuiltinDir() const {
410     return BuiltinIncludeDir;
411   }
412 
413   /// Is this a compiler builtin header?
414   static bool isBuiltinHeader(StringRef FileName);
415   bool isBuiltinHeader(const FileEntry *File);
416 
417   /// Add a module map callback.
addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback)418   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
419     Callbacks.push_back(std::move(Callback));
420   }
421 
422   /// Retrieve the module that owns the given header file, if any. Note that
423   /// this does not implicitly load module maps, except for builtin headers,
424   /// and does not consult the external source. (Those checks are the
425   /// responsibility of \ref HeaderSearch.)
426   ///
427   /// \param File The header file that is likely to be included.
428   ///
429   /// \param AllowTextual If \c true and \p File is a textual header, return
430   /// its owning module. Otherwise, no KnownHeader will be returned if the
431   /// file is only known as a textual header.
432   ///
433   /// \returns The module KnownHeader, which provides the module that owns the
434   /// given header file.  The KnownHeader is default constructed to indicate
435   /// that no module owns this header file.
436   KnownHeader findModuleForHeader(const FileEntry *File,
437                                   bool AllowTextual = false);
438 
439   /// Retrieve all the modules that contain the given header file. Note that
440   /// this does not implicitly load module maps, except for builtin headers,
441   /// and does not consult the external source. (Those checks are the
442   /// responsibility of \ref HeaderSearch.)
443   ///
444   /// Typically, \ref findModuleForHeader should be used instead, as it picks
445   /// the preferred module for the header.
446   ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File);
447 
448   /// Like \ref findAllModulesForHeader, but do not attempt to infer module
449   /// ownership from umbrella headers if we've not already done so.
450   ArrayRef<KnownHeader>
451   findResolvedModulesForHeader(const FileEntry *File) const;
452 
453   /// Resolve all lazy header directives for the specified file.
454   ///
455   /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
456   /// is effectively internal, but is exposed so HeaderSearch can call it.
457   void resolveHeaderDirectives(const FileEntry *File) const;
458 
459   /// Resolve all lazy header directives for the specified module.
460   void resolveHeaderDirectives(Module *Mod) const;
461 
462   /// Reports errors if a module must not include a specific file.
463   ///
464   /// \param RequestingModule The module including a file.
465   ///
466   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
467   ///        the interface of RequestingModule, \c false if it's in the
468   ///        implementation of RequestingModule. Value is ignored and
469   ///        meaningless if RequestingModule is nullptr.
470   ///
471   /// \param FilenameLoc The location of the inclusion's filename.
472   ///
473   /// \param Filename The included filename as written.
474   ///
475   /// \param File The included file.
476   void diagnoseHeaderInclusion(Module *RequestingModule,
477                                bool RequestingModuleIsModuleInterface,
478                                SourceLocation FilenameLoc, StringRef Filename,
479                                const FileEntry *File);
480 
481   /// Determine whether the given header is part of a module
482   /// marked 'unavailable'.
483   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
484 
485   /// Determine whether the given header is unavailable as part
486   /// of the specified module.
487   bool isHeaderUnavailableInModule(const FileEntry *Header,
488                                    const Module *RequestingModule) const;
489 
490   /// Retrieve a module with the given name.
491   ///
492   /// \param Name The name of the module to look up.
493   ///
494   /// \returns The named module, if known; otherwise, returns null.
495   Module *findModule(StringRef Name) const;
496 
497   /// Retrieve a module with the given name using lexical name lookup,
498   /// starting at the given context.
499   ///
500   /// \param Name The name of the module to look up.
501   ///
502   /// \param Context The module context, from which we will perform lexical
503   /// name lookup.
504   ///
505   /// \returns The named module, if known; otherwise, returns null.
506   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
507 
508   /// Retrieve a module with the given name within the given context,
509   /// using direct (qualified) name lookup.
510   ///
511   /// \param Name The name of the module to look up.
512   ///
513   /// \param Context The module for which we will look for a submodule. If
514   /// null, we will look for a top-level module.
515   ///
516   /// \returns The named submodule, if known; otherwose, returns null.
517   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
518 
519   /// Find a new module or submodule, or create it if it does not already
520   /// exist.
521   ///
522   /// \param Name The name of the module to find or create.
523   ///
524   /// \param Parent The module that will act as the parent of this submodule,
525   /// or nullptr to indicate that this is a top-level module.
526   ///
527   /// \param IsFramework Whether this is a framework module.
528   ///
529   /// \param IsExplicit Whether this is an explicit submodule.
530   ///
531   /// \returns The found or newly-created module, along with a boolean value
532   /// that will be true if the module is newly-created.
533   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
534                                                bool IsFramework,
535                                                bool IsExplicit);
536 
537   /// Create a global module fragment for a C++ module unit.
538   ///
539   /// We model the global module fragment as a submodule of the module
540   /// interface unit. Unfortunately, we can't create the module interface
541   /// unit's Module until later, because we don't know what it will be called.
542   Module *createGlobalModuleFragmentForModuleUnit(SourceLocation Loc);
543 
544   /// Create a global module fragment for a C++ module interface unit.
545   Module *createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
546                                                       SourceLocation Loc);
547 
548   /// Create a new module for a C++ module interface unit.
549   /// The module must not already exist, and will be configured for the current
550   /// compilation.
551   ///
552   /// Note that this also sets the current module to the newly-created module.
553   ///
554   /// \returns The newly-created module.
555   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name,
556                                        Module *GlobalModule);
557 
558   /// Create a header module from the specified list of headers.
559   Module *createHeaderModule(StringRef Name, ArrayRef<Module::Header> Headers);
560 
561   /// Infer the contents of a framework module map from the given
562   /// framework directory.
563   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
564                                bool IsSystem, Module *Parent);
565 
566   /// Create a new top-level module that is shadowed by
567   /// \p ShadowingModule.
568   Module *createShadowedModule(StringRef Name, bool IsFramework,
569                                Module *ShadowingModule);
570 
571   /// Creates a new declaration scope for module names, allowing
572   /// previously defined modules to shadow definitions from the new scope.
573   ///
574   /// \note Module names from earlier scopes will shadow names from the new
575   /// scope, which is the opposite of how shadowing works for variables.
finishModuleDeclarationScope()576   void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
577 
mayShadowNewModule(Module * ExistingModule)578   bool mayShadowNewModule(Module *ExistingModule) {
579     assert(!ExistingModule->Parent && "expected top-level module");
580     assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
581     return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
582   }
583 
584   /// Retrieve the module map file containing the definition of the given
585   /// module.
586   ///
587   /// \param Module The module whose module map file will be returned, if known.
588   ///
589   /// \returns The file entry for the module map file containing the given
590   /// module, or nullptr if the module definition was inferred.
591   const FileEntry *getContainingModuleMapFile(const Module *Module) const;
592 
593   /// Get the module map file that (along with the module name) uniquely
594   /// identifies this module.
595   ///
596   /// The particular module that \c Name refers to may depend on how the module
597   /// was found in header search. However, the combination of \c Name and
598   /// this module map will be globally unique for top-level modules. In the case
599   /// of inferred modules, returns the module map that allowed the inference
600   /// (e.g. contained 'module *'). Otherwise, returns
601   /// getContainingModuleMapFile().
602   const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
603 
604   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap);
605 
606   /// Get any module map files other than getModuleMapFileForUniquing(M)
607   /// that define submodules of a top-level module \p M. This is cheaper than
608   /// getting the module map file for each submodule individually, since the
609   /// expected number of results is very small.
getAdditionalModuleMapFiles(const Module * M)610   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
611     auto I = AdditionalModMaps.find(M);
612     if (I == AdditionalModMaps.end())
613       return nullptr;
614     return &I->second;
615   }
616 
617   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap);
618 
619   /// Resolve all of the unresolved exports in the given module.
620   ///
621   /// \param Mod The module whose exports should be resolved.
622   ///
623   /// \param Complain Whether to emit diagnostics for failures.
624   ///
625   /// \returns true if any errors were encountered while resolving exports,
626   /// false otherwise.
627   bool resolveExports(Module *Mod, bool Complain);
628 
629   /// Resolve all of the unresolved uses in the given module.
630   ///
631   /// \param Mod The module whose uses should be resolved.
632   ///
633   /// \param Complain Whether to emit diagnostics for failures.
634   ///
635   /// \returns true if any errors were encountered while resolving uses,
636   /// false otherwise.
637   bool resolveUses(Module *Mod, bool Complain);
638 
639   /// Resolve all of the unresolved conflicts in the given module.
640   ///
641   /// \param Mod The module whose conflicts should be resolved.
642   ///
643   /// \param Complain Whether to emit diagnostics for failures.
644   ///
645   /// \returns true if any errors were encountered while resolving conflicts,
646   /// false otherwise.
647   bool resolveConflicts(Module *Mod, bool Complain);
648 
649   /// Sets the umbrella header of the given module to the given
650   /// header.
651   void setUmbrellaHeader(Module *Mod, FileEntryRef UmbrellaHeader,
652                          Twine NameAsWritten);
653 
654   /// Sets the umbrella directory of the given module to the given
655   /// directory.
656   void setUmbrellaDir(Module *Mod, DirectoryEntryRef UmbrellaDir,
657                       Twine NameAsWritten);
658 
659   /// Adds this header to the given module.
660   /// \param Role The role of the header wrt the module.
661   void addHeader(Module *Mod, Module::Header Header,
662                  ModuleHeaderRole Role, bool Imported = false);
663 
664   /// Marks this header as being excluded from the given module.
665   void excludeHeader(Module *Mod, Module::Header Header);
666 
667   /// Parse the given module map file, and record any modules we
668   /// encounter.
669   ///
670   /// \param File The file to be parsed.
671   ///
672   /// \param IsSystem Whether this module map file is in a system header
673   /// directory, and therefore should be considered a system module.
674   ///
675   /// \param HomeDir The directory in which relative paths within this module
676   ///        map file will be resolved.
677   ///
678   /// \param ID The FileID of the file to process, if we've already entered it.
679   ///
680   /// \param Offset [inout] On input the offset at which to start parsing. On
681   ///        output, the offset at which the module map terminated.
682   ///
683   /// \param ExternModuleLoc The location of the "extern module" declaration
684   ///        that caused us to load this module map file, if any.
685   ///
686   /// \returns true if an error occurred, false otherwise.
687   bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
688                           const DirectoryEntry *HomeDir,
689                           FileID ID = FileID(), unsigned *Offset = nullptr,
690                           SourceLocation ExternModuleLoc = SourceLocation());
691 
692   /// Dump the contents of the module map, for debugging purposes.
693   void dump();
694 
695   using module_iterator = llvm::StringMap<Module *>::const_iterator;
696 
module_begin()697   module_iterator module_begin() const { return Modules.begin(); }
module_end()698   module_iterator module_end()   const { return Modules.end(); }
699 
700   /// Cache a module load.  M might be nullptr.
cacheModuleLoad(const IdentifierInfo & II,Module * M)701   void cacheModuleLoad(const IdentifierInfo &II, Module *M) {
702     CachedModuleLoads[&II] = M;
703   }
704 
705   /// Return a cached module load.
getCachedModuleLoad(const IdentifierInfo & II)706   llvm::Optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
707     auto I = CachedModuleLoads.find(&II);
708     if (I == CachedModuleLoads.end())
709       return None;
710     return I->second;
711   }
712 };
713 
714 } // namespace clang
715 
716 #endif // LLVM_CLANG_LEX_MODULEMAP_H
717