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/IdentifierTable.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/Module.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/TinyPtrVector.h"
30 #include "llvm/ADT/Twine.h"
31 #include <ctime>
32 #include <memory>
33 #include <string>
34 #include <utility>
35 
36 namespace clang {
37 
38 class DiagnosticsEngine;
39 class DirectoryEntry;
40 class FileEntry;
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.
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.
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.
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:
159     KnownHeader() : Storage(nullptr, NormalHeader) {}
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.
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 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::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 
244     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 
265     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   const FileEntry *findHeader(Module *M,
332                               const Module::UnresolvedHeaderDirective &Header,
333                               SmallVectorImpl<char> &RelativePathName,
334                               bool &NeedsFramework);
335 
336   /// Resolve the given header directive.
337   ///
338   /// \param M The module in which we're resolving the header directive.
339   /// \param Header The header directive to resolve.
340   /// \param NeedsFramework If M is not a framework but a missing header would
341   ///        be found in case M was, set it to true. False otherwise.
342   void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
343                      bool &NeedsFramework);
344 
345   /// Attempt to resolve the specified header directive as naming a builtin
346   /// header.
347   /// \return \c true if a corresponding builtin header was found.
348   bool resolveAsBuiltinHeader(Module *M,
349                               const Module::UnresolvedHeaderDirective &Header);
350 
351   /// Looks up the modules that \p File corresponds to.
352   ///
353   /// If \p File represents a builtin header within Clang's builtin include
354   /// directory, this also loads all of the module maps to see if it will get
355   /// associated with a specific module (e.g. in /usr/include).
356   HeadersMap::iterator findKnownHeader(const FileEntry *File);
357 
358   /// Searches for a module whose umbrella directory contains \p File.
359   ///
360   /// \param File The header to search for.
361   ///
362   /// \param IntermediateDirs On success, contains the set of directories
363   /// searched before finding \p File.
364   KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
365                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
366 
367   /// Given that \p File is not in the Headers map, look it up within
368   /// umbrella directories and find or create a module for it.
369   KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
370 
371   /// A convenience method to determine if \p File is (possibly nested)
372   /// in an umbrella directory.
373   bool isHeaderInUmbrellaDirs(const FileEntry *File) {
374     SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
375     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
376   }
377 
378   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
379                                Attributes Attrs, Module *Parent);
380 
381 public:
382   /// Construct a new module map.
383   ///
384   /// \param SourceMgr The source manager used to find module files and headers.
385   /// This source manager should be shared with the header-search mechanism,
386   /// since they will refer to the same headers.
387   ///
388   /// \param Diags A diagnostic engine used for diagnostics.
389   ///
390   /// \param LangOpts Language options for this translation unit.
391   ///
392   /// \param Target The target for this translation unit.
393   ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
394             const LangOptions &LangOpts, const TargetInfo *Target,
395             HeaderSearch &HeaderInfo);
396 
397   /// Destroy the module map.
398   ~ModuleMap();
399 
400   /// Set the target information.
401   void setTarget(const TargetInfo &Target);
402 
403   /// Set the directory that contains Clang-supplied include
404   /// files, such as our stdarg.h or tgmath.h.
405   void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
406     BuiltinIncludeDir = Dir;
407   }
408 
409   /// Get the directory that contains Clang-supplied include files.
410   const DirectoryEntry *getBuiltinDir() const {
411     return BuiltinIncludeDir;
412   }
413 
414   /// Is this a compiler builtin header?
415   static bool isBuiltinHeader(StringRef FileName);
416 
417   /// Add a module map 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.
423   ///
424   /// \param File The header file that is likely to be included.
425   ///
426   /// \param AllowTextual If \c true and \p File is a textual header, return
427   /// its owning module. Otherwise, no KnownHeader will be returned if the
428   /// file is only known as a textual header.
429   ///
430   /// \returns The module KnownHeader, which provides the module that owns the
431   /// given header file.  The KnownHeader is default constructed to indicate
432   /// that no module owns this header file.
433   KnownHeader findModuleForHeader(const FileEntry *File,
434                                   bool AllowTextual = false);
435 
436   /// Retrieve all the modules that contain the given header file. This
437   /// may not include umbrella modules, nor information from external sources,
438   /// if they have not yet been inferred / loaded.
439   ///
440   /// Typically, \ref findModuleForHeader should be used instead, as it picks
441   /// the preferred module for the header.
442   ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
443 
444   /// Resolve all lazy header directives for the specified file.
445   ///
446   /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
447   /// is effectively internal, but is exposed so HeaderSearch can call it.
448   void resolveHeaderDirectives(const FileEntry *File) const;
449 
450   /// Resolve all lazy header directives for the specified module.
451   void resolveHeaderDirectives(Module *Mod) const;
452 
453   /// Reports errors if a module must not include a specific file.
454   ///
455   /// \param RequestingModule The module including a file.
456   ///
457   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
458   ///        the interface of RequestingModule, \c false if it's in the
459   ///        implementation of RequestingModule. Value is ignored and
460   ///        meaningless if RequestingModule is nullptr.
461   ///
462   /// \param FilenameLoc The location of the inclusion's filename.
463   ///
464   /// \param Filename The included filename as written.
465   ///
466   /// \param File The included file.
467   void diagnoseHeaderInclusion(Module *RequestingModule,
468                                bool RequestingModuleIsModuleInterface,
469                                SourceLocation FilenameLoc, StringRef Filename,
470                                const FileEntry *File);
471 
472   /// Determine whether the given header is part of a module
473   /// marked 'unavailable'.
474   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
475 
476   /// Determine whether the given header is unavailable as part
477   /// of the specified module.
478   bool isHeaderUnavailableInModule(const FileEntry *Header,
479                                    const Module *RequestingModule) const;
480 
481   /// Retrieve a module with the given name.
482   ///
483   /// \param Name The name of the module to look up.
484   ///
485   /// \returns The named module, if known; otherwise, returns null.
486   Module *findModule(StringRef Name) const;
487 
488   /// Retrieve a module with the given name using lexical name lookup,
489   /// starting at the given context.
490   ///
491   /// \param Name The name of the module to look up.
492   ///
493   /// \param Context The module context, from which we will perform lexical
494   /// name lookup.
495   ///
496   /// \returns The named module, if known; otherwise, returns null.
497   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
498 
499   /// Retrieve a module with the given name within the given context,
500   /// using direct (qualified) name lookup.
501   ///
502   /// \param Name The name of the module to look up.
503   ///
504   /// \param Context The module for which we will look for a submodule. If
505   /// null, we will look for a top-level module.
506   ///
507   /// \returns The named submodule, if known; otherwose, returns null.
508   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
509 
510   /// Find a new module or submodule, or create it if it does not already
511   /// exist.
512   ///
513   /// \param Name The name of the module to find or create.
514   ///
515   /// \param Parent The module that will act as the parent of this submodule,
516   /// or nullptr to indicate that this is a top-level module.
517   ///
518   /// \param IsFramework Whether this is a framework module.
519   ///
520   /// \param IsExplicit Whether this is an explicit submodule.
521   ///
522   /// \returns The found or newly-created module, along with a boolean value
523   /// that will be true if the module is newly-created.
524   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
525                                                bool IsFramework,
526                                                bool IsExplicit);
527 
528   /// Create a global module fragment for a C++ module unit.
529   ///
530   /// We model the global module fragment as a submodule of the module
531   /// interface unit. Unfortunately, we can't create the module interface
532   /// unit's Module until later, because we don't know what it will be called.
533   Module *createGlobalModuleFragmentForModuleUnit(SourceLocation Loc);
534 
535   /// Create a global module fragment for a C++ module interface unit.
536   Module *createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
537                                                       SourceLocation Loc);
538 
539   /// Create a new module for a C++ module interface unit.
540   /// The module must not already exist, and will be configured for the current
541   /// compilation.
542   ///
543   /// Note that this also sets the current module to the newly-created module.
544   ///
545   /// \returns The newly-created module.
546   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name,
547                                        Module *GlobalModule);
548 
549   /// Create a header module from the specified list of headers.
550   Module *createHeaderModule(StringRef Name, ArrayRef<Module::Header> Headers);
551 
552   /// Infer the contents of a framework module map from the given
553   /// framework directory.
554   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
555                                bool IsSystem, Module *Parent);
556 
557   /// Create a new top-level module that is shadowed by
558   /// \p ShadowingModule.
559   Module *createShadowedModule(StringRef Name, bool IsFramework,
560                                Module *ShadowingModule);
561 
562   /// Creates a new declaration scope for module names, allowing
563   /// previously defined modules to shadow definitions from the new scope.
564   ///
565   /// \note Module names from earlier scopes will shadow names from the new
566   /// scope, which is the opposite of how shadowing works for variables.
567   void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
568 
569   bool mayShadowNewModule(Module *ExistingModule) {
570     assert(!ExistingModule->Parent && "expected top-level module");
571     assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
572     return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
573   }
574 
575   /// Retrieve the module map file containing the definition of the given
576   /// module.
577   ///
578   /// \param Module The module whose module map file will be returned, if known.
579   ///
580   /// \returns The file entry for the module map file containing the given
581   /// module, or nullptr if the module definition was inferred.
582   const FileEntry *getContainingModuleMapFile(const Module *Module) const;
583 
584   /// Get the module map file that (along with the module name) uniquely
585   /// identifies this module.
586   ///
587   /// The particular module that \c Name refers to may depend on how the module
588   /// was found in header search. However, the combination of \c Name and
589   /// this module map will be globally unique for top-level modules. In the case
590   /// of inferred modules, returns the module map that allowed the inference
591   /// (e.g. contained 'module *'). Otherwise, returns
592   /// getContainingModuleMapFile().
593   const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
594 
595   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap);
596 
597   /// Get any module map files other than getModuleMapFileForUniquing(M)
598   /// that define submodules of a top-level module \p M. This is cheaper than
599   /// getting the module map file for each submodule individually, since the
600   /// expected number of results is very small.
601   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
602     auto I = AdditionalModMaps.find(M);
603     if (I == AdditionalModMaps.end())
604       return nullptr;
605     return &I->second;
606   }
607 
608   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
609     AdditionalModMaps[M].insert(ModuleMap);
610   }
611 
612   /// Resolve all of the unresolved exports in the given module.
613   ///
614   /// \param Mod The module whose exports should be resolved.
615   ///
616   /// \param Complain Whether to emit diagnostics for failures.
617   ///
618   /// \returns true if any errors were encountered while resolving exports,
619   /// false otherwise.
620   bool resolveExports(Module *Mod, bool Complain);
621 
622   /// Resolve all of the unresolved uses in the given module.
623   ///
624   /// \param Mod The module whose uses should be resolved.
625   ///
626   /// \param Complain Whether to emit diagnostics for failures.
627   ///
628   /// \returns true if any errors were encountered while resolving uses,
629   /// false otherwise.
630   bool resolveUses(Module *Mod, bool Complain);
631 
632   /// Resolve all of the unresolved conflicts in the given module.
633   ///
634   /// \param Mod The module whose conflicts should be resolved.
635   ///
636   /// \param Complain Whether to emit diagnostics for failures.
637   ///
638   /// \returns true if any errors were encountered while resolving conflicts,
639   /// false otherwise.
640   bool resolveConflicts(Module *Mod, bool Complain);
641 
642   /// Sets the umbrella header of the given module to the given
643   /// header.
644   void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
645                          Twine NameAsWritten);
646 
647   /// Sets the umbrella directory of the given module to the given
648   /// directory.
649   void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
650                       Twine NameAsWritten);
651 
652   /// Adds this header to the given module.
653   /// \param Role The role of the header wrt the module.
654   void addHeader(Module *Mod, Module::Header Header,
655                  ModuleHeaderRole Role, bool Imported = false);
656 
657   /// Marks this header as being excluded from the given module.
658   void excludeHeader(Module *Mod, Module::Header Header);
659 
660   /// Parse the given module map file, and record any modules we
661   /// encounter.
662   ///
663   /// \param File The file to be parsed.
664   ///
665   /// \param IsSystem Whether this module map file is in a system header
666   /// directory, and therefore should be considered a system module.
667   ///
668   /// \param HomeDir The directory in which relative paths within this module
669   ///        map file will be resolved.
670   ///
671   /// \param ID The FileID of the file to process, if we've already entered it.
672   ///
673   /// \param Offset [inout] On input the offset at which to start parsing. On
674   ///        output, the offset at which the module map terminated.
675   ///
676   /// \param ExternModuleLoc The location of the "extern module" declaration
677   ///        that caused us to load this module map file, if any.
678   ///
679   /// \returns true if an error occurred, false otherwise.
680   bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
681                           const DirectoryEntry *HomeDir,
682                           FileID ID = FileID(), unsigned *Offset = nullptr,
683                           SourceLocation ExternModuleLoc = SourceLocation());
684 
685   /// Dump the contents of the module map, for debugging purposes.
686   void dump();
687 
688   using module_iterator = llvm::StringMap<Module *>::const_iterator;
689 
690   module_iterator module_begin() const { return Modules.begin(); }
691   module_iterator module_end()   const { return Modules.end(); }
692 
693   /// Cache a module load.  M might be nullptr.
694   void cacheModuleLoad(const IdentifierInfo &II, Module *M) {
695     CachedModuleLoads[&II] = M;
696   }
697 
698   /// Return a cached module load.
699   llvm::Optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
700     auto I = CachedModuleLoads.find(&II);
701     if (I == CachedModuleLoads.end())
702       return None;
703     return I->second;
704   }
705 };
706 
707 } // namespace clang
708 
709 #endif // LLVM_CLANG_LEX_MODULEMAP_H
710