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