1 //===- HeaderSearch.h - Resolve Header File Locations -----------*- 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 HeaderSearch interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
14 #define LLVM_CLANG_LEX_HEADERSEARCH_H
15 
16 #include "clang/Basic/SourceLocation.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/DirectoryLookup.h"
19 #include "clang/Lex/HeaderMap.h"
20 #include "clang/Lex/ModuleMap.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/Support/Allocator.h"
28 #include <cassert>
29 #include <cstddef>
30 #include <memory>
31 #include <string>
32 #include <utility>
33 #include <vector>
34 
35 namespace llvm {
36 
37 class Triple;
38 
39 } // namespace llvm
40 
41 namespace clang {
42 
43 class DiagnosticsEngine;
44 class DirectoryEntry;
45 class ExternalPreprocessorSource;
46 class FileEntry;
47 class FileManager;
48 class HeaderSearch;
49 class HeaderSearchOptions;
50 class IdentifierInfo;
51 class LangOptions;
52 class Module;
53 class Preprocessor;
54 class TargetInfo;
55 
56 /// The preprocessor keeps track of this information for each
57 /// file that is \#included.
58 struct HeaderFileInfo {
59   // TODO: Whether the file was imported is not a property of the file itself.
60   // It's a preprocessor state, move it there.
61   /// True if this is a \#import'd file.
62   unsigned isImport : 1;
63 
64   /// True if this is a \#pragma once file.
65   unsigned isPragmaOnce : 1;
66 
67   /// Keep track of whether this is a system header, and if so,
68   /// whether it is C++ clean or not.  This can be set by the include paths or
69   /// by \#pragma gcc system_header.  This is an instance of
70   /// SrcMgr::CharacteristicKind.
71   unsigned DirInfo : 3;
72 
73   /// Whether this header file info was supplied by an external source,
74   /// and has not changed since.
75   unsigned External : 1;
76 
77   /// Whether this header is part of a module.
78   unsigned isModuleHeader : 1;
79 
80   /// Whether this header is part of the module that we are building.
81   unsigned isCompilingModuleHeader : 1;
82 
83   /// Whether this structure is considered to already have been
84   /// "resolved", meaning that it was loaded from the external source.
85   unsigned Resolved : 1;
86 
87   /// Whether this is a header inside a framework that is currently
88   /// being built.
89   ///
90   /// When a framework is being built, the headers have not yet been placed
91   /// into the appropriate framework subdirectories, and therefore are
92   /// provided via a header map. This bit indicates when this is one of
93   /// those framework headers.
94   unsigned IndexHeaderMapHeader : 1;
95 
96   /// Whether this file has been looked up as a header.
97   unsigned IsValid : 1;
98 
99   /// The ID number of the controlling macro.
100   ///
101   /// This ID number will be non-zero when there is a controlling
102   /// macro whose IdentifierInfo may not yet have been loaded from
103   /// external storage.
104   unsigned ControllingMacroID = 0;
105 
106   /// If this file has a \#ifndef XXX (or equivalent) guard that
107   /// protects the entire contents of the file, this is the identifier
108   /// for the macro that controls whether or not it has any effect.
109   ///
110   /// Note: Most clients should use getControllingMacro() to access
111   /// the controlling macro of this header, since
112   /// getControllingMacro() is able to load a controlling macro from
113   /// external storage.
114   const IdentifierInfo *ControllingMacro = nullptr;
115 
116   /// If this header came from a framework include, this is the name
117   /// of the framework.
118   StringRef Framework;
119 
120   HeaderFileInfo()
121       : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
122         External(false), isModuleHeader(false), isCompilingModuleHeader(false),
123         Resolved(false), IndexHeaderMapHeader(false), IsValid(false)  {}
124 
125   /// Retrieve the controlling macro for this header file, if
126   /// any.
127   const IdentifierInfo *
128   getControllingMacro(ExternalPreprocessorSource *External);
129 };
130 
131 /// An external source of header file information, which may supply
132 /// information about header files already included.
133 class ExternalHeaderFileInfoSource {
134 public:
135   virtual ~ExternalHeaderFileInfoSource();
136 
137   /// Retrieve the header file information for the given file entry.
138   ///
139   /// \returns Header file information for the given file entry, with the
140   /// \c External bit set. If the file entry is not known, return a
141   /// default-constructed \c HeaderFileInfo.
142   virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
143 };
144 
145 /// This structure is used to record entries in our framework cache.
146 struct FrameworkCacheEntry {
147   /// The directory entry which should be used for the cached framework.
148   OptionalDirectoryEntryRef Directory;
149 
150   /// Whether this framework has been "user-specified" to be treated as if it
151   /// were a system framework (even if it was found outside a system framework
152   /// directory).
153   bool IsUserSpecifiedSystemFramework;
154 };
155 
156 namespace detail {
157 template <bool Const, typename T>
158 using Qualified = std::conditional_t<Const, const T, T>;
159 
160 /// Forward iterator over the search directories of \c HeaderSearch.
161 template <bool IsConst>
162 struct SearchDirIteratorImpl
163     : llvm::iterator_facade_base<SearchDirIteratorImpl<IsConst>,
164                                  std::forward_iterator_tag,
165                                  Qualified<IsConst, DirectoryLookup>> {
166   /// Const -> non-const iterator conversion.
167   template <typename Enable = std::enable_if<IsConst, bool>>
168   SearchDirIteratorImpl(const SearchDirIteratorImpl<false> &Other)
169       : HS(Other.HS), Idx(Other.Idx) {}
170 
171   SearchDirIteratorImpl(const SearchDirIteratorImpl &) = default;
172 
173   SearchDirIteratorImpl &operator=(const SearchDirIteratorImpl &) = default;
174 
175   bool operator==(const SearchDirIteratorImpl &RHS) const {
176     return HS == RHS.HS && Idx == RHS.Idx;
177   }
178 
179   SearchDirIteratorImpl &operator++() {
180     assert(*this && "Invalid iterator.");
181     ++Idx;
182     return *this;
183   }
184 
185   Qualified<IsConst, DirectoryLookup> &operator*() const {
186     assert(*this && "Invalid iterator.");
187     return HS->SearchDirs[Idx];
188   }
189 
190   /// Creates an invalid iterator.
191   SearchDirIteratorImpl(std::nullptr_t) : HS(nullptr), Idx(0) {}
192 
193   /// Checks whether the iterator is valid.
194   explicit operator bool() const { return HS != nullptr; }
195 
196 private:
197   /// The parent \c HeaderSearch. This is \c nullptr for invalid iterator.
198   Qualified<IsConst, HeaderSearch> *HS;
199 
200   /// The index of the current element.
201   size_t Idx;
202 
203   /// The constructor that creates a valid iterator.
204   SearchDirIteratorImpl(Qualified<IsConst, HeaderSearch> &HS, size_t Idx)
205       : HS(&HS), Idx(Idx) {}
206 
207   /// Only HeaderSearch is allowed to instantiate valid iterators.
208   friend HeaderSearch;
209 
210   /// Enables const -> non-const conversion.
211   friend SearchDirIteratorImpl<!IsConst>;
212 };
213 } // namespace detail
214 
215 using ConstSearchDirIterator = detail::SearchDirIteratorImpl<true>;
216 using SearchDirIterator = detail::SearchDirIteratorImpl<false>;
217 
218 using ConstSearchDirRange = llvm::iterator_range<ConstSearchDirIterator>;
219 using SearchDirRange = llvm::iterator_range<SearchDirIterator>;
220 
221 /// Encapsulates the information needed to find the file referenced
222 /// by a \#include or \#include_next, (sub-)framework lookup, etc.
223 class HeaderSearch {
224   friend class DirectoryLookup;
225 
226   friend ConstSearchDirIterator;
227   friend SearchDirIterator;
228 
229   /// Header-search options used to initialize this header search.
230   std::shared_ptr<HeaderSearchOptions> HSOpts;
231 
232   /// Mapping from SearchDir to HeaderSearchOptions::UserEntries indices.
233   llvm::DenseMap<unsigned, unsigned> SearchDirToHSEntry;
234 
235   DiagnosticsEngine &Diags;
236   FileManager &FileMgr;
237 
238   /// \#include search path information.  Requests for \#include "x" search the
239   /// directory of the \#including file first, then each directory in SearchDirs
240   /// consecutively. Requests for <x> search the current dir first, then each
241   /// directory in SearchDirs, starting at AngledDirIdx, consecutively.  If
242   /// NoCurDirSearch is true, then the check for the file in the current
243   /// directory is suppressed.
244   std::vector<DirectoryLookup> SearchDirs;
245   /// Whether the DirectoryLookup at the corresponding index in SearchDirs has
246   /// been successfully used to lookup a file.
247   std::vector<bool> SearchDirsUsage;
248   unsigned AngledDirIdx = 0;
249   unsigned SystemDirIdx = 0;
250   bool NoCurDirSearch = false;
251 
252   /// Maps HeaderMap keys to SearchDir indices. When HeaderMaps are used
253   /// heavily, SearchDirs can start with thousands of HeaderMaps, so this Index
254   /// lets us avoid scanning them all to find a match.
255   llvm::StringMap<unsigned, llvm::BumpPtrAllocator> SearchDirHeaderMapIndex;
256 
257   /// The index of the first SearchDir that isn't a header map.
258   unsigned FirstNonHeaderMapSearchDirIdx = 0;
259 
260   /// \#include prefixes for which the 'system header' property is
261   /// overridden.
262   ///
263   /// For a \#include "x" or \#include \<x> directive, the last string in this
264   /// list which is a prefix of 'x' determines whether the file is treated as
265   /// a system header.
266   std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes;
267 
268   /// The hash used for module cache paths.
269   std::string ModuleHash;
270 
271   /// The path to the module cache.
272   std::string ModuleCachePath;
273 
274   /// All of the preprocessor-specific data about files that are
275   /// included, indexed by the FileEntry's UID.
276   mutable std::vector<HeaderFileInfo> FileInfo;
277 
278   /// Keeps track of each lookup performed by LookupFile.
279   struct LookupFileCacheInfo {
280     /// Starting search directory iterator that the cached search was performed
281     /// from. If there is a hit and this value doesn't match the current query,
282     /// the cache has to be ignored.
283     ConstSearchDirIterator StartIt = nullptr;
284 
285     /// The search directory iterator that satisfied the query.
286     ConstSearchDirIterator HitIt = nullptr;
287 
288     /// This is non-null if the original filename was mapped to a framework
289     /// include via a headermap.
290     const char *MappedName = nullptr;
291 
292     /// Default constructor -- Initialize all members with zero.
293     LookupFileCacheInfo() = default;
294 
295     void reset(ConstSearchDirIterator NewStartIt) {
296       StartIt = NewStartIt;
297       MappedName = nullptr;
298     }
299   };
300   llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
301 
302   /// Collection mapping a framework or subframework
303   /// name like "Carbon" to the Carbon.framework directory.
304   llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
305 
306   /// Maps include file names (including the quotes or
307   /// angle brackets) to other include file names.  This is used to support the
308   /// include_alias pragma for Microsoft compatibility.
309   using IncludeAliasMap =
310       llvm::StringMap<std::string, llvm::BumpPtrAllocator>;
311   std::unique_ptr<IncludeAliasMap> IncludeAliases;
312 
313   /// This is a mapping from FileEntry -> HeaderMap, uniquing headermaps.
314   std::vector<std::pair<const FileEntry *, std::unique_ptr<HeaderMap>>> HeaderMaps;
315 
316   /// The mapping between modules and headers.
317   mutable ModuleMap ModMap;
318 
319   /// Describes whether a given directory has a module map in it.
320   llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
321 
322   /// Set of module map files we've already loaded, and a flag indicating
323   /// whether they were valid or not.
324   llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps;
325 
326   // A map of discovered headers with their associated include file name.
327   llvm::DenseMap<const FileEntry *, llvm::SmallString<64>> IncludeNames;
328 
329   /// Uniqued set of framework names, which is used to track which
330   /// headers were included as framework headers.
331   llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
332 
333   /// Entity used to resolve the identifier IDs of controlling
334   /// macros into IdentifierInfo pointers, and keep the identifire up to date,
335   /// as needed.
336   ExternalPreprocessorSource *ExternalLookup = nullptr;
337 
338   /// Entity used to look up stored header file information.
339   ExternalHeaderFileInfoSource *ExternalSource = nullptr;
340 
341   /// Scan all of the header maps at the beginning of SearchDirs and
342   /// map their keys to the SearchDir index of their header map.
343   void indexInitialHeaderMaps();
344 
345 public:
346   HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
347                SourceManager &SourceMgr, DiagnosticsEngine &Diags,
348                const LangOptions &LangOpts, const TargetInfo *Target);
349   HeaderSearch(const HeaderSearch &) = delete;
350   HeaderSearch &operator=(const HeaderSearch &) = delete;
351 
352   /// Retrieve the header-search options with which this header search
353   /// was initialized.
354   HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
355 
356   FileManager &getFileMgr() const { return FileMgr; }
357 
358   DiagnosticsEngine &getDiags() const { return Diags; }
359 
360   /// Interface for setting the file search paths.
361   void SetSearchPaths(std::vector<DirectoryLookup> dirs, unsigned angledDirIdx,
362                       unsigned systemDirIdx, bool noCurDirSearch,
363                       llvm::DenseMap<unsigned, unsigned> searchDirToHSEntry);
364 
365   /// Add an additional search path.
366   void AddSearchPath(const DirectoryLookup &dir, bool isAngled);
367 
368   /// Add an additional system search path.
369   void AddSystemSearchPath(const DirectoryLookup &dir) {
370     SearchDirs.push_back(dir);
371     SearchDirsUsage.push_back(false);
372   }
373 
374   /// Set the list of system header prefixes.
375   void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) {
376     SystemHeaderPrefixes.assign(P.begin(), P.end());
377   }
378 
379   /// Checks whether the map exists or not.
380   bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
381 
382   /// Map the source include name to the dest include name.
383   ///
384   /// The Source should include the angle brackets or quotes, the dest
385   /// should not.  This allows for distinction between <> and "" headers.
386   void AddIncludeAlias(StringRef Source, StringRef Dest) {
387     if (!IncludeAliases)
388       IncludeAliases.reset(new IncludeAliasMap);
389     (*IncludeAliases)[Source] = std::string(Dest);
390   }
391 
392   /// Maps one header file name to a different header
393   /// file name, for use with the include_alias pragma.  Note that the source
394   /// file name should include the angle brackets or quotes.  Returns StringRef
395   /// as null if the header cannot be mapped.
396   StringRef MapHeaderToIncludeAlias(StringRef Source) {
397     assert(IncludeAliases && "Trying to map headers when there's no map");
398 
399     // Do any filename replacements before anything else
400     IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
401     if (Iter != IncludeAliases->end())
402       return Iter->second;
403     return {};
404   }
405 
406   /// Set the hash to use for module cache paths.
407   void setModuleHash(StringRef Hash) { ModuleHash = std::string(Hash); }
408 
409   /// Set the path to the module cache.
410   void setModuleCachePath(StringRef CachePath) {
411     ModuleCachePath = std::string(CachePath);
412   }
413 
414   /// Retrieve the module hash.
415   StringRef getModuleHash() const { return ModuleHash; }
416 
417   /// Retrieve the path to the module cache.
418   StringRef getModuleCachePath() const { return ModuleCachePath; }
419 
420   /// Consider modules when including files from this directory.
421   void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
422     DirectoryHasModuleMap[Dir] = true;
423   }
424 
425   /// Forget everything we know about headers so far.
426   void ClearFileInfo() {
427     FileInfo.clear();
428   }
429 
430   void SetExternalLookup(ExternalPreprocessorSource *EPS) {
431     ExternalLookup = EPS;
432   }
433 
434   ExternalPreprocessorSource *getExternalLookup() const {
435     return ExternalLookup;
436   }
437 
438   /// Set the external source of header information.
439   void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
440     ExternalSource = ES;
441   }
442 
443   /// Set the target information for the header search, if not
444   /// already known.
445   void setTarget(const TargetInfo &Target);
446 
447   /// Given a "foo" or \<foo> reference, look up the indicated file,
448   /// return null on failure.
449   ///
450   /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
451   /// the file was found in, or null if not applicable.
452   ///
453   /// \param IncludeLoc Used for diagnostics if valid.
454   ///
455   /// \param isAngled indicates whether the file reference is a <> reference.
456   ///
457   /// \param CurDir If non-null, the file was found in the specified directory
458   /// search location.  This is used to implement \#include_next.
459   ///
460   /// \param Includers Indicates where the \#including file(s) are, in case
461   /// relative searches are needed. In reverse order of inclusion.
462   ///
463   /// \param SearchPath If non-null, will be set to the search path relative
464   /// to which the file was found. If the include path is absolute, SearchPath
465   /// will be set to an empty string.
466   ///
467   /// \param RelativePath If non-null, will be set to the path relative to
468   /// SearchPath at which the file was found. This only differs from the
469   /// Filename for framework includes.
470   ///
471   /// \param SuggestedModule If non-null, and the file found is semantically
472   /// part of a known module, this will be set to the module that should
473   /// be imported instead of preprocessing/parsing the file found.
474   ///
475   /// \param IsMapped If non-null, and the search involved header maps, set to
476   /// true.
477   ///
478   /// \param IsFrameworkFound If non-null, will be set to true if a framework is
479   /// found in any of searched SearchDirs. Will be set to false if a framework
480   /// is found only through header maps. Doesn't guarantee the requested file is
481   /// found.
482   OptionalFileEntryRef LookupFile(
483       StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
484       ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDir,
485       ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
486       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
487       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
488       bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
489       bool BuildSystemModule = false, bool OpenFile = true,
490       bool CacheFailures = true);
491 
492   /// Look up a subframework for the specified \#include file.
493   ///
494   /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
495   /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
496   /// HIToolbox is a subframework within Carbon.framework.  If so, return
497   /// the FileEntry for the designated file, otherwise return null.
498   OptionalFileEntryRef LookupSubframeworkHeader(
499       StringRef Filename, const FileEntry *ContextFileEnt,
500       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
501       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule);
502 
503   /// Look up the specified framework name in our framework cache.
504   /// \returns The DirectoryEntry it is in if we know, null otherwise.
505   FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
506     return FrameworkMap[FWName];
507   }
508 
509   /// Mark the specified file as a target of a \#include,
510   /// \#include_next, or \#import directive.
511   ///
512   /// \return false if \#including the file will have no effect or true
513   /// if we should include it.
514   bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File,
515                               bool isImport, bool ModulesEnabled, Module *M,
516                               bool &IsFirstIncludeOfFile);
517 
518   /// Return whether the specified file is a normal header,
519   /// a system header, or a C++ friendly system header.
520   SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
521     return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
522   }
523 
524   /// Mark the specified file as a "once only" file due to
525   /// \#pragma once.
526   void MarkFileIncludeOnce(const FileEntry *File) {
527     HeaderFileInfo &FI = getFileInfo(File);
528     FI.isPragmaOnce = true;
529   }
530 
531   /// Mark the specified file as a system header, e.g. due to
532   /// \#pragma GCC system_header.
533   void MarkFileSystemHeader(const FileEntry *File) {
534     getFileInfo(File).DirInfo = SrcMgr::C_System;
535   }
536 
537   /// Mark the specified file as part of a module.
538   void MarkFileModuleHeader(const FileEntry *FE,
539                             ModuleMap::ModuleHeaderRole Role,
540                             bool isCompilingModuleHeader);
541 
542   /// Mark the specified file as having a controlling macro.
543   ///
544   /// This is used by the multiple-include optimization to eliminate
545   /// no-op \#includes.
546   void SetFileControllingMacro(const FileEntry *File,
547                                const IdentifierInfo *ControllingMacro) {
548     getFileInfo(File).ControllingMacro = ControllingMacro;
549   }
550 
551   /// Determine whether this file is intended to be safe from
552   /// multiple inclusions, e.g., it has \#pragma once or a controlling
553   /// macro.
554   ///
555   /// This routine does not consider the effect of \#import
556   bool isFileMultipleIncludeGuarded(const FileEntry *File);
557 
558   /// Determine whether the given file is known to have ever been \#imported.
559   bool hasFileBeenImported(const FileEntry *File) {
560     const HeaderFileInfo *FI = getExistingFileInfo(File);
561     return FI && FI->isImport;
562   }
563 
564   /// Determine which HeaderSearchOptions::UserEntries have been successfully
565   /// used so far and mark their index with 'true' in the resulting bit vector.
566   /// Note: implicit module maps don't contribute to entry usage.
567   std::vector<bool> computeUserEntryUsage() const;
568 
569   /// This method returns a HeaderMap for the specified
570   /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
571   const HeaderMap *CreateHeaderMap(const FileEntry *FE);
572 
573   /// Get filenames for all registered header maps.
574   void getHeaderMapFileNames(SmallVectorImpl<std::string> &Names) const;
575 
576   /// Retrieve the name of the cached module file that should be used
577   /// to load the given module.
578   ///
579   /// \param Module The module whose module file name will be returned.
580   ///
581   /// \returns The name of the module file that corresponds to this module,
582   /// or an empty string if this module does not correspond to any module file.
583   std::string getCachedModuleFileName(Module *Module);
584 
585   /// Retrieve the name of the prebuilt module file that should be used
586   /// to load a module with the given name.
587   ///
588   /// \param ModuleName The module whose module file name will be returned.
589   ///
590   /// \param FileMapOnly If true, then only look in the explicit module name
591   //  to file name map and skip the directory search.
592   ///
593   /// \returns The name of the module file that corresponds to this module,
594   /// or an empty string if this module does not correspond to any module file.
595   std::string getPrebuiltModuleFileName(StringRef ModuleName,
596                                         bool FileMapOnly = false);
597 
598   /// Retrieve the name of the prebuilt module file that should be used
599   /// to load the given module.
600   ///
601   /// \param Module The module whose module file name will be returned.
602   ///
603   /// \returns The name of the module file that corresponds to this module,
604   /// or an empty string if this module does not correspond to any module file.
605   std::string getPrebuiltImplicitModuleFileName(Module *Module);
606 
607   /// Retrieve the name of the (to-be-)cached module file that should
608   /// be used to load a module with the given name.
609   ///
610   /// \param ModuleName The module whose module file name will be returned.
611   ///
612   /// \param ModuleMapPath A path that when combined with \c ModuleName
613   /// uniquely identifies this module. See Module::ModuleMap.
614   ///
615   /// \returns The name of the module file that corresponds to this module,
616   /// or an empty string if this module does not correspond to any module file.
617   std::string getCachedModuleFileName(StringRef ModuleName,
618                                       StringRef ModuleMapPath);
619 
620   /// Lookup a module Search for a module with the given name.
621   ///
622   /// \param ModuleName The name of the module we're looking for.
623   ///
624   /// \param ImportLoc Location of the module include/import.
625   ///
626   /// \param AllowSearch Whether we are allowed to search in the various
627   /// search directories to produce a module definition. If not, this lookup
628   /// will only return an already-known module.
629   ///
630   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
631   /// in subdirectories.
632   ///
633   /// \returns The module with the given name.
634   Module *lookupModule(StringRef ModuleName,
635                        SourceLocation ImportLoc = SourceLocation(),
636                        bool AllowSearch = true,
637                        bool AllowExtraModuleMapSearch = false);
638 
639   /// Try to find a module map file in the given directory, returning
640   /// \c nullptr if none is found.
641   const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir,
642                                        bool IsFramework);
643 
644   /// Determine whether there is a module map that may map the header
645   /// with the given file name to a (sub)module.
646   /// Always returns false if modules are disabled.
647   ///
648   /// \param Filename The name of the file.
649   ///
650   /// \param Root The "root" directory, at which we should stop looking for
651   /// module maps.
652   ///
653   /// \param IsSystem Whether the directories we're looking at are system
654   /// header directories.
655   bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root,
656                     bool IsSystem);
657 
658   /// Retrieve the module that corresponds to the given file, if any.
659   ///
660   /// \param File The header that we wish to map to a module.
661   /// \param AllowTextual Whether we want to find textual headers too.
662   ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File,
663                                              bool AllowTextual = false,
664                                              bool AllowExcluded = false) const;
665 
666   /// Retrieve all the modules corresponding to the given file.
667   ///
668   /// \ref findModuleForHeader should typically be used instead of this.
669   ArrayRef<ModuleMap::KnownHeader>
670   findAllModulesForHeader(const FileEntry *File) const;
671 
672   /// Read the contents of the given module map file.
673   ///
674   /// \param File The module map file.
675   /// \param IsSystem Whether this file is in a system header directory.
676   /// \param ID If the module map file is already mapped (perhaps as part of
677   ///        processing a preprocessed module), the ID of the file.
678   /// \param Offset [inout] An offset within ID to start parsing. On exit,
679   ///        filled by the end of the parsed contents (either EOF or the
680   ///        location of an end-of-module-map pragma).
681   /// \param OriginalModuleMapFile The original path to the module map file,
682   ///        used to resolve paths within the module (this is required when
683   ///        building the module from preprocessed source).
684   /// \returns true if an error occurred, false otherwise.
685   bool loadModuleMapFile(const FileEntry *File, bool IsSystem,
686                          FileID ID = FileID(), unsigned *Offset = nullptr,
687                          StringRef OriginalModuleMapFile = StringRef());
688 
689   /// Collect the set of all known, top-level modules.
690   ///
691   /// \param Modules Will be filled with the set of known, top-level modules.
692   void collectAllModules(SmallVectorImpl<Module *> &Modules);
693 
694   /// Load all known, top-level system modules.
695   void loadTopLevelSystemModules();
696 
697 private:
698   /// Lookup a module with the given module name and search-name.
699   ///
700   /// \param ModuleName The name of the module we're looking for.
701   ///
702   /// \param SearchName The "search-name" to derive filesystem paths from
703   /// when looking for the module map; this is usually equal to ModuleName,
704   /// but for compatibility with some buggy frameworks, additional attempts
705   /// may be made to find the module under a related-but-different search-name.
706   ///
707   /// \param ImportLoc Location of the module include/import.
708   ///
709   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
710   /// in subdirectories.
711   ///
712   /// \returns The module named ModuleName.
713   Module *lookupModule(StringRef ModuleName, StringRef SearchName,
714                        SourceLocation ImportLoc,
715                        bool AllowExtraModuleMapSearch = false);
716 
717   /// Retrieve the name of the (to-be-)cached module file that should
718   /// be used to load a module with the given name.
719   ///
720   /// \param ModuleName The module whose module file name will be returned.
721   ///
722   /// \param ModuleMapPath A path that when combined with \c ModuleName
723   /// uniquely identifies this module. See Module::ModuleMap.
724   ///
725   /// \param CachePath A path to the module cache.
726   ///
727   /// \returns The name of the module file that corresponds to this module,
728   /// or an empty string if this module does not correspond to any module file.
729   std::string getCachedModuleFileNameImpl(StringRef ModuleName,
730                                           StringRef ModuleMapPath,
731                                           StringRef CachePath);
732 
733   /// Retrieve a module with the given name, which may be part of the
734   /// given framework.
735   ///
736   /// \param Name The name of the module to retrieve.
737   ///
738   /// \param Dir The framework directory (e.g., ModuleName.framework).
739   ///
740   /// \param IsSystem Whether the framework directory is part of the system
741   /// frameworks.
742   ///
743   /// \returns The module, if found; otherwise, null.
744   Module *loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
745                               bool IsSystem);
746 
747   /// Load all of the module maps within the immediate subdirectories
748   /// of the given search directory.
749   void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
750 
751   /// Find and suggest a usable module for the given file.
752   ///
753   /// \return \c true if the file can be used, \c false if we are not permitted to
754   ///         find this file due to requirements from \p RequestingModule.
755   bool findUsableModuleForHeader(const FileEntry *File,
756                                  const DirectoryEntry *Root,
757                                  Module *RequestingModule,
758                                  ModuleMap::KnownHeader *SuggestedModule,
759                                  bool IsSystemHeaderDir);
760 
761   /// Find and suggest a usable module for the given file, which is part of
762   /// the specified framework.
763   ///
764   /// \return \c true if the file can be used, \c false if we are not permitted to
765   ///         find this file due to requirements from \p RequestingModule.
766   bool findUsableModuleForFrameworkHeader(
767       const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
768       ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework);
769 
770   /// Look up the file with the specified name and determine its owning
771   /// module.
772   OptionalFileEntryRef
773   getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc,
774                           const DirectoryEntry *Dir, bool IsSystemHeaderDir,
775                           Module *RequestingModule,
776                           ModuleMap::KnownHeader *SuggestedModule,
777                           bool OpenFile = true, bool CacheFailures = true);
778 
779   /// Cache the result of a successful lookup at the given include location
780   /// using the search path at \c HitIt.
781   void cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
782                           ConstSearchDirIterator HitIt,
783                           SourceLocation IncludeLoc);
784 
785   /// Note that a lookup at the given include location was successful using the
786   /// search path at index `HitIdx`.
787   void noteLookupUsage(unsigned HitIdx, SourceLocation IncludeLoc);
788 
789 public:
790   /// Retrieve the module map.
791   ModuleMap &getModuleMap() { return ModMap; }
792 
793   /// Retrieve the module map.
794   const ModuleMap &getModuleMap() const { return ModMap; }
795 
796   unsigned header_file_size() const { return FileInfo.size(); }
797 
798   /// Return the HeaderFileInfo structure for the specified FileEntry,
799   /// in preparation for updating it in some way.
800   HeaderFileInfo &getFileInfo(const FileEntry *FE);
801 
802   /// Return the HeaderFileInfo structure for the specified FileEntry,
803   /// if it has ever been filled in.
804   /// \param WantExternal Whether the caller wants purely-external header file
805   ///        info (where \p External is true).
806   const HeaderFileInfo *getExistingFileInfo(const FileEntry *FE,
807                                             bool WantExternal = true) const;
808 
809   SearchDirIterator search_dir_begin() { return {*this, 0}; }
810   SearchDirIterator search_dir_end() { return {*this, SearchDirs.size()}; }
811   SearchDirRange search_dir_range() {
812     return {search_dir_begin(), search_dir_end()};
813   }
814 
815   ConstSearchDirIterator search_dir_begin() const { return quoted_dir_begin(); }
816   ConstSearchDirIterator search_dir_nth(size_t n) const {
817     assert(n < SearchDirs.size());
818     return {*this, n};
819   }
820   ConstSearchDirIterator search_dir_end() const { return system_dir_end(); }
821   ConstSearchDirRange search_dir_range() const {
822     return {search_dir_begin(), search_dir_end()};
823   }
824 
825   unsigned search_dir_size() const { return SearchDirs.size(); }
826 
827   ConstSearchDirIterator quoted_dir_begin() const { return {*this, 0}; }
828   ConstSearchDirIterator quoted_dir_end() const { return angled_dir_begin(); }
829 
830   ConstSearchDirIterator angled_dir_begin() const {
831     return {*this, AngledDirIdx};
832   }
833   ConstSearchDirIterator angled_dir_end() const { return system_dir_begin(); }
834 
835   ConstSearchDirIterator system_dir_begin() const {
836     return {*this, SystemDirIdx};
837   }
838   ConstSearchDirIterator system_dir_end() const {
839     return {*this, SearchDirs.size()};
840   }
841 
842   /// Get the index of the given search directory.
843   unsigned searchDirIdx(const DirectoryLookup &DL) const;
844 
845   /// Retrieve a uniqued framework name.
846   StringRef getUniqueFrameworkName(StringRef Framework);
847 
848   /// Retrieve the include name for the header.
849   ///
850   /// \param File The entry for a given header.
851   /// \returns The name of how the file was included when the header's location
852   /// was resolved.
853   StringRef getIncludeNameForHeader(const FileEntry *File) const;
854 
855   /// Suggest a path by which the specified file could be found, for use in
856   /// diagnostics to suggest a #include. Returned path will only contain forward
857   /// slashes as separators. MainFile is the absolute path of the file that we
858   /// are generating the diagnostics for. It will try to shorten the path using
859   /// MainFile location, if none of the include search directories were prefix
860   /// of File.
861   ///
862   /// \param IsSystem If non-null, filled in to indicate whether the suggested
863   ///        path is relative to a system header directory.
864   std::string suggestPathToFileForDiagnostics(const FileEntry *File,
865                                               llvm::StringRef MainFile,
866                                               bool *IsSystem = nullptr);
867 
868   /// Suggest a path by which the specified file could be found, for use in
869   /// diagnostics to suggest a #include. Returned path will only contain forward
870   /// slashes as separators. MainFile is the absolute path of the file that we
871   /// are generating the diagnostics for. It will try to shorten the path using
872   /// MainFile location, if none of the include search directories were prefix
873   /// of File.
874   ///
875   /// \param WorkingDir If non-empty, this will be prepended to search directory
876   /// paths that are relative.
877   std::string suggestPathToFileForDiagnostics(llvm::StringRef File,
878                                               llvm::StringRef WorkingDir,
879                                               llvm::StringRef MainFile,
880                                               bool *IsSystem = nullptr);
881 
882   void PrintStats();
883 
884   size_t getTotalMemory() const;
885 
886 private:
887   /// Describes what happened when we tried to load a module map file.
888   enum LoadModuleMapResult {
889     /// The module map file had already been loaded.
890     LMM_AlreadyLoaded,
891 
892     /// The module map file was loaded by this invocation.
893     LMM_NewlyLoaded,
894 
895     /// There is was directory with the given name.
896     LMM_NoDirectory,
897 
898     /// There was either no module map file or the module map file was
899     /// invalid.
900     LMM_InvalidModuleMap
901   };
902 
903   LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
904                                             bool IsSystem,
905                                             DirectoryEntryRef Dir,
906                                             FileID ID = FileID(),
907                                             unsigned *Offset = nullptr);
908 
909   /// Try to load the module map file in the given directory.
910   ///
911   /// \param DirName The name of the directory where we will look for a module
912   /// map file.
913   /// \param IsSystem Whether this is a system header directory.
914   /// \param IsFramework Whether this is a framework directory.
915   ///
916   /// \returns The result of attempting to load the module map file from the
917   /// named directory.
918   LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem,
919                                         bool IsFramework);
920 
921   /// Try to load the module map file in the given directory.
922   ///
923   /// \param Dir The directory where we will look for a module map file.
924   /// \param IsSystem Whether this is a system header directory.
925   /// \param IsFramework Whether this is a framework directory.
926   ///
927   /// \returns The result of attempting to load the module map file from the
928   /// named directory.
929   LoadModuleMapResult loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
930                                         bool IsFramework);
931 };
932 
933 /// Apply the header search options to get given HeaderSearch object.
934 void ApplyHeaderSearchOptions(HeaderSearch &HS,
935                               const HeaderSearchOptions &HSOpts,
936                               const LangOptions &Lang,
937                               const llvm::Triple &triple);
938 
939 } // namespace clang
940 
941 #endif // LLVM_CLANG_LEX_HEADERSEARCH_H
942