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