xref: /llvm-project/clang/lib/Lex/HeaderSearch.cpp (revision 84df7a09f8da5809b85fd097015e5ac6cc8a3f88)
1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
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 implements the DirectoryLookup and HeaderSearch interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Lex/HeaderSearch.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/Module.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/DirectoryLookup.h"
20 #include "clang/Lex/ExternalPreprocessorSource.h"
21 #include "clang/Lex/HeaderMap.h"
22 #include "clang/Lex/HeaderSearchOptions.h"
23 #include "clang/Lex/LexDiagnostic.h"
24 #include "clang/Lex/ModuleMap.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/Hashing.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/Capacity.h"
35 #include "llvm/Support/Errc.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/VirtualFileSystem.h"
40 #include <algorithm>
41 #include <cassert>
42 #include <cstddef>
43 #include <cstdio>
44 #include <cstring>
45 #include <string>
46 #include <system_error>
47 #include <utility>
48 
49 using namespace clang;
50 
51 #define DEBUG_TYPE "file-search"
52 
53 ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");
54 ALWAYS_ENABLED_STATISTIC(
55     NumMultiIncludeFileOptzn,
56     "Number of #includes skipped due to the multi-include optimization.");
57 ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");
58 ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,
59                          "Number of subframework lookups.");
60 
61 const IdentifierInfo *
62 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
63   if (ControllingMacro) {
64     if (ControllingMacro->isOutOfDate()) {
65       assert(External && "We must have an external source if we have a "
66                          "controlling macro that is out of date.");
67       External->updateOutOfDateIdentifier(*ControllingMacro);
68     }
69     return ControllingMacro;
70   }
71 
72   if (!ControllingMacroID || !External)
73     return nullptr;
74 
75   ControllingMacro = External->GetIdentifier(ControllingMacroID);
76   return ControllingMacro;
77 }
78 
79 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
80 
81 HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
82                            SourceManager &SourceMgr, DiagnosticsEngine &Diags,
83                            const LangOptions &LangOpts,
84                            const TargetInfo *Target)
85     : HSOpts(std::move(HSOpts)), Diags(Diags),
86       FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
87       ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
88 
89 void HeaderSearch::PrintStats() {
90   llvm::errs() << "\n*** HeaderSearch Stats:\n"
91                << FileInfo.size() << " files tracked.\n";
92   unsigned NumOnceOnlyFiles = 0;
93   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i)
94     NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport);
95   llvm::errs() << "  " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
96 
97   llvm::errs() << "  " << NumIncluded << " #include/#include_next/#import.\n"
98                << "    " << NumMultiIncludeFileOptzn
99                << " #includes skipped due to the multi-include optimization.\n";
100 
101   llvm::errs() << NumFrameworkLookups << " framework lookups.\n"
102                << NumSubFrameworkLookups << " subframework lookups.\n";
103 }
104 
105 void HeaderSearch::SetSearchPaths(
106     std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx,
107     unsigned int systemDirIdx,
108     llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) {
109   assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
110          "Directory indices are unordered");
111   SearchDirs = std::move(dirs);
112   SearchDirsUsage.assign(SearchDirs.size(), false);
113   AngledDirIdx = angledDirIdx;
114   SystemDirIdx = systemDirIdx;
115   SearchDirToHSEntry = std::move(searchDirToHSEntry);
116   //LookupFileCache.clear();
117   indexInitialHeaderMaps();
118 }
119 
120 void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
121   unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
122   SearchDirs.insert(SearchDirs.begin() + idx, dir);
123   SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false);
124   if (!isAngled)
125     AngledDirIdx++;
126   SystemDirIdx++;
127 }
128 
129 std::vector<bool> HeaderSearch::computeUserEntryUsage() const {
130   std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());
131   for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {
132     // Check whether this DirectoryLookup has been successfully used.
133     if (SearchDirsUsage[I]) {
134       auto UserEntryIdxIt = SearchDirToHSEntry.find(I);
135       // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
136       if (UserEntryIdxIt != SearchDirToHSEntry.end())
137         UserEntryUsage[UserEntryIdxIt->second] = true;
138     }
139   }
140   return UserEntryUsage;
141 }
142 
143 std::vector<bool> HeaderSearch::collectVFSUsageAndClear() const {
144   std::vector<bool> VFSUsage;
145   if (!getHeaderSearchOpts().ModulesIncludeVFSUsage)
146     return VFSUsage;
147 
148   llvm::vfs::FileSystem &RootFS = FileMgr.getVirtualFileSystem();
149   // TODO: This only works if the `RedirectingFileSystem`s were all created by
150   //       `createVFSFromOverlayFiles`.
151   RootFS.visit([&](llvm::vfs::FileSystem &FS) {
152     if (auto *RFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&FS)) {
153       VFSUsage.push_back(RFS->hasBeenUsed());
154       RFS->clearHasBeenUsed();
155     }
156   });
157   assert(VFSUsage.size() == getHeaderSearchOpts().VFSOverlayFiles.size() &&
158          "A different number of RedirectingFileSystem's were present than "
159          "-ivfsoverlay options passed to Clang!");
160   // VFS visit order is the opposite of VFSOverlayFiles order.
161   std::reverse(VFSUsage.begin(), VFSUsage.end());
162   return VFSUsage;
163 }
164 
165 /// CreateHeaderMap - This method returns a HeaderMap for the specified
166 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
167 const HeaderMap *HeaderSearch::CreateHeaderMap(FileEntryRef FE) {
168   // We expect the number of headermaps to be small, and almost always empty.
169   // If it ever grows, use of a linear search should be re-evaluated.
170   if (!HeaderMaps.empty()) {
171     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
172       // Pointer equality comparison of FileEntries works because they are
173       // already uniqued by inode.
174       if (HeaderMaps[i].first == FE)
175         return HeaderMaps[i].second.get();
176   }
177 
178   if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
179     HeaderMaps.emplace_back(FE, std::move(HM));
180     return HeaderMaps.back().second.get();
181   }
182 
183   return nullptr;
184 }
185 
186 /// Get filenames for all registered header maps.
187 void HeaderSearch::getHeaderMapFileNames(
188     SmallVectorImpl<std::string> &Names) const {
189   for (auto &HM : HeaderMaps)
190     Names.push_back(std::string(HM.first.getName()));
191 }
192 
193 std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
194   OptionalFileEntryRef ModuleMap =
195       getModuleMap().getModuleMapFileForUniquing(Module);
196   // The ModuleMap maybe a nullptr, when we load a cached C++ module without
197   // *.modulemap file. In this case, just return an empty string.
198   if (!ModuleMap)
199     return {};
200   return getCachedModuleFileName(Module->Name, ModuleMap->getNameAsRequested());
201 }
202 
203 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
204                                                     bool FileMapOnly) {
205   // First check the module name to pcm file map.
206   auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
207   if (i != HSOpts->PrebuiltModuleFiles.end())
208     return i->second;
209 
210   if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
211     return {};
212 
213   // Then go through each prebuilt module directory and try to find the pcm
214   // file.
215   for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
216     SmallString<256> Result(Dir);
217     llvm::sys::fs::make_absolute(Result);
218     if (ModuleName.contains(':'))
219       // The separator of C++20 modules partitions (':') is not good for file
220       // systems, here clang and gcc choose '-' by default since it is not a
221       // valid character of C++ indentifiers. So we could avoid conflicts.
222       llvm::sys::path::append(Result, ModuleName.split(':').first + "-" +
223                                           ModuleName.split(':').second +
224                                           ".pcm");
225     else
226       llvm::sys::path::append(Result, ModuleName + ".pcm");
227     if (getFileMgr().getFile(Result.str()))
228       return std::string(Result);
229   }
230 
231   return {};
232 }
233 
234 std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) {
235   OptionalFileEntryRef ModuleMap =
236       getModuleMap().getModuleMapFileForUniquing(Module);
237   StringRef ModuleName = Module->Name;
238   StringRef ModuleMapPath = ModuleMap->getName();
239   StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();
240   for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
241     SmallString<256> CachePath(Dir);
242     llvm::sys::fs::make_absolute(CachePath);
243     llvm::sys::path::append(CachePath, ModuleCacheHash);
244     std::string FileName =
245         getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);
246     if (!FileName.empty() && getFileMgr().getFile(FileName))
247       return FileName;
248   }
249   return {};
250 }
251 
252 std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
253                                                   StringRef ModuleMapPath) {
254   return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,
255                                      getModuleCachePath());
256 }
257 
258 std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,
259                                                       StringRef ModuleMapPath,
260                                                       StringRef CachePath) {
261   // If we don't have a module cache path or aren't supposed to use one, we
262   // can't do anything.
263   if (CachePath.empty())
264     return {};
265 
266   SmallString<256> Result(CachePath);
267   llvm::sys::fs::make_absolute(Result);
268 
269   if (HSOpts->DisableModuleHash) {
270     llvm::sys::path::append(Result, ModuleName + ".pcm");
271   } else {
272     // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
273     // ideally be globally unique to this particular module. Name collisions
274     // in the hash are safe (because any translation unit can only import one
275     // module with each name), but result in a loss of caching.
276     //
277     // To avoid false-negatives, we form as canonical a path as we can, and map
278     // to lower-case in case we're on a case-insensitive file system.
279     SmallString<128> CanonicalPath(ModuleMapPath);
280     if (getModuleMap().canonicalizeModuleMapPath(CanonicalPath))
281       return {};
282 
283     llvm::hash_code Hash = llvm::hash_combine(CanonicalPath.str().lower());
284 
285     SmallString<128> HashStr;
286     llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
287     llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
288   }
289   return Result.str().str();
290 }
291 
292 Module *HeaderSearch::lookupModule(StringRef ModuleName,
293                                    SourceLocation ImportLoc, bool AllowSearch,
294                                    bool AllowExtraModuleMapSearch) {
295   // Look in the module map to determine if there is a module by this name.
296   Module *Module = ModMap.findModule(ModuleName);
297   if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
298     return Module;
299 
300   StringRef SearchName = ModuleName;
301   Module = lookupModule(ModuleName, SearchName, ImportLoc,
302                         AllowExtraModuleMapSearch);
303 
304   // The facility for "private modules" -- adjacent, optional module maps named
305   // module.private.modulemap that are supposed to define private submodules --
306   // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
307   //
308   // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
309   // should also rename to Foo_Private. Representing private as submodules
310   // could force building unwanted dependencies into the parent module and cause
311   // dependency cycles.
312   if (!Module && SearchName.consume_back("_Private"))
313     Module = lookupModule(ModuleName, SearchName, ImportLoc,
314                           AllowExtraModuleMapSearch);
315   if (!Module && SearchName.consume_back("Private"))
316     Module = lookupModule(ModuleName, SearchName, ImportLoc,
317                           AllowExtraModuleMapSearch);
318   return Module;
319 }
320 
321 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
322                                    SourceLocation ImportLoc,
323                                    bool AllowExtraModuleMapSearch) {
324   Module *Module = nullptr;
325 
326   // Look through the various header search paths to load any available module
327   // maps, searching for a module map that describes this module.
328   for (DirectoryLookup &Dir : search_dir_range()) {
329     if (Dir.isFramework()) {
330       // Search for or infer a module map for a framework. Here we use
331       // SearchName rather than ModuleName, to permit finding private modules
332       // named FooPrivate in buggy frameworks named Foo.
333       SmallString<128> FrameworkDirName;
334       FrameworkDirName += Dir.getFrameworkDirRef()->getName();
335       llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
336       if (auto FrameworkDir =
337               FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {
338         bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;
339         Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
340         if (Module)
341           break;
342       }
343     }
344 
345     // FIXME: Figure out how header maps and module maps will work together.
346 
347     // Only deal with normal search directories.
348     if (!Dir.isNormalDir())
349       continue;
350 
351     bool IsSystem = Dir.isSystemHeaderDirectory();
352     // Only returns std::nullopt if not a normal directory, which we just
353     // checked
354     DirectoryEntryRef NormalDir = *Dir.getDirRef();
355     // Search for a module map file in this directory.
356     if (loadModuleMapFile(NormalDir, IsSystem,
357                           /*IsFramework*/false) == LMM_NewlyLoaded) {
358       // We just loaded a module map file; check whether the module is
359       // available now.
360       Module = ModMap.findModule(ModuleName);
361       if (Module)
362         break;
363     }
364 
365     // Search for a module map in a subdirectory with the same name as the
366     // module.
367     SmallString<128> NestedModuleMapDirName;
368     NestedModuleMapDirName = Dir.getDirRef()->getName();
369     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
370     if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
371                           /*IsFramework*/false) == LMM_NewlyLoaded){
372       // If we just loaded a module map file, look for the module again.
373       Module = ModMap.findModule(ModuleName);
374       if (Module)
375         break;
376     }
377 
378     // If we've already performed the exhaustive search for module maps in this
379     // search directory, don't do it again.
380     if (Dir.haveSearchedAllModuleMaps())
381       continue;
382 
383     // Load all module maps in the immediate subdirectories of this search
384     // directory if ModuleName was from @import.
385     if (AllowExtraModuleMapSearch)
386       loadSubdirectoryModuleMaps(Dir);
387 
388     // Look again for the module.
389     Module = ModMap.findModule(ModuleName);
390     if (Module)
391       break;
392   }
393 
394   return Module;
395 }
396 
397 void HeaderSearch::indexInitialHeaderMaps() {
398   llvm::StringMap<unsigned, llvm::BumpPtrAllocator> Index(SearchDirs.size());
399 
400   // Iterate over all filename keys and associate them with the index i.
401   for (unsigned i = 0; i != SearchDirs.size(); ++i) {
402     auto &Dir = SearchDirs[i];
403 
404     // We're concerned with only the initial contiguous run of header
405     // maps within SearchDirs, which can be 99% of SearchDirs when
406     // SearchDirs.size() is ~10000.
407     if (!Dir.isHeaderMap()) {
408       SearchDirHeaderMapIndex = std::move(Index);
409       FirstNonHeaderMapSearchDirIdx = i;
410       break;
411     }
412 
413     // Give earlier keys precedence over identical later keys.
414     auto Callback = [&](StringRef Filename) {
415       Index.try_emplace(Filename.lower(), i);
416     };
417     Dir.getHeaderMap()->forEachKey(Callback);
418   }
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // File lookup within a DirectoryLookup scope
423 //===----------------------------------------------------------------------===//
424 
425 /// getName - Return the directory or filename corresponding to this lookup
426 /// object.
427 StringRef DirectoryLookup::getName() const {
428   if (isNormalDir())
429     return getDirRef()->getName();
430   if (isFramework())
431     return getFrameworkDirRef()->getName();
432   assert(isHeaderMap() && "Unknown DirectoryLookup");
433   return getHeaderMap()->getFileName();
434 }
435 
436 OptionalFileEntryRef HeaderSearch::getFileAndSuggestModule(
437     StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
438     bool IsSystemHeaderDir, Module *RequestingModule,
439     ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/,
440     bool CacheFailures /*=true*/) {
441   // If we have a module map that might map this header, load it and
442   // check whether we'll have a suggestion for a module.
443   auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures);
444   if (!File) {
445     // For rare, surprising errors (e.g. "out of file handles"), diag the EC
446     // message.
447     std::error_code EC = llvm::errorToErrorCode(File.takeError());
448     if (EC != llvm::errc::no_such_file_or_directory &&
449         EC != llvm::errc::invalid_argument &&
450         EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
451       Diags.Report(IncludeLoc, diag::err_cannot_open_file)
452           << FileName << EC.message();
453     }
454     return std::nullopt;
455   }
456 
457   // If there is a module that corresponds to this header, suggest it.
458   if (!findUsableModuleForHeader(
459           *File, Dir ? Dir : File->getFileEntry().getDir(), RequestingModule,
460           SuggestedModule, IsSystemHeaderDir))
461     return std::nullopt;
462 
463   return *File;
464 }
465 
466 /// LookupFile - Lookup the specified file in this search path, returning it
467 /// if it exists or returning null if not.
468 OptionalFileEntryRef DirectoryLookup::LookupFile(
469     StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
470     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
471     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
472     bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
473     bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName,
474     bool OpenFile) const {
475   InUserSpecifiedSystemFramework = false;
476   IsInHeaderMap = false;
477   MappedName.clear();
478 
479   SmallString<1024> TmpDir;
480   if (isNormalDir()) {
481     // Concatenate the requested file onto the directory.
482     TmpDir = getDirRef()->getName();
483     llvm::sys::path::append(TmpDir, Filename);
484     if (SearchPath) {
485       StringRef SearchPathRef(getDirRef()->getName());
486       SearchPath->clear();
487       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
488     }
489     if (RelativePath) {
490       RelativePath->clear();
491       RelativePath->append(Filename.begin(), Filename.end());
492     }
493 
494     return HS.getFileAndSuggestModule(
495         TmpDir, IncludeLoc, getDir(), isSystemHeaderDirectory(),
496         RequestingModule, SuggestedModule, OpenFile);
497   }
498 
499   if (isFramework())
500     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
501                              RequestingModule, SuggestedModule,
502                              InUserSpecifiedSystemFramework, IsFrameworkFound);
503 
504   assert(isHeaderMap() && "Unknown directory lookup");
505   const HeaderMap *HM = getHeaderMap();
506   SmallString<1024> Path;
507   StringRef Dest = HM->lookupFilename(Filename, Path);
508   if (Dest.empty())
509     return std::nullopt;
510 
511   IsInHeaderMap = true;
512 
513   auto FixupSearchPathAndFindUsableModule =
514       [&](FileEntryRef File) -> OptionalFileEntryRef {
515     if (SearchPath) {
516       StringRef SearchPathRef(getName());
517       SearchPath->clear();
518       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
519     }
520     if (RelativePath) {
521       RelativePath->clear();
522       RelativePath->append(Filename.begin(), Filename.end());
523     }
524     if (!HS.findUsableModuleForHeader(File, File.getFileEntry().getDir(),
525                                       RequestingModule, SuggestedModule,
526                                       isSystemHeaderDirectory())) {
527       return std::nullopt;
528     }
529     return File;
530   };
531 
532   // Check if the headermap maps the filename to a framework include
533   // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
534   // framework include.
535   if (llvm::sys::path::is_relative(Dest)) {
536     MappedName.append(Dest.begin(), Dest.end());
537     Filename = StringRef(MappedName.begin(), MappedName.size());
538     Dest = HM->lookupFilename(Filename, Path);
539   }
540 
541   if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest, OpenFile)) {
542     return FixupSearchPathAndFindUsableModule(*Res);
543   }
544 
545   // Header maps need to be marked as used whenever the filename matches.
546   // The case where the target file **exists** is handled by callee of this
547   // function as part of the regular logic that applies to include search paths.
548   // The case where the target file **does not exist** is handled here:
549   HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc);
550   return std::nullopt;
551 }
552 
553 /// Given a framework directory, find the top-most framework directory.
554 ///
555 /// \param FileMgr The file manager to use for directory lookups.
556 /// \param DirName The name of the framework directory.
557 /// \param SubmodulePath Will be populated with the submodule path from the
558 /// returned top-level module to the originally named framework.
559 static OptionalDirectoryEntryRef
560 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
561                    SmallVectorImpl<std::string> &SubmodulePath) {
562   assert(llvm::sys::path::extension(DirName) == ".framework" &&
563          "Not a framework directory");
564 
565   // Note: as an egregious but useful hack we use the real path here, because
566   // frameworks moving between top-level frameworks to embedded frameworks tend
567   // to be symlinked, and we base the logical structure of modules on the
568   // physical layout. In particular, we need to deal with crazy includes like
569   //
570   //   #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
571   //
572   // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
573   // which one should access with, e.g.,
574   //
575   //   #include <Bar/Wibble.h>
576   //
577   // Similar issues occur when a top-level framework has moved into an
578   // embedded framework.
579   auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);
580 
581   if (TopFrameworkDir)
582     DirName = FileMgr.getCanonicalName(*TopFrameworkDir);
583   do {
584     // Get the parent directory name.
585     DirName = llvm::sys::path::parent_path(DirName);
586     if (DirName.empty())
587       break;
588 
589     // Determine whether this directory exists.
590     auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
591     if (!Dir)
592       break;
593 
594     // If this is a framework directory, then we're a subframework of this
595     // framework.
596     if (llvm::sys::path::extension(DirName) == ".framework") {
597       SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
598       TopFrameworkDir = *Dir;
599     }
600   } while (true);
601 
602   return TopFrameworkDir;
603 }
604 
605 static bool needModuleLookup(Module *RequestingModule,
606                              bool HasSuggestedModule) {
607   return HasSuggestedModule ||
608          (RequestingModule && RequestingModule->NoUndeclaredIncludes);
609 }
610 
611 /// DoFrameworkLookup - Do a lookup of the specified file in the current
612 /// DirectoryLookup, which is a framework directory.
613 OptionalFileEntryRef DirectoryLookup::DoFrameworkLookup(
614     StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
615     SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
616     ModuleMap::KnownHeader *SuggestedModule,
617     bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
618   FileManager &FileMgr = HS.getFileMgr();
619 
620   // Framework names must have a '/' in the filename.
621   size_t SlashPos = Filename.find('/');
622   if (SlashPos == StringRef::npos)
623     return std::nullopt;
624 
625   // Find out if this is the home for the specified framework, by checking
626   // HeaderSearch.  Possible answers are yes/no and unknown.
627   FrameworkCacheEntry &CacheEntry =
628     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
629 
630   // If it is known and in some other directory, fail.
631   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef())
632     return std::nullopt;
633 
634   // Otherwise, construct the path to this framework dir.
635 
636   // FrameworkName = "/System/Library/Frameworks/"
637   SmallString<1024> FrameworkName;
638   FrameworkName += getFrameworkDirRef()->getName();
639   if (FrameworkName.empty() || FrameworkName.back() != '/')
640     FrameworkName.push_back('/');
641 
642   // FrameworkName = "/System/Library/Frameworks/Cocoa"
643   StringRef ModuleName(Filename.begin(), SlashPos);
644   FrameworkName += ModuleName;
645 
646   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
647   FrameworkName += ".framework/";
648 
649   // If the cache entry was unresolved, populate it now.
650   if (!CacheEntry.Directory) {
651     ++NumFrameworkLookups;
652 
653     // If the framework dir doesn't exist, we fail.
654     auto Dir = FileMgr.getDirectory(FrameworkName);
655     if (!Dir)
656       return std::nullopt;
657 
658     // Otherwise, if it does, remember that this is the right direntry for this
659     // framework.
660     CacheEntry.Directory = getFrameworkDirRef();
661 
662     // If this is a user search directory, check if the framework has been
663     // user-specified as a system framework.
664     if (getDirCharacteristic() == SrcMgr::C_User) {
665       SmallString<1024> SystemFrameworkMarker(FrameworkName);
666       SystemFrameworkMarker += ".system_framework";
667       if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
668         CacheEntry.IsUserSpecifiedSystemFramework = true;
669       }
670     }
671   }
672 
673   // Set out flags.
674   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
675   IsFrameworkFound = CacheEntry.Directory.has_value();
676 
677   if (RelativePath) {
678     RelativePath->clear();
679     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
680   }
681 
682   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
683   unsigned OrigSize = FrameworkName.size();
684 
685   FrameworkName += "Headers/";
686 
687   if (SearchPath) {
688     SearchPath->clear();
689     // Without trailing '/'.
690     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
691   }
692 
693   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
694 
695   auto File =
696       FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
697   if (!File) {
698     // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
699     const char *Private = "Private";
700     FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
701                          Private+strlen(Private));
702     if (SearchPath)
703       SearchPath->insert(SearchPath->begin()+OrigSize, Private,
704                          Private+strlen(Private));
705 
706     File = FileMgr.getOptionalFileRef(FrameworkName,
707                                       /*OpenFile=*/!SuggestedModule);
708   }
709 
710   // If we found the header and are allowed to suggest a module, do so now.
711   if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
712     // Find the framework in which this header occurs.
713     StringRef FrameworkPath = File->getDir().getName();
714     bool FoundFramework = false;
715     do {
716       // Determine whether this directory exists.
717       auto Dir = FileMgr.getDirectory(FrameworkPath);
718       if (!Dir)
719         break;
720 
721       // If this is a framework directory, then we're a subframework of this
722       // framework.
723       if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
724         FoundFramework = true;
725         break;
726       }
727 
728       // Get the parent directory name.
729       FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
730       if (FrameworkPath.empty())
731         break;
732     } while (true);
733 
734     bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
735     if (FoundFramework) {
736       if (!HS.findUsableModuleForFrameworkHeader(*File, FrameworkPath,
737                                                  RequestingModule,
738                                                  SuggestedModule, IsSystem))
739         return std::nullopt;
740     } else {
741       if (!HS.findUsableModuleForHeader(*File, getDir(), RequestingModule,
742                                         SuggestedModule, IsSystem))
743         return std::nullopt;
744     }
745   }
746   if (File)
747     return *File;
748   return std::nullopt;
749 }
750 
751 void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
752                                       ConstSearchDirIterator HitIt,
753                                       SourceLocation Loc) {
754   CacheLookup.HitIt = HitIt;
755   noteLookupUsage(HitIt.Idx, Loc);
756 }
757 
758 void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {
759   SearchDirsUsage[HitIdx] = true;
760 
761   auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);
762   if (UserEntryIdxIt != SearchDirToHSEntry.end())
763     Diags.Report(Loc, diag::remark_pp_search_path_usage)
764         << HSOpts->UserEntries[UserEntryIdxIt->second].Path;
765 }
766 
767 void HeaderSearch::setTarget(const TargetInfo &Target) {
768   ModMap.setTarget(Target);
769 }
770 
771 //===----------------------------------------------------------------------===//
772 // Header File Location.
773 //===----------------------------------------------------------------------===//
774 
775 /// Return true with a diagnostic if the file that MSVC would have found
776 /// fails to match the one that Clang would have found with MSVC header search
777 /// disabled.
778 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
779                                   OptionalFileEntryRef MSFE,
780                                   const FileEntry *FE,
781                                   SourceLocation IncludeLoc) {
782   if (MSFE && FE != *MSFE) {
783     Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
784     return true;
785   }
786   return false;
787 }
788 
789 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
790   assert(!Str.empty());
791   char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
792   std::copy(Str.begin(), Str.end(), CopyStr);
793   CopyStr[Str.size()] = '\0';
794   return CopyStr;
795 }
796 
797 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
798                                  SmallVectorImpl<char> &FrameworkName,
799                                  SmallVectorImpl<char> &IncludeSpelling) {
800   using namespace llvm::sys;
801   path::const_iterator I = path::begin(Path);
802   path::const_iterator E = path::end(Path);
803   IsPrivateHeader = false;
804 
805   // Detect different types of framework style paths:
806   //
807   //   ...Foo.framework/{Headers,PrivateHeaders}
808   //   ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
809   //   ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
810   //   ...<other variations with 'Versions' like in the above path>
811   //
812   // and some other variations among these lines.
813   int FoundComp = 0;
814   while (I != E) {
815     if (*I == "Headers") {
816       ++FoundComp;
817     } else if (*I == "PrivateHeaders") {
818       ++FoundComp;
819       IsPrivateHeader = true;
820     } else if (I->ends_with(".framework")) {
821       StringRef Name = I->drop_back(10); // Drop .framework
822       // Need to reset the strings and counter to support nested frameworks.
823       FrameworkName.clear();
824       FrameworkName.append(Name.begin(), Name.end());
825       IncludeSpelling.clear();
826       IncludeSpelling.append(Name.begin(), Name.end());
827       FoundComp = 1;
828     } else if (FoundComp >= 2) {
829       IncludeSpelling.push_back('/');
830       IncludeSpelling.append(I->begin(), I->end());
831     }
832     ++I;
833   }
834 
835   return !FrameworkName.empty() && FoundComp >= 2;
836 }
837 
838 static void
839 diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
840                          StringRef Includer, StringRef IncludeFilename,
841                          FileEntryRef IncludeFE, bool isAngled = false,
842                          bool FoundByHeaderMap = false) {
843   bool IsIncluderPrivateHeader = false;
844   SmallString<128> FromFramework, ToFramework;
845   SmallString<128> FromIncludeSpelling, ToIncludeSpelling;
846   if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,
847                             FromIncludeSpelling))
848     return;
849   bool IsIncludeePrivateHeader = false;
850   bool IsIncludeeInFramework =
851       isFrameworkStylePath(IncludeFE.getName(), IsIncludeePrivateHeader,
852                            ToFramework, ToIncludeSpelling);
853 
854   if (!isAngled && !FoundByHeaderMap) {
855     SmallString<128> NewInclude("<");
856     if (IsIncludeeInFramework) {
857       NewInclude += ToIncludeSpelling;
858       NewInclude += ">";
859     } else {
860       NewInclude += IncludeFilename;
861       NewInclude += ">";
862     }
863     Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
864         << IncludeFilename
865         << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
866   }
867 
868   // Headers in Foo.framework/Headers should not include headers
869   // from Foo.framework/PrivateHeaders, since this violates public/private
870   // API boundaries and can cause modular dependency cycles.
871   if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
872       IsIncludeePrivateHeader && FromFramework == ToFramework)
873     Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
874         << IncludeFilename;
875 }
876 
877 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
878 /// return null on failure.  isAngled indicates whether the file reference is
879 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
880 /// non-empty, indicates where the \#including file(s) are, in case a relative
881 /// search is needed. Microsoft mode will pass all \#including files.
882 OptionalFileEntryRef HeaderSearch::LookupFile(
883     StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
884     ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg,
885     ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>> Includers,
886     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
887     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
888     bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
889     bool BuildSystemModule, bool OpenFile, bool CacheFailures) {
890   ConstSearchDirIterator CurDirLocal = nullptr;
891   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
892 
893   if (IsMapped)
894     *IsMapped = false;
895 
896   if (IsFrameworkFound)
897     *IsFrameworkFound = false;
898 
899   if (SuggestedModule)
900     *SuggestedModule = ModuleMap::KnownHeader();
901 
902   // If 'Filename' is absolute, check to see if it exists and no searching.
903   if (llvm::sys::path::is_absolute(Filename)) {
904     CurDir = nullptr;
905 
906     // If this was an #include_next "/absolute/file", fail.
907     if (FromDir)
908       return std::nullopt;
909 
910     if (SearchPath)
911       SearchPath->clear();
912     if (RelativePath) {
913       RelativePath->clear();
914       RelativePath->append(Filename.begin(), Filename.end());
915     }
916     // Otherwise, just return the file.
917     return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
918                                    /*IsSystemHeaderDir*/ false,
919                                    RequestingModule, SuggestedModule, OpenFile,
920                                    CacheFailures);
921   }
922 
923   // This is the header that MSVC's header search would have found.
924   ModuleMap::KnownHeader MSSuggestedModule;
925   OptionalFileEntryRef MSFE;
926 
927   // Check to see if the file is in the #includer's directory. This cannot be
928   // based on CurDir, because each includer could be a #include of a
929   // subdirectory (#include "foo/bar.h") and a subsequent include of "baz.h"
930   // should resolve to "whatever/foo/baz.h". This search is not done for <>
931   // headers.
932   if (!Includers.empty() && !isAngled) {
933     SmallString<1024> TmpDir;
934     bool First = true;
935     for (const auto &IncluderAndDir : Includers) {
936       OptionalFileEntryRef Includer = IncluderAndDir.first;
937 
938       // Concatenate the requested file onto the directory.
939       TmpDir = IncluderAndDir.second.getName();
940       llvm::sys::path::append(TmpDir, Filename);
941 
942       // FIXME: We don't cache the result of getFileInfo across the call to
943       // getFileAndSuggestModule, because it's a reference to an element of
944       // a container that could be reallocated across this call.
945       //
946       // If we have no includer, that means we're processing a #include
947       // from a module build. We should treat this as a system header if we're
948       // building a [system] module.
949       bool IncluderIsSystemHeader = [&]() {
950         if (!Includer)
951           return BuildSystemModule;
952         const HeaderFileInfo *HFI = getExistingFileInfo(*Includer);
953         assert(HFI && "includer without file info");
954         return HFI->DirInfo != SrcMgr::C_User;
955       }();
956       if (OptionalFileEntryRef FE = getFileAndSuggestModule(
957               TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
958               RequestingModule, SuggestedModule)) {
959         if (!Includer) {
960           assert(First && "only first includer can have no file");
961           return FE;
962         }
963 
964         // Leave CurDir unset.
965         // This file is a system header or C++ unfriendly if the old file is.
966         //
967         // Note that we only use one of FromHFI/ToHFI at once, due to potential
968         // reallocation of the underlying vector potentially making the first
969         // reference binding dangling.
970         const HeaderFileInfo *FromHFI = getExistingFileInfo(*Includer);
971         assert(FromHFI && "includer without file info");
972         unsigned DirInfo = FromHFI->DirInfo;
973         bool IndexHeaderMapHeader = FromHFI->IndexHeaderMapHeader;
974         StringRef Framework = FromHFI->Framework;
975 
976         HeaderFileInfo &ToHFI = getFileInfo(*FE);
977         ToHFI.DirInfo = DirInfo;
978         ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
979         ToHFI.Framework = Framework;
980 
981         if (SearchPath) {
982           StringRef SearchPathRef(IncluderAndDir.second.getName());
983           SearchPath->clear();
984           SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
985         }
986         if (RelativePath) {
987           RelativePath->clear();
988           RelativePath->append(Filename.begin(), Filename.end());
989         }
990         if (First) {
991           diagnoseFrameworkInclude(Diags, IncludeLoc,
992                                    IncluderAndDir.second.getName(), Filename,
993                                    *FE);
994           return FE;
995         }
996 
997         // Otherwise, we found the path via MSVC header search rules.  If
998         // -Wmsvc-include is enabled, we have to keep searching to see if we
999         // would've found this header in -I or -isystem directories.
1000         if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
1001           return FE;
1002         } else {
1003           MSFE = FE;
1004           if (SuggestedModule) {
1005             MSSuggestedModule = *SuggestedModule;
1006             *SuggestedModule = ModuleMap::KnownHeader();
1007           }
1008           break;
1009         }
1010       }
1011       First = false;
1012     }
1013   }
1014 
1015   CurDir = nullptr;
1016 
1017   // If this is a system #include, ignore the user #include locs.
1018   ConstSearchDirIterator It =
1019       isAngled ? angled_dir_begin() : search_dir_begin();
1020 
1021   // If this is a #include_next request, start searching after the directory the
1022   // file was found in.
1023   if (FromDir)
1024     It = FromDir;
1025 
1026   // Cache all of the lookups performed by this method.  Many headers are
1027   // multiply included, and the "pragma once" optimization prevents them from
1028   // being relex/pp'd, but they would still have to search through a
1029   // (potentially huge) series of SearchDirs to find it.
1030   LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
1031 
1032   ConstSearchDirIterator NextIt = std::next(It);
1033 
1034   if (!SkipCache) {
1035     if (CacheLookup.StartIt == NextIt &&
1036         CacheLookup.RequestingModule == RequestingModule) {
1037       // HIT: Skip querying potentially lots of directories for this lookup.
1038       if (CacheLookup.HitIt)
1039         It = CacheLookup.HitIt;
1040       if (CacheLookup.MappedName) {
1041         Filename = CacheLookup.MappedName;
1042         if (IsMapped)
1043           *IsMapped = true;
1044       }
1045     } else {
1046       // MISS: This is the first query, or the previous query didn't match
1047       // our search start.  We will fill in our found location below, so prime
1048       // the start point value.
1049       CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);
1050 
1051       if (It == search_dir_begin() && FirstNonHeaderMapSearchDirIdx > 0) {
1052         // Handle cold misses of user includes in the presence of many header
1053         // maps.  We avoid searching perhaps thousands of header maps by
1054         // jumping directly to the correct one or jumping beyond all of them.
1055         auto Iter = SearchDirHeaderMapIndex.find(Filename.lower());
1056         if (Iter == SearchDirHeaderMapIndex.end())
1057           // Not in index => Skip to first SearchDir after initial header maps
1058           It = search_dir_nth(FirstNonHeaderMapSearchDirIdx);
1059         else
1060           // In index => Start with a specific header map
1061           It = search_dir_nth(Iter->second);
1062       }
1063     }
1064   } else {
1065     CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);
1066   }
1067 
1068   SmallString<64> MappedName;
1069 
1070   // Check each directory in sequence to see if it contains this file.
1071   for (; It != search_dir_end(); ++It) {
1072     bool InUserSpecifiedSystemFramework = false;
1073     bool IsInHeaderMap = false;
1074     bool IsFrameworkFoundInDir = false;
1075     OptionalFileEntryRef File = It->LookupFile(
1076         Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
1077         SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
1078         IsInHeaderMap, MappedName, OpenFile);
1079     if (!MappedName.empty()) {
1080       assert(IsInHeaderMap && "MappedName should come from a header map");
1081       CacheLookup.MappedName =
1082           copyString(MappedName, LookupFileCache.getAllocator());
1083     }
1084     if (IsMapped)
1085       // A filename is mapped when a header map remapped it to a relative path
1086       // used in subsequent header search or to an absolute path pointing to an
1087       // existing file.
1088       *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
1089     if (IsFrameworkFound)
1090       // Because we keep a filename remapped for subsequent search directory
1091       // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
1092       // just for remapping in a current search directory.
1093       *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
1094     if (!File)
1095       continue;
1096 
1097     CurDir = It;
1098 
1099     IncludeNames[*File] = Filename;
1100 
1101     // This file is a system header or C++ unfriendly if the dir is.
1102     HeaderFileInfo &HFI = getFileInfo(*File);
1103     HFI.DirInfo = CurDir->getDirCharacteristic();
1104 
1105     // If the directory characteristic is User but this framework was
1106     // user-specified to be treated as a system framework, promote the
1107     // characteristic.
1108     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
1109       HFI.DirInfo = SrcMgr::C_System;
1110 
1111     // If the filename matches a known system header prefix, override
1112     // whether the file is a system header.
1113     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
1114       if (Filename.starts_with(SystemHeaderPrefixes[j - 1].first)) {
1115         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
1116                                                        : SrcMgr::C_User;
1117         break;
1118       }
1119     }
1120 
1121     // Set the `Framework` info if this file is in a header map with framework
1122     // style include spelling or found in a framework dir. The header map case
1123     // is possible when building frameworks which use header maps.
1124     if (CurDir->isHeaderMap() && isAngled) {
1125       size_t SlashPos = Filename.find('/');
1126       if (SlashPos != StringRef::npos)
1127         HFI.Framework =
1128             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1129       if (CurDir->isIndexHeaderMap())
1130         HFI.IndexHeaderMapHeader = 1;
1131     } else if (CurDir->isFramework()) {
1132       size_t SlashPos = Filename.find('/');
1133       if (SlashPos != StringRef::npos)
1134         HFI.Framework =
1135             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1136     }
1137 
1138     if (checkMSVCHeaderSearch(Diags, MSFE, &File->getFileEntry(), IncludeLoc)) {
1139       if (SuggestedModule)
1140         *SuggestedModule = MSSuggestedModule;
1141       return MSFE;
1142     }
1143 
1144     bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
1145     if (!Includers.empty())
1146       diagnoseFrameworkInclude(Diags, IncludeLoc,
1147                                Includers.front().second.getName(), Filename,
1148                                *File, isAngled, FoundByHeaderMap);
1149 
1150     // Remember this location for the next lookup we do.
1151     cacheLookupSuccess(CacheLookup, It, IncludeLoc);
1152     return File;
1153   }
1154 
1155   // If we are including a file with a quoted include "foo.h" from inside
1156   // a header in a framework that is currently being built, and we couldn't
1157   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1158   // "Foo" is the name of the framework in which the including header was found.
1159   if (!Includers.empty() && Includers.front().first && !isAngled &&
1160       !Filename.contains('/')) {
1161     const HeaderFileInfo *IncludingHFI =
1162         getExistingFileInfo(*Includers.front().first);
1163     assert(IncludingHFI && "includer without file info");
1164     if (IncludingHFI->IndexHeaderMapHeader) {
1165       SmallString<128> ScratchFilename;
1166       ScratchFilename += IncludingHFI->Framework;
1167       ScratchFilename += '/';
1168       ScratchFilename += Filename;
1169 
1170       OptionalFileEntryRef File = LookupFile(
1171           ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir,
1172           Includers.front(), SearchPath, RelativePath, RequestingModule,
1173           SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
1174 
1175       if (checkMSVCHeaderSearch(Diags, MSFE,
1176                                 File ? &File->getFileEntry() : nullptr,
1177                                 IncludeLoc)) {
1178         if (SuggestedModule)
1179           *SuggestedModule = MSSuggestedModule;
1180         return MSFE;
1181       }
1182 
1183       cacheLookupSuccess(LookupFileCache[Filename],
1184                          LookupFileCache[ScratchFilename].HitIt, IncludeLoc);
1185       // FIXME: SuggestedModule.
1186       return File;
1187     }
1188   }
1189 
1190   if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
1191     if (SuggestedModule)
1192       *SuggestedModule = MSSuggestedModule;
1193     return MSFE;
1194   }
1195 
1196   // Otherwise, didn't find it. Remember we didn't find this.
1197   CacheLookup.HitIt = search_dir_end();
1198   return std::nullopt;
1199 }
1200 
1201 /// LookupSubframeworkHeader - Look up a subframework for the specified
1202 /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1203 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1204 /// is a subframework within Carbon.framework.  If so, return the FileEntry
1205 /// for the designated file, otherwise return null.
1206 OptionalFileEntryRef HeaderSearch::LookupSubframeworkHeader(
1207     StringRef Filename, FileEntryRef ContextFileEnt,
1208     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1209     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
1210   // Framework names must have a '/' in the filename.  Find it.
1211   // FIXME: Should we permit '\' on Windows?
1212   size_t SlashPos = Filename.find('/');
1213   if (SlashPos == StringRef::npos)
1214     return std::nullopt;
1215 
1216   // Look up the base framework name of the ContextFileEnt.
1217   StringRef ContextName = ContextFileEnt.getName();
1218 
1219   // If the context info wasn't a framework, couldn't be a subframework.
1220   const unsigned DotFrameworkLen = 10;
1221   auto FrameworkPos = ContextName.find(".framework");
1222   if (FrameworkPos == StringRef::npos ||
1223       (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1224        ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1225     return std::nullopt;
1226 
1227   SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1228                                                           FrameworkPos +
1229                                                           DotFrameworkLen + 1);
1230 
1231   // Append Frameworks/HIToolbox.framework/
1232   FrameworkName += "Frameworks/";
1233   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1234   FrameworkName += ".framework/";
1235 
1236   auto &CacheLookup =
1237       *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1238                                           FrameworkCacheEntry())).first;
1239 
1240   // Some other location?
1241   if (CacheLookup.second.Directory &&
1242       CacheLookup.first().size() == FrameworkName.size() &&
1243       memcmp(CacheLookup.first().data(), &FrameworkName[0],
1244              CacheLookup.first().size()) != 0)
1245     return std::nullopt;
1246 
1247   // Cache subframework.
1248   if (!CacheLookup.second.Directory) {
1249     ++NumSubFrameworkLookups;
1250 
1251     // If the framework dir doesn't exist, we fail.
1252     auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
1253     if (!Dir)
1254       return std::nullopt;
1255 
1256     // Otherwise, if it does, remember that this is the right direntry for this
1257     // framework.
1258     CacheLookup.second.Directory = Dir;
1259   }
1260 
1261 
1262   if (RelativePath) {
1263     RelativePath->clear();
1264     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1265   }
1266 
1267   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1268   SmallString<1024> HeadersFilename(FrameworkName);
1269   HeadersFilename += "Headers/";
1270   if (SearchPath) {
1271     SearchPath->clear();
1272     // Without trailing '/'.
1273     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1274   }
1275 
1276   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1277   auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1278   if (!File) {
1279     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1280     HeadersFilename = FrameworkName;
1281     HeadersFilename += "PrivateHeaders/";
1282     if (SearchPath) {
1283       SearchPath->clear();
1284       // Without trailing '/'.
1285       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1286     }
1287 
1288     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1289     File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1290 
1291     if (!File)
1292       return std::nullopt;
1293   }
1294 
1295   // This file is a system header or C++ unfriendly if the old file is.
1296   const HeaderFileInfo *ContextHFI = getExistingFileInfo(ContextFileEnt);
1297   assert(ContextHFI && "context file without file info");
1298   // Note that the temporary 'DirInfo' is required here, as the call to
1299   // getFileInfo could resize the vector and might invalidate 'ContextHFI'.
1300   unsigned DirInfo = ContextHFI->DirInfo;
1301   getFileInfo(*File).DirInfo = DirInfo;
1302 
1303   FrameworkName.pop_back(); // remove the trailing '/'
1304   if (!findUsableModuleForFrameworkHeader(*File, FrameworkName,
1305                                           RequestingModule, SuggestedModule,
1306                                           /*IsSystem*/ false))
1307     return std::nullopt;
1308 
1309   return *File;
1310 }
1311 
1312 //===----------------------------------------------------------------------===//
1313 // File Info Management.
1314 //===----------------------------------------------------------------------===//
1315 
1316 static void mergeHeaderFileInfoModuleBits(HeaderFileInfo &HFI,
1317                                           bool isModuleHeader,
1318                                           bool isTextualModuleHeader) {
1319   assert((!isModuleHeader || !isTextualModuleHeader) &&
1320          "A header can't build with a module and be textual at the same time");
1321   HFI.isModuleHeader |= isModuleHeader;
1322   if (HFI.isModuleHeader)
1323     HFI.isTextualModuleHeader = false;
1324   else
1325     HFI.isTextualModuleHeader |= isTextualModuleHeader;
1326 }
1327 
1328 void HeaderFileInfo::mergeModuleMembership(ModuleMap::ModuleHeaderRole Role) {
1329   mergeHeaderFileInfoModuleBits(*this, ModuleMap::isModular(Role),
1330                                 (Role & ModuleMap::TextualHeader));
1331 }
1332 
1333 /// Merge the header file info provided by \p OtherHFI into the current
1334 /// header file info (\p HFI)
1335 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1336                                 const HeaderFileInfo &OtherHFI) {
1337   assert(OtherHFI.External && "expected to merge external HFI");
1338 
1339   HFI.isImport |= OtherHFI.isImport;
1340   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1341   mergeHeaderFileInfoModuleBits(HFI, OtherHFI.isModuleHeader,
1342                                 OtherHFI.isTextualModuleHeader);
1343 
1344   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1345     HFI.ControllingMacro = OtherHFI.ControllingMacro;
1346     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1347   }
1348 
1349   HFI.DirInfo = OtherHFI.DirInfo;
1350   HFI.External = (!HFI.IsValid || HFI.External);
1351   HFI.IsValid = true;
1352   HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1353 
1354   if (HFI.Framework.empty())
1355     HFI.Framework = OtherHFI.Framework;
1356 }
1357 
1358 HeaderFileInfo &HeaderSearch::getFileInfo(FileEntryRef FE) {
1359   if (FE.getUID() >= FileInfo.size())
1360     FileInfo.resize(FE.getUID() + 1);
1361 
1362   HeaderFileInfo *HFI = &FileInfo[FE.getUID()];
1363   // FIXME: Use a generation count to check whether this is really up to date.
1364   if (ExternalSource && !HFI->Resolved) {
1365     auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1366     if (ExternalHFI.IsValid) {
1367       HFI->Resolved = true;
1368       if (ExternalHFI.External)
1369         mergeHeaderFileInfo(*HFI, ExternalHFI);
1370     }
1371   }
1372 
1373   HFI->IsValid = true;
1374   // We assume the caller has local information about this header file, so it's
1375   // no longer strictly external.
1376   HFI->External = false;
1377   return *HFI;
1378 }
1379 
1380 const HeaderFileInfo *HeaderSearch::getExistingFileInfo(FileEntryRef FE) const {
1381   HeaderFileInfo *HFI;
1382   if (ExternalSource) {
1383     if (FE.getUID() >= FileInfo.size())
1384       FileInfo.resize(FE.getUID() + 1);
1385 
1386     HFI = &FileInfo[FE.getUID()];
1387     // FIXME: Use a generation count to check whether this is really up to date.
1388     if (!HFI->Resolved) {
1389       auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1390       if (ExternalHFI.IsValid) {
1391         HFI->Resolved = true;
1392         if (ExternalHFI.External)
1393           mergeHeaderFileInfo(*HFI, ExternalHFI);
1394       }
1395     }
1396   } else if (FE.getUID() < FileInfo.size()) {
1397     HFI = &FileInfo[FE.getUID()];
1398   } else {
1399     HFI = nullptr;
1400   }
1401 
1402   return (HFI && HFI->IsValid) ? HFI : nullptr;
1403 }
1404 
1405 const HeaderFileInfo *
1406 HeaderSearch::getExistingLocalFileInfo(FileEntryRef FE) const {
1407   HeaderFileInfo *HFI;
1408   if (FE.getUID() < FileInfo.size()) {
1409     HFI = &FileInfo[FE.getUID()];
1410   } else {
1411     HFI = nullptr;
1412   }
1413 
1414   return (HFI && HFI->IsValid && !HFI->External) ? HFI : nullptr;
1415 }
1416 
1417 bool HeaderSearch::isFileMultipleIncludeGuarded(FileEntryRef File) const {
1418   // Check if we've entered this file and found an include guard or #pragma
1419   // once. Note that we dor't check for #import, because that's not a property
1420   // of the file itself.
1421   if (auto *HFI = getExistingFileInfo(File))
1422     return HFI->isPragmaOnce || HFI->ControllingMacro ||
1423            HFI->ControllingMacroID;
1424   return false;
1425 }
1426 
1427 void HeaderSearch::MarkFileModuleHeader(FileEntryRef FE,
1428                                         ModuleMap::ModuleHeaderRole Role,
1429                                         bool isCompilingModuleHeader) {
1430   // Don't mark the file info as non-external if there's nothing to change.
1431   if (!isCompilingModuleHeader) {
1432     if ((Role & ModuleMap::ExcludedHeader))
1433       return;
1434     auto *HFI = getExistingFileInfo(FE);
1435     if (HFI && HFI->isModuleHeader)
1436       return;
1437   }
1438 
1439   auto &HFI = getFileInfo(FE);
1440   HFI.mergeModuleMembership(Role);
1441   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1442 }
1443 
1444 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1445                                           FileEntryRef File, bool isImport,
1446                                           bool ModulesEnabled, Module *M,
1447                                           bool &IsFirstIncludeOfFile) {
1448   // An include file should be entered if either:
1449   // 1. This is the first include of the file.
1450   // 2. This file can be included multiple times, that is it's not an
1451   //    "include-once" file.
1452   //
1453   // Include-once is controlled by these preprocessor directives.
1454   //
1455   // #pragma once
1456   // This directive is in the include file, and marks it as an include-once
1457   // file.
1458   //
1459   // #import <file>
1460   // This directive is in the includer, and indicates that the include file
1461   // should only be entered if this is the first include.
1462   ++NumIncluded;
1463   IsFirstIncludeOfFile = false;
1464   HeaderFileInfo &FileInfo = getFileInfo(File);
1465 
1466   auto MaybeReenterImportedFile = [&]() -> bool {
1467     // Modules add a wrinkle though: what's included isn't necessarily visible.
1468     // Consider this module.
1469     // module Example {
1470     //   module A { header "a.h" export * }
1471     //   module B { header "b.h" export * }
1472     // }
1473     // b.h includes c.h. The main file includes a.h, which will trigger a module
1474     // build of Example, and c.h will be included. However, c.h isn't visible to
1475     // the main file. Normally this is fine, the main file can just include c.h
1476     // if it needs it. If c.h is in a module, the include will translate into a
1477     // module import, this function will be skipped, and everything will work as
1478     // expected. However, if c.h is not in a module (or is `textual`), then this
1479     // function will run. If c.h is include-once, it will not be entered from
1480     // the main file and it will still not be visible.
1481 
1482     // If modules aren't enabled then there's no visibility issue. Always
1483     // respect `#pragma once`.
1484     if (!ModulesEnabled || FileInfo.isPragmaOnce)
1485       return false;
1486 
1487     // Ensure FileInfo bits are up to date.
1488     ModMap.resolveHeaderDirectives(File);
1489 
1490     // This brings up a subtlety of #import - it's not a very good indicator of
1491     // include-once. Developers are often unaware of the difference between
1492     // #include and #import, and tend to use one or the other indiscrimiately.
1493     // In order to support #include on include-once headers that lack macro
1494     // guards and `#pragma once` (which is the vast majority of Objective-C
1495     // headers), if a file is ever included with #import, it's marked as
1496     // isImport in the HeaderFileInfo and treated as include-once. This allows
1497     // #include to work in Objective-C.
1498     // #include <Foundation/Foundation.h>
1499     // #include <Foundation/NSString.h>
1500     // Foundation.h has an #import of NSString.h, and so the second #include is
1501     // skipped even though NSString.h has no `#pragma once` and no macro guard.
1502     //
1503     // However, this helpfulness causes problems with modules. If c.h is not an
1504     // include-once file, but something included it with #import anyway (as is
1505     // typical in Objective-C code), this include will be skipped and c.h will
1506     // not be visible. Consider it not include-once if it is a `textual` header
1507     // in a module.
1508     if (FileInfo.isTextualModuleHeader)
1509       return true;
1510 
1511     if (FileInfo.isCompilingModuleHeader) {
1512       // It's safer to re-enter a file whose module is being built because its
1513       // declarations will still be scoped to a single module.
1514       if (FileInfo.isModuleHeader) {
1515         // Headers marked as "builtin" are covered by the system module maps
1516         // rather than the builtin ones. Some versions of the Darwin module fail
1517         // to mark stdarg.h and stddef.h as textual. Attempt to re-enter these
1518         // files while building their module to allow them to function properly.
1519         if (ModMap.isBuiltinHeader(File))
1520           return true;
1521       } else {
1522         // Files that are excluded from their module can potentially be
1523         // re-entered from their own module. This might cause redeclaration
1524         // errors if another module saw this file first, but there's a
1525         // reasonable chance that its module will build first. However if
1526         // there's no controlling macro, then trust the #import and assume this
1527         // really is an include-once file.
1528         if (FileInfo.getControllingMacro(ExternalLookup))
1529           return true;
1530       }
1531     }
1532     // If the include file has a macro guard, then it might still not be
1533     // re-entered if the controlling macro is visibly defined. e.g. another
1534     // header in the module being built included this file and local submodule
1535     // visibility is not enabled.
1536 
1537     // It might be tempting to re-enter the include-once file if it's not
1538     // visible in an attempt to make it visible. However this will still cause
1539     // redeclaration errors against the known-but-not-visible declarations. The
1540     // include file not being visible will most likely cause "undefined x"
1541     // errors, but at least there's a slim chance of compilation succeeding.
1542     return false;
1543   };
1544 
1545   if (isImport) {
1546     // As discussed above, record that this file was ever `#import`ed, and treat
1547     // it as an include-once file from here out.
1548     FileInfo.isImport = true;
1549     if (PP.alreadyIncluded(File) && !MaybeReenterImportedFile())
1550       return false;
1551   } else {
1552     // isPragmaOnce and isImport are only set after the file has been included
1553     // at least once. If either are set then this is a repeat #include of an
1554     // include-once file.
1555     if (FileInfo.isPragmaOnce ||
1556         (FileInfo.isImport && !MaybeReenterImportedFile()))
1557       return false;
1558   }
1559 
1560   // As a final optimization, check for a macro guard and skip entering the file
1561   // if the controlling macro is defined. The macro guard will effectively erase
1562   // the file's contents, and the include would have no effect other than to
1563   // waste time opening and reading a file.
1564   if (const IdentifierInfo *ControllingMacro =
1565           FileInfo.getControllingMacro(ExternalLookup)) {
1566     // If the header corresponds to a module, check whether the macro is already
1567     // defined in that module rather than checking all visible modules. This is
1568     // mainly to cover corner cases where the same controlling macro is used in
1569     // different files in multiple modules.
1570     if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1571           : PP.isMacroDefined(ControllingMacro)) {
1572       ++NumMultiIncludeFileOptzn;
1573       return false;
1574     }
1575   }
1576 
1577   IsFirstIncludeOfFile = PP.markIncluded(File);
1578   return true;
1579 }
1580 
1581 size_t HeaderSearch::getTotalMemory() const {
1582   return SearchDirs.capacity()
1583     + llvm::capacity_in_bytes(FileInfo)
1584     + llvm::capacity_in_bytes(HeaderMaps)
1585     + LookupFileCache.getAllocator().getTotalMemory()
1586     + FrameworkMap.getAllocator().getTotalMemory();
1587 }
1588 
1589 unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const {
1590   return &DL - &*SearchDirs.begin();
1591 }
1592 
1593 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1594   return FrameworkNames.insert(Framework).first->first();
1595 }
1596 
1597 StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {
1598   auto It = IncludeNames.find(File);
1599   if (It == IncludeNames.end())
1600     return {};
1601   return It->second;
1602 }
1603 
1604 bool HeaderSearch::hasModuleMap(StringRef FileName,
1605                                 const DirectoryEntry *Root,
1606                                 bool IsSystem) {
1607   if (!HSOpts->ImplicitModuleMaps)
1608     return false;
1609 
1610   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1611 
1612   StringRef DirName = FileName;
1613   do {
1614     // Get the parent directory name.
1615     DirName = llvm::sys::path::parent_path(DirName);
1616     if (DirName.empty())
1617       return false;
1618 
1619     // Determine whether this directory exists.
1620     auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
1621     if (!Dir)
1622       return false;
1623 
1624     // Try to load the module map file in this directory.
1625     switch (loadModuleMapFile(*Dir, IsSystem,
1626                               llvm::sys::path::extension(Dir->getName()) ==
1627                                   ".framework")) {
1628     case LMM_NewlyLoaded:
1629     case LMM_AlreadyLoaded:
1630       // Success. All of the directories we stepped through inherit this module
1631       // map file.
1632       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1633         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1634       return true;
1635 
1636     case LMM_NoDirectory:
1637     case LMM_InvalidModuleMap:
1638       break;
1639     }
1640 
1641     // If we hit the top of our search, we're done.
1642     if (*Dir == Root)
1643       return false;
1644 
1645     // Keep track of all of the directories we checked, so we can mark them as
1646     // having module maps if we eventually do find a module map.
1647     FixUpDirectories.push_back(*Dir);
1648   } while (true);
1649 }
1650 
1651 ModuleMap::KnownHeader
1652 HeaderSearch::findModuleForHeader(FileEntryRef File, bool AllowTextual,
1653                                   bool AllowExcluded) const {
1654   if (ExternalSource) {
1655     // Make sure the external source has handled header info about this file,
1656     // which includes whether the file is part of a module.
1657     (void)getExistingFileInfo(File);
1658   }
1659   return ModMap.findModuleForHeader(File, AllowTextual, AllowExcluded);
1660 }
1661 
1662 ArrayRef<ModuleMap::KnownHeader>
1663 HeaderSearch::findAllModulesForHeader(FileEntryRef File) const {
1664   if (ExternalSource) {
1665     // Make sure the external source has handled header info about this file,
1666     // which includes whether the file is part of a module.
1667     (void)getExistingFileInfo(File);
1668   }
1669   return ModMap.findAllModulesForHeader(File);
1670 }
1671 
1672 ArrayRef<ModuleMap::KnownHeader>
1673 HeaderSearch::findResolvedModulesForHeader(FileEntryRef File) const {
1674   if (ExternalSource) {
1675     // Make sure the external source has handled header info about this file,
1676     // which includes whether the file is part of a module.
1677     (void)getExistingFileInfo(File);
1678   }
1679   return ModMap.findResolvedModulesForHeader(File);
1680 }
1681 
1682 static bool suggestModule(HeaderSearch &HS, FileEntryRef File,
1683                           Module *RequestingModule,
1684                           ModuleMap::KnownHeader *SuggestedModule) {
1685   ModuleMap::KnownHeader Module =
1686       HS.findModuleForHeader(File, /*AllowTextual*/true);
1687 
1688   // If this module specifies [no_undeclared_includes], we cannot find any
1689   // file that's in a non-dependency module.
1690   if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1691     HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);
1692     if (!RequestingModule->directlyUses(Module.getModule())) {
1693       // Builtin headers are a special case. Multiple modules can use the same
1694       // builtin as a modular header (see also comment in
1695       // ShouldEnterIncludeFile()), so the builtin header may have been
1696       // "claimed" by an unrelated module. This shouldn't prevent us from
1697       // including the builtin header textually in this module.
1698       if (HS.getModuleMap().isBuiltinHeader(File)) {
1699         if (SuggestedModule)
1700           *SuggestedModule = ModuleMap::KnownHeader();
1701         return true;
1702       }
1703       // TODO: Add this module (or just its module map file) into something like
1704       // `RequestingModule->AffectingClangModules`.
1705       return false;
1706     }
1707   }
1708 
1709   if (SuggestedModule)
1710     *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1711                            ? ModuleMap::KnownHeader()
1712                            : Module;
1713 
1714   return true;
1715 }
1716 
1717 bool HeaderSearch::findUsableModuleForHeader(
1718     FileEntryRef File, const DirectoryEntry *Root, Module *RequestingModule,
1719     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1720   if (needModuleLookup(RequestingModule, SuggestedModule)) {
1721     // If there is a module that corresponds to this header, suggest it.
1722     hasModuleMap(File.getNameAsRequested(), Root, IsSystemHeaderDir);
1723     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1724   }
1725   return true;
1726 }
1727 
1728 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1729     FileEntryRef File, StringRef FrameworkName, Module *RequestingModule,
1730     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1731   // If we're supposed to suggest a module, look for one now.
1732   if (needModuleLookup(RequestingModule, SuggestedModule)) {
1733     // Find the top-level framework based on this framework.
1734     SmallVector<std::string, 4> SubmodulePath;
1735     OptionalDirectoryEntryRef TopFrameworkDir =
1736         ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1737     assert(TopFrameworkDir && "Could not find the top-most framework dir");
1738 
1739     // Determine the name of the top-level framework.
1740     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1741 
1742     // Load this framework module. If that succeeds, find the suggested module
1743     // for this header, if any.
1744     loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);
1745 
1746     // FIXME: This can find a module not part of ModuleName, which is
1747     // important so that we're consistent about whether this header
1748     // corresponds to a module. Possibly we should lock down framework modules
1749     // so that this is not possible.
1750     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1751   }
1752   return true;
1753 }
1754 
1755 static OptionalFileEntryRef getPrivateModuleMap(FileEntryRef File,
1756                                                 FileManager &FileMgr,
1757                                                 DiagnosticsEngine &Diags) {
1758   StringRef Filename = llvm::sys::path::filename(File.getName());
1759   SmallString<128>  PrivateFilename(File.getDir().getName());
1760   if (Filename == "module.map")
1761     llvm::sys::path::append(PrivateFilename, "module_private.map");
1762   else if (Filename == "module.modulemap")
1763     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1764   else
1765     return std::nullopt;
1766   auto PMMFile = FileMgr.getOptionalFileRef(PrivateFilename);
1767   if (PMMFile) {
1768     if (Filename == "module.map")
1769       Diags.Report(diag::warn_deprecated_module_dot_map)
1770           << PrivateFilename << 1
1771           << File.getDir().getName().ends_with(".framework");
1772   }
1773   return PMMFile;
1774 }
1775 
1776 bool HeaderSearch::loadModuleMapFile(FileEntryRef File, bool IsSystem,
1777                                      FileID ID, unsigned *Offset,
1778                                      StringRef OriginalModuleMapFile) {
1779   // Find the directory for the module. For frameworks, that may require going
1780   // up from the 'Modules' directory.
1781   OptionalDirectoryEntryRef Dir;
1782   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1783     Dir = FileMgr.getOptionalDirectoryRef(".");
1784   } else {
1785     if (!OriginalModuleMapFile.empty()) {
1786       // We're building a preprocessed module map. Find or invent the directory
1787       // that it originally occupied.
1788       Dir = FileMgr.getOptionalDirectoryRef(
1789           llvm::sys::path::parent_path(OriginalModuleMapFile));
1790       if (!Dir) {
1791         auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0);
1792         Dir = FakeFile.getDir();
1793       }
1794     } else {
1795       Dir = File.getDir();
1796     }
1797 
1798     assert(Dir && "parent must exist");
1799     StringRef DirName(Dir->getName());
1800     if (llvm::sys::path::filename(DirName) == "Modules") {
1801       DirName = llvm::sys::path::parent_path(DirName);
1802       if (DirName.ends_with(".framework"))
1803         if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName))
1804           Dir = *MaybeDir;
1805       // FIXME: This assert can fail if there's a race between the above check
1806       // and the removal of the directory.
1807       assert(Dir && "parent must exist");
1808     }
1809   }
1810 
1811   assert(Dir && "module map home directory must exist");
1812   switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) {
1813   case LMM_AlreadyLoaded:
1814   case LMM_NewlyLoaded:
1815     return false;
1816   case LMM_NoDirectory:
1817   case LMM_InvalidModuleMap:
1818     return true;
1819   }
1820   llvm_unreachable("Unknown load module map result");
1821 }
1822 
1823 HeaderSearch::LoadModuleMapResult
1824 HeaderSearch::loadModuleMapFileImpl(FileEntryRef File, bool IsSystem,
1825                                     DirectoryEntryRef Dir, FileID ID,
1826                                     unsigned *Offset) {
1827   // Check whether we've already loaded this module map, and mark it as being
1828   // loaded in case we recursively try to load it from itself.
1829   auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1830   if (!AddResult.second)
1831     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1832 
1833   if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1834     LoadedModuleMaps[File] = false;
1835     return LMM_InvalidModuleMap;
1836   }
1837 
1838   // Try to load a corresponding private module map.
1839   if (OptionalFileEntryRef PMMFile =
1840           getPrivateModuleMap(File, FileMgr, Diags)) {
1841     if (ModMap.parseModuleMapFile(*PMMFile, IsSystem, Dir)) {
1842       LoadedModuleMaps[File] = false;
1843       return LMM_InvalidModuleMap;
1844     }
1845   }
1846 
1847   // This directory has a module map.
1848   return LMM_NewlyLoaded;
1849 }
1850 
1851 OptionalFileEntryRef
1852 HeaderSearch::lookupModuleMapFile(DirectoryEntryRef Dir, bool IsFramework) {
1853   if (!HSOpts->ImplicitModuleMaps)
1854     return std::nullopt;
1855   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1856   // module.map at the framework root is also accepted.
1857   SmallString<128> ModuleMapFileName(Dir.getName());
1858   if (IsFramework)
1859     llvm::sys::path::append(ModuleMapFileName, "Modules");
1860   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1861   if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1862     return *F;
1863 
1864   // Continue to allow module.map, but warn it's deprecated.
1865   ModuleMapFileName = Dir.getName();
1866   llvm::sys::path::append(ModuleMapFileName, "module.map");
1867   if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName)) {
1868     Diags.Report(diag::warn_deprecated_module_dot_map)
1869         << ModuleMapFileName << 0 << IsFramework;
1870     return *F;
1871   }
1872 
1873   // For frameworks, allow to have a private module map with a preferred
1874   // spelling when a public module map is absent.
1875   if (IsFramework) {
1876     ModuleMapFileName = Dir.getName();
1877     llvm::sys::path::append(ModuleMapFileName, "Modules",
1878                             "module.private.modulemap");
1879     if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1880       return *F;
1881   }
1882   return std::nullopt;
1883 }
1884 
1885 Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
1886                                           bool IsSystem) {
1887   // Try to load a module map file.
1888   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1889   case LMM_InvalidModuleMap:
1890     // Try to infer a module map from the framework directory.
1891     if (HSOpts->ImplicitModuleMaps)
1892       ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1893     break;
1894 
1895   case LMM_NoDirectory:
1896     return nullptr;
1897 
1898   case LMM_AlreadyLoaded:
1899   case LMM_NewlyLoaded:
1900     break;
1901   }
1902 
1903   return ModMap.findModule(Name);
1904 }
1905 
1906 HeaderSearch::LoadModuleMapResult
1907 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1908                                 bool IsFramework) {
1909   if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName))
1910     return loadModuleMapFile(*Dir, IsSystem, IsFramework);
1911 
1912   return LMM_NoDirectory;
1913 }
1914 
1915 HeaderSearch::LoadModuleMapResult
1916 HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
1917                                 bool IsFramework) {
1918   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1919   if (KnownDir != DirectoryHasModuleMap.end())
1920     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1921 
1922   if (OptionalFileEntryRef ModuleMapFile =
1923           lookupModuleMapFile(Dir, IsFramework)) {
1924     LoadModuleMapResult Result =
1925         loadModuleMapFileImpl(*ModuleMapFile, IsSystem, Dir);
1926     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1927     // E.g. Foo.framework/Modules/module.modulemap
1928     //      ^Dir                  ^ModuleMapFile
1929     if (Result == LMM_NewlyLoaded)
1930       DirectoryHasModuleMap[Dir] = true;
1931     else if (Result == LMM_InvalidModuleMap)
1932       DirectoryHasModuleMap[Dir] = false;
1933     return Result;
1934   }
1935   return LMM_InvalidModuleMap;
1936 }
1937 
1938 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1939   Modules.clear();
1940 
1941   if (HSOpts->ImplicitModuleMaps) {
1942     // Load module maps for each of the header search directories.
1943     for (DirectoryLookup &DL : search_dir_range()) {
1944       bool IsSystem = DL.isSystemHeaderDirectory();
1945       if (DL.isFramework()) {
1946         std::error_code EC;
1947         SmallString<128> DirNative;
1948         llvm::sys::path::native(DL.getFrameworkDirRef()->getName(), DirNative);
1949 
1950         // Search each of the ".framework" directories to load them as modules.
1951         llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1952         for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1953                                            DirEnd;
1954              Dir != DirEnd && !EC; Dir.increment(EC)) {
1955           if (llvm::sys::path::extension(Dir->path()) != ".framework")
1956             continue;
1957 
1958           auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path());
1959           if (!FrameworkDir)
1960             continue;
1961 
1962           // Load this framework module.
1963           loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
1964                               IsSystem);
1965         }
1966         continue;
1967       }
1968 
1969       // FIXME: Deal with header maps.
1970       if (DL.isHeaderMap())
1971         continue;
1972 
1973       // Try to load a module map file for the search directory.
1974       loadModuleMapFile(*DL.getDirRef(), IsSystem, /*IsFramework*/ false);
1975 
1976       // Try to load module map files for immediate subdirectories of this
1977       // search directory.
1978       loadSubdirectoryModuleMaps(DL);
1979     }
1980   }
1981 
1982   // Populate the list of modules.
1983   llvm::transform(ModMap.modules(), std::back_inserter(Modules),
1984                   [](const auto &NameAndMod) { return NameAndMod.second; });
1985 }
1986 
1987 void HeaderSearch::loadTopLevelSystemModules() {
1988   if (!HSOpts->ImplicitModuleMaps)
1989     return;
1990 
1991   // Load module maps for each of the header search directories.
1992   for (const DirectoryLookup &DL : search_dir_range()) {
1993     // We only care about normal header directories.
1994     if (!DL.isNormalDir())
1995       continue;
1996 
1997     // Try to load a module map file for the search directory.
1998     loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(),
1999                       DL.isFramework());
2000   }
2001 }
2002 
2003 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
2004   assert(HSOpts->ImplicitModuleMaps &&
2005          "Should not be loading subdirectory module maps");
2006 
2007   if (SearchDir.haveSearchedAllModuleMaps())
2008     return;
2009 
2010   std::error_code EC;
2011   SmallString<128> Dir = SearchDir.getDirRef()->getName();
2012   FileMgr.makeAbsolutePath(Dir);
2013   SmallString<128> DirNative;
2014   llvm::sys::path::native(Dir, DirNative);
2015   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
2016   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
2017        Dir != DirEnd && !EC; Dir.increment(EC)) {
2018     if (Dir->type() == llvm::sys::fs::file_type::regular_file)
2019       continue;
2020     bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
2021     if (IsFramework == SearchDir.isFramework())
2022       loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
2023                         SearchDir.isFramework());
2024   }
2025 
2026   SearchDir.setSearchedAllModuleMaps(true);
2027 }
2028 
2029 std::string HeaderSearch::suggestPathToFileForDiagnostics(
2030     FileEntryRef File, llvm::StringRef MainFile, bool *IsAngled) const {
2031   return suggestPathToFileForDiagnostics(File.getName(), /*WorkingDir=*/"",
2032                                          MainFile, IsAngled);
2033 }
2034 
2035 std::string HeaderSearch::suggestPathToFileForDiagnostics(
2036     llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
2037     bool *IsAngled) const {
2038   using namespace llvm::sys;
2039 
2040   llvm::SmallString<32> FilePath = File;
2041   // remove_dots switches to backslashes on windows as a side-effect!
2042   // We always want to suggest forward slashes for includes.
2043   // (not remove_dots(..., posix) as that misparses windows paths).
2044   path::remove_dots(FilePath, /*remove_dot_dot=*/true);
2045   path::native(FilePath, path::Style::posix);
2046   File = FilePath;
2047 
2048   unsigned BestPrefixLength = 0;
2049   // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
2050   // the longest prefix we've seen so for it, returns true and updates the
2051   // `BestPrefixLength` accordingly.
2052   auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool {
2053     if (!WorkingDir.empty() && !path::is_absolute(Dir))
2054       fs::make_absolute(WorkingDir, Dir);
2055     path::remove_dots(Dir, /*remove_dot_dot=*/true);
2056     for (auto NI = path::begin(File), NE = path::end(File),
2057               DI = path::begin(Dir), DE = path::end(Dir);
2058          NI != NE; ++NI, ++DI) {
2059       if (DI == DE) {
2060         // Dir is a prefix of File, up to choice of path separators.
2061         unsigned PrefixLength = NI - path::begin(File);
2062         if (PrefixLength > BestPrefixLength) {
2063           BestPrefixLength = PrefixLength;
2064           return true;
2065         }
2066         break;
2067       }
2068 
2069       // Consider all path separators equal.
2070       if (NI->size() == 1 && DI->size() == 1 &&
2071           path::is_separator(NI->front()) && path::is_separator(DI->front()))
2072         continue;
2073 
2074       // Special case Apple .sdk folders since the search path is typically a
2075       // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
2076       // located in `iPhoneSimulator.sdk` (the real folder).
2077       if (NI->ends_with(".sdk") && DI->ends_with(".sdk")) {
2078         StringRef NBasename = path::stem(*NI);
2079         StringRef DBasename = path::stem(*DI);
2080         if (DBasename.starts_with(NBasename))
2081           continue;
2082       }
2083 
2084       if (*NI != *DI)
2085         break;
2086     }
2087     return false;
2088   };
2089 
2090   bool BestPrefixIsFramework = false;
2091   for (const DirectoryLookup &DL : search_dir_range()) {
2092     if (DL.isNormalDir()) {
2093       StringRef Dir = DL.getDirRef()->getName();
2094       if (CheckDir(Dir)) {
2095         if (IsAngled)
2096           *IsAngled = BestPrefixLength && isSystem(DL.getDirCharacteristic());
2097         BestPrefixIsFramework = false;
2098       }
2099     } else if (DL.isFramework()) {
2100       StringRef Dir = DL.getFrameworkDirRef()->getName();
2101       if (CheckDir(Dir)) {
2102         // Framework includes by convention use <>.
2103         if (IsAngled)
2104           *IsAngled = BestPrefixLength;
2105         BestPrefixIsFramework = true;
2106       }
2107     }
2108   }
2109 
2110   // Try to shorten include path using TUs directory, if we couldn't find any
2111   // suitable prefix in include search paths.
2112   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {
2113     if (IsAngled)
2114       *IsAngled = false;
2115     BestPrefixIsFramework = false;
2116   }
2117 
2118   // Try resolving resulting filename via reverse search in header maps,
2119   // key from header name is user preferred name for the include file.
2120   StringRef Filename = File.drop_front(BestPrefixLength);
2121   for (const DirectoryLookup &DL : search_dir_range()) {
2122     if (!DL.isHeaderMap())
2123       continue;
2124 
2125     StringRef SpelledFilename =
2126         DL.getHeaderMap()->reverseLookupFilename(Filename);
2127     if (!SpelledFilename.empty()) {
2128       Filename = SpelledFilename;
2129       BestPrefixIsFramework = false;
2130       break;
2131     }
2132   }
2133 
2134   // If the best prefix is a framework path, we need to compute the proper
2135   // include spelling for the framework header.
2136   bool IsPrivateHeader;
2137   SmallString<128> FrameworkName, IncludeSpelling;
2138   if (BestPrefixIsFramework &&
2139       isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,
2140                            IncludeSpelling)) {
2141     Filename = IncludeSpelling;
2142   }
2143   return path::convert_to_slash(Filename);
2144 }
2145