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     if (CacheLookup.HitIt)
980       It = CacheLookup.HitIt;
981     if (CacheLookup.MappedName) {
982       Filename = CacheLookup.MappedName;
983       if (IsMapped)
984         *IsMapped = true;
985     }
986   } else {
987     // Otherwise, this is the first query, or the previous query didn't match
988     // our search start.  We will fill in our found location below, so prime the
989     // start point value.
990     CacheLookup.reset(/*NewStartIt=*/NextIt);
991   }
992 
993   SmallString<64> MappedName;
994 
995   // Check each directory in sequence to see if it contains this file.
996   for (; It != search_dir_end(); ++It) {
997     bool InUserSpecifiedSystemFramework = false;
998     bool IsInHeaderMap = false;
999     bool IsFrameworkFoundInDir = false;
1000     Optional<FileEntryRef> File = It->LookupFile(
1001         Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
1002         SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
1003         IsInHeaderMap, MappedName);
1004     if (!MappedName.empty()) {
1005       assert(IsInHeaderMap && "MappedName should come from a header map");
1006       CacheLookup.MappedName =
1007           copyString(MappedName, LookupFileCache.getAllocator());
1008     }
1009     if (IsMapped)
1010       // A filename is mapped when a header map remapped it to a relative path
1011       // used in subsequent header search or to an absolute path pointing to an
1012       // existing file.
1013       *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
1014     if (IsFrameworkFound)
1015       // Because we keep a filename remapped for subsequent search directory
1016       // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
1017       // just for remapping in a current search directory.
1018       *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
1019     if (!File)
1020       continue;
1021 
1022     CurDir = It;
1023 
1024     // This file is a system header or C++ unfriendly if the dir is.
1025     HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry());
1026     HFI.DirInfo = CurDir->getDirCharacteristic();
1027 
1028     // If the directory characteristic is User but this framework was
1029     // user-specified to be treated as a system framework, promote the
1030     // characteristic.
1031     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
1032       HFI.DirInfo = SrcMgr::C_System;
1033 
1034     // If the filename matches a known system header prefix, override
1035     // whether the file is a system header.
1036     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
1037       if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
1038         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
1039                                                        : SrcMgr::C_User;
1040         break;
1041       }
1042     }
1043 
1044     // Set the `Framework` info if this file is in a header map with framework
1045     // style include spelling or found in a framework dir. The header map case
1046     // is possible when building frameworks which use header maps.
1047     if (CurDir->isHeaderMap() && isAngled) {
1048       size_t SlashPos = Filename.find('/');
1049       if (SlashPos != StringRef::npos)
1050         HFI.Framework =
1051             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1052       if (CurDir->isIndexHeaderMap())
1053         HFI.IndexHeaderMapHeader = 1;
1054     } else if (CurDir->isFramework()) {
1055       size_t SlashPos = Filename.find('/');
1056       if (SlashPos != StringRef::npos)
1057         HFI.Framework =
1058             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1059     }
1060 
1061     if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1062                               &File->getFileEntry(), IncludeLoc)) {
1063       if (SuggestedModule)
1064         *SuggestedModule = MSSuggestedModule;
1065       return MSFE;
1066     }
1067 
1068     bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
1069     if (!Includers.empty())
1070       diagnoseFrameworkInclude(
1071           Diags, IncludeLoc, Includers.front().second->getName(), Filename,
1072           &File->getFileEntry(), isAngled, FoundByHeaderMap);
1073 
1074     // Remember this location for the next lookup we do.
1075     cacheLookupSuccess(CacheLookup, It, IncludeLoc);
1076     return File;
1077   }
1078 
1079   // If we are including a file with a quoted include "foo.h" from inside
1080   // a header in a framework that is currently being built, and we couldn't
1081   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1082   // "Foo" is the name of the framework in which the including header was found.
1083   if (!Includers.empty() && Includers.front().first && !isAngled &&
1084       !Filename.contains('/')) {
1085     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
1086     if (IncludingHFI.IndexHeaderMapHeader) {
1087       SmallString<128> ScratchFilename;
1088       ScratchFilename += IncludingHFI.Framework;
1089       ScratchFilename += '/';
1090       ScratchFilename += Filename;
1091 
1092       Optional<FileEntryRef> File = LookupFile(
1093           ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir,
1094           Includers.front(), SearchPath, RelativePath, RequestingModule,
1095           SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
1096 
1097       if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1098                                 File ? &File->getFileEntry() : nullptr,
1099                                 IncludeLoc)) {
1100         if (SuggestedModule)
1101           *SuggestedModule = MSSuggestedModule;
1102         return MSFE;
1103       }
1104 
1105       cacheLookupSuccess(LookupFileCache[Filename],
1106                          LookupFileCache[ScratchFilename].HitIt, IncludeLoc);
1107       // FIXME: SuggestedModule.
1108       return File;
1109     }
1110   }
1111 
1112   if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1113                             nullptr, IncludeLoc)) {
1114     if (SuggestedModule)
1115       *SuggestedModule = MSSuggestedModule;
1116     return MSFE;
1117   }
1118 
1119   // Otherwise, didn't find it. Remember we didn't find this.
1120   CacheLookup.HitIt = search_dir_end();
1121   return None;
1122 }
1123 
1124 /// LookupSubframeworkHeader - Look up a subframework for the specified
1125 /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1126 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1127 /// is a subframework within Carbon.framework.  If so, return the FileEntry
1128 /// for the designated file, otherwise return null.
1129 Optional<FileEntryRef> HeaderSearch::LookupSubframeworkHeader(
1130     StringRef Filename, const FileEntry *ContextFileEnt,
1131     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1132     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
1133   assert(ContextFileEnt && "No context file?");
1134 
1135   // Framework names must have a '/' in the filename.  Find it.
1136   // FIXME: Should we permit '\' on Windows?
1137   size_t SlashPos = Filename.find('/');
1138   if (SlashPos == StringRef::npos)
1139     return None;
1140 
1141   // Look up the base framework name of the ContextFileEnt.
1142   StringRef ContextName = ContextFileEnt->getName();
1143 
1144   // If the context info wasn't a framework, couldn't be a subframework.
1145   const unsigned DotFrameworkLen = 10;
1146   auto FrameworkPos = ContextName.find(".framework");
1147   if (FrameworkPos == StringRef::npos ||
1148       (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1149        ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1150     return None;
1151 
1152   SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1153                                                           FrameworkPos +
1154                                                           DotFrameworkLen + 1);
1155 
1156   // Append Frameworks/HIToolbox.framework/
1157   FrameworkName += "Frameworks/";
1158   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1159   FrameworkName += ".framework/";
1160 
1161   auto &CacheLookup =
1162       *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1163                                           FrameworkCacheEntry())).first;
1164 
1165   // Some other location?
1166   if (CacheLookup.second.Directory &&
1167       CacheLookup.first().size() == FrameworkName.size() &&
1168       memcmp(CacheLookup.first().data(), &FrameworkName[0],
1169              CacheLookup.first().size()) != 0)
1170     return None;
1171 
1172   // Cache subframework.
1173   if (!CacheLookup.second.Directory) {
1174     ++NumSubFrameworkLookups;
1175 
1176     // If the framework dir doesn't exist, we fail.
1177     auto Dir = FileMgr.getDirectory(FrameworkName);
1178     if (!Dir)
1179       return None;
1180 
1181     // Otherwise, if it does, remember that this is the right direntry for this
1182     // framework.
1183     CacheLookup.second.Directory = *Dir;
1184   }
1185 
1186 
1187   if (RelativePath) {
1188     RelativePath->clear();
1189     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1190   }
1191 
1192   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1193   SmallString<1024> HeadersFilename(FrameworkName);
1194   HeadersFilename += "Headers/";
1195   if (SearchPath) {
1196     SearchPath->clear();
1197     // Without trailing '/'.
1198     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1199   }
1200 
1201   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1202   auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1203   if (!File) {
1204     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1205     HeadersFilename = FrameworkName;
1206     HeadersFilename += "PrivateHeaders/";
1207     if (SearchPath) {
1208       SearchPath->clear();
1209       // Without trailing '/'.
1210       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1211     }
1212 
1213     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1214     File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1215 
1216     if (!File)
1217       return None;
1218   }
1219 
1220   // This file is a system header or C++ unfriendly if the old file is.
1221   //
1222   // Note that the temporary 'DirInfo' is required here, as either call to
1223   // getFileInfo could resize the vector and we don't want to rely on order
1224   // of evaluation.
1225   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1226   getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
1227 
1228   FrameworkName.pop_back(); // remove the trailing '/'
1229   if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName,
1230                                           RequestingModule, SuggestedModule,
1231                                           /*IsSystem*/ false))
1232     return None;
1233 
1234   return *File;
1235 }
1236 
1237 //===----------------------------------------------------------------------===//
1238 // File Info Management.
1239 //===----------------------------------------------------------------------===//
1240 
1241 /// Merge the header file info provided by \p OtherHFI into the current
1242 /// header file info (\p HFI)
1243 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1244                                 const HeaderFileInfo &OtherHFI) {
1245   assert(OtherHFI.External && "expected to merge external HFI");
1246 
1247   HFI.isImport |= OtherHFI.isImport;
1248   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1249   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1250 
1251   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1252     HFI.ControllingMacro = OtherHFI.ControllingMacro;
1253     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1254   }
1255 
1256   HFI.DirInfo = OtherHFI.DirInfo;
1257   HFI.External = (!HFI.IsValid || HFI.External);
1258   HFI.IsValid = true;
1259   HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1260 
1261   if (HFI.Framework.empty())
1262     HFI.Framework = OtherHFI.Framework;
1263 }
1264 
1265 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1266 /// FileEntry.
1267 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1268   if (FE->getUID() >= FileInfo.size())
1269     FileInfo.resize(FE->getUID() + 1);
1270 
1271   HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1272   // FIXME: Use a generation count to check whether this is really up to date.
1273   if (ExternalSource && !HFI->Resolved) {
1274     auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1275     if (ExternalHFI.IsValid) {
1276       HFI->Resolved = true;
1277       if (ExternalHFI.External)
1278         mergeHeaderFileInfo(*HFI, ExternalHFI);
1279     }
1280   }
1281 
1282   HFI->IsValid = true;
1283   // We have local information about this header file, so it's no longer
1284   // strictly external.
1285   HFI->External = false;
1286   return *HFI;
1287 }
1288 
1289 const HeaderFileInfo *
1290 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1291                                   bool WantExternal) const {
1292   // If we have an external source, ensure we have the latest information.
1293   // FIXME: Use a generation count to check whether this is really up to date.
1294   HeaderFileInfo *HFI;
1295   if (ExternalSource) {
1296     if (FE->getUID() >= FileInfo.size()) {
1297       if (!WantExternal)
1298         return nullptr;
1299       FileInfo.resize(FE->getUID() + 1);
1300     }
1301 
1302     HFI = &FileInfo[FE->getUID()];
1303     if (!WantExternal && (!HFI->IsValid || HFI->External))
1304       return nullptr;
1305     if (!HFI->Resolved) {
1306       auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1307       if (ExternalHFI.IsValid) {
1308         HFI->Resolved = true;
1309         if (ExternalHFI.External)
1310           mergeHeaderFileInfo(*HFI, ExternalHFI);
1311       }
1312     }
1313   } else if (FE->getUID() >= FileInfo.size()) {
1314     return nullptr;
1315   } else {
1316     HFI = &FileInfo[FE->getUID()];
1317   }
1318 
1319   if (!HFI->IsValid || (HFI->External && !WantExternal))
1320     return nullptr;
1321 
1322   return HFI;
1323 }
1324 
1325 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1326   // Check if we've entered this file and found an include guard or #pragma
1327   // once. Note that we dor't check for #import, because that's not a property
1328   // of the file itself.
1329   if (auto *HFI = getExistingFileInfo(File))
1330     return HFI->isPragmaOnce || HFI->ControllingMacro ||
1331            HFI->ControllingMacroID;
1332   return false;
1333 }
1334 
1335 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1336                                         ModuleMap::ModuleHeaderRole Role,
1337                                         bool isCompilingModuleHeader) {
1338   bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1339 
1340   // Don't mark the file info as non-external if there's nothing to change.
1341   if (!isCompilingModuleHeader) {
1342     if (!isModularHeader)
1343       return;
1344     auto *HFI = getExistingFileInfo(FE);
1345     if (HFI && HFI->isModuleHeader)
1346       return;
1347   }
1348 
1349   auto &HFI = getFileInfo(FE);
1350   HFI.isModuleHeader |= isModularHeader;
1351   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1352 }
1353 
1354 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1355                                           const FileEntry *File, bool isImport,
1356                                           bool ModulesEnabled, Module *M,
1357                                           bool &IsFirstIncludeOfFile) {
1358   ++NumIncluded; // Count # of attempted #includes.
1359 
1360   IsFirstIncludeOfFile = false;
1361 
1362   // Get information about this file.
1363   HeaderFileInfo &FileInfo = getFileInfo(File);
1364 
1365   // FIXME: this is a workaround for the lack of proper modules-aware support
1366   // for #import / #pragma once
1367   auto TryEnterImported = [&]() -> bool {
1368     if (!ModulesEnabled)
1369       return false;
1370     // Ensure FileInfo bits are up to date.
1371     ModMap.resolveHeaderDirectives(File);
1372     // Modules with builtins are special; multiple modules use builtins as
1373     // modular headers, example:
1374     //
1375     //    module stddef { header "stddef.h" export * }
1376     //
1377     // After module map parsing, this expands to:
1378     //
1379     //    module stddef {
1380     //      header "/path_to_builtin_dirs/stddef.h"
1381     //      textual "stddef.h"
1382     //    }
1383     //
1384     // It's common that libc++ and system modules will both define such
1385     // submodules. Make sure cached results for a builtin header won't
1386     // prevent other builtin modules from potentially entering the builtin
1387     // header. Note that builtins are header guarded and the decision to
1388     // actually enter them is postponed to the controlling macros logic below.
1389     bool TryEnterHdr = false;
1390     if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1391       TryEnterHdr = ModMap.isBuiltinHeader(File);
1392 
1393     // Textual headers can be #imported from different modules. Since ObjC
1394     // headers find in the wild might rely only on #import and do not contain
1395     // controlling macros, be conservative and only try to enter textual headers
1396     // if such macro is present.
1397     if (!FileInfo.isModuleHeader &&
1398         FileInfo.getControllingMacro(ExternalLookup))
1399       TryEnterHdr = true;
1400     return TryEnterHdr;
1401   };
1402 
1403   // If this is a #import directive, check that we have not already imported
1404   // this header.
1405   if (isImport) {
1406     // If this has already been imported, don't import it again.
1407     FileInfo.isImport = true;
1408 
1409     // Has this already been #import'ed or #include'd?
1410     if (PP.alreadyIncluded(File) && !TryEnterImported())
1411       return false;
1412   } else {
1413     // Otherwise, if this is a #include of a file that was previously #import'd
1414     // or if this is the second #include of a #pragma once file, ignore it.
1415     if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported())
1416       return false;
1417   }
1418 
1419   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
1420   // if the macro that guards it is defined, we know the #include has no effect.
1421   if (const IdentifierInfo *ControllingMacro
1422       = FileInfo.getControllingMacro(ExternalLookup)) {
1423     // If the header corresponds to a module, check whether the macro is already
1424     // defined in that module rather than checking in the current set of visible
1425     // modules.
1426     if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1427           : PP.isMacroDefined(ControllingMacro)) {
1428       ++NumMultiIncludeFileOptzn;
1429       return false;
1430     }
1431   }
1432 
1433   IsFirstIncludeOfFile = PP.markIncluded(File);
1434 
1435   return true;
1436 }
1437 
1438 size_t HeaderSearch::getTotalMemory() const {
1439   return SearchDirs.capacity()
1440     + llvm::capacity_in_bytes(FileInfo)
1441     + llvm::capacity_in_bytes(HeaderMaps)
1442     + LookupFileCache.getAllocator().getTotalMemory()
1443     + FrameworkMap.getAllocator().getTotalMemory();
1444 }
1445 
1446 unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const {
1447   return &DL - &*SearchDirs.begin();
1448 }
1449 
1450 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1451   return FrameworkNames.insert(Framework).first->first();
1452 }
1453 
1454 bool HeaderSearch::hasModuleMap(StringRef FileName,
1455                                 const DirectoryEntry *Root,
1456                                 bool IsSystem) {
1457   if (!HSOpts->ImplicitModuleMaps)
1458     return false;
1459 
1460   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1461 
1462   StringRef DirName = FileName;
1463   do {
1464     // Get the parent directory name.
1465     DirName = llvm::sys::path::parent_path(DirName);
1466     if (DirName.empty())
1467       return false;
1468 
1469     // Determine whether this directory exists.
1470     auto Dir = FileMgr.getDirectory(DirName);
1471     if (!Dir)
1472       return false;
1473 
1474     // Try to load the module map file in this directory.
1475     switch (loadModuleMapFile(*Dir, IsSystem,
1476                               llvm::sys::path::extension((*Dir)->getName()) ==
1477                                   ".framework")) {
1478     case LMM_NewlyLoaded:
1479     case LMM_AlreadyLoaded:
1480       // Success. All of the directories we stepped through inherit this module
1481       // map file.
1482       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1483         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1484       return true;
1485 
1486     case LMM_NoDirectory:
1487     case LMM_InvalidModuleMap:
1488       break;
1489     }
1490 
1491     // If we hit the top of our search, we're done.
1492     if (*Dir == Root)
1493       return false;
1494 
1495     // Keep track of all of the directories we checked, so we can mark them as
1496     // having module maps if we eventually do find a module map.
1497     FixUpDirectories.push_back(*Dir);
1498   } while (true);
1499 }
1500 
1501 ModuleMap::KnownHeader
1502 HeaderSearch::findModuleForHeader(const FileEntry *File,
1503                                   bool AllowTextual) const {
1504   if (ExternalSource) {
1505     // Make sure the external source has handled header info about this file,
1506     // which includes whether the file is part of a module.
1507     (void)getExistingFileInfo(File);
1508   }
1509   return ModMap.findModuleForHeader(File, AllowTextual);
1510 }
1511 
1512 ArrayRef<ModuleMap::KnownHeader>
1513 HeaderSearch::findAllModulesForHeader(const FileEntry *File) const {
1514   if (ExternalSource) {
1515     // Make sure the external source has handled header info about this file,
1516     // which includes whether the file is part of a module.
1517     (void)getExistingFileInfo(File);
1518   }
1519   return ModMap.findAllModulesForHeader(File);
1520 }
1521 
1522 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1523                           Module *RequestingModule,
1524                           ModuleMap::KnownHeader *SuggestedModule) {
1525   ModuleMap::KnownHeader Module =
1526       HS.findModuleForHeader(File, /*AllowTextual*/true);
1527 
1528   // If this module specifies [no_undeclared_includes], we cannot find any
1529   // file that's in a non-dependency module.
1530   if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1531     HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);
1532     if (!RequestingModule->directlyUses(Module.getModule())) {
1533       // Builtin headers are a special case. Multiple modules can use the same
1534       // builtin as a modular header (see also comment in
1535       // ShouldEnterIncludeFile()), so the builtin header may have been
1536       // "claimed" by an unrelated module. This shouldn't prevent us from
1537       // including the builtin header textually in this module.
1538       if (HS.getModuleMap().isBuiltinHeader(File)) {
1539         if (SuggestedModule)
1540           *SuggestedModule = ModuleMap::KnownHeader();
1541         return true;
1542       }
1543       return false;
1544     }
1545   }
1546 
1547   if (SuggestedModule)
1548     *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1549                            ? ModuleMap::KnownHeader()
1550                            : Module;
1551 
1552   return true;
1553 }
1554 
1555 bool HeaderSearch::findUsableModuleForHeader(
1556     const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1557     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1558   if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1559     // If there is a module that corresponds to this header, suggest it.
1560     hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1561     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1562   }
1563   return true;
1564 }
1565 
1566 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1567     const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1568     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1569   // If we're supposed to suggest a module, look for one now.
1570   if (needModuleLookup(RequestingModule, SuggestedModule)) {
1571     // Find the top-level framework based on this framework.
1572     SmallVector<std::string, 4> SubmodulePath;
1573     const DirectoryEntry *TopFrameworkDir
1574       = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1575 
1576     // Determine the name of the top-level framework.
1577     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1578 
1579     // Load this framework module. If that succeeds, find the suggested module
1580     // for this header, if any.
1581     loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1582 
1583     // FIXME: This can find a module not part of ModuleName, which is
1584     // important so that we're consistent about whether this header
1585     // corresponds to a module. Possibly we should lock down framework modules
1586     // so that this is not possible.
1587     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1588   }
1589   return true;
1590 }
1591 
1592 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1593                                             FileManager &FileMgr) {
1594   StringRef Filename = llvm::sys::path::filename(File->getName());
1595   SmallString<128>  PrivateFilename(File->getDir()->getName());
1596   if (Filename == "module.map")
1597     llvm::sys::path::append(PrivateFilename, "module_private.map");
1598   else if (Filename == "module.modulemap")
1599     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1600   else
1601     return nullptr;
1602   if (auto File = FileMgr.getFile(PrivateFilename))
1603     return *File;
1604   return nullptr;
1605 }
1606 
1607 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
1608                                      FileID ID, unsigned *Offset,
1609                                      StringRef OriginalModuleMapFile) {
1610   // Find the directory for the module. For frameworks, that may require going
1611   // up from the 'Modules' directory.
1612   const DirectoryEntry *Dir = nullptr;
1613   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1614     if (auto DirOrErr = FileMgr.getDirectory("."))
1615       Dir = *DirOrErr;
1616   } else {
1617     if (!OriginalModuleMapFile.empty()) {
1618       // We're building a preprocessed module map. Find or invent the directory
1619       // that it originally occupied.
1620       auto DirOrErr = FileMgr.getDirectory(
1621           llvm::sys::path::parent_path(OriginalModuleMapFile));
1622       if (DirOrErr) {
1623         Dir = *DirOrErr;
1624       } else {
1625         auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1626         Dir = FakeFile->getDir();
1627       }
1628     } else {
1629       Dir = File->getDir();
1630     }
1631 
1632     StringRef DirName(Dir->getName());
1633     if (llvm::sys::path::filename(DirName) == "Modules") {
1634       DirName = llvm::sys::path::parent_path(DirName);
1635       if (DirName.endswith(".framework"))
1636         if (auto DirOrErr = FileMgr.getDirectory(DirName))
1637           Dir = *DirOrErr;
1638       // FIXME: This assert can fail if there's a race between the above check
1639       // and the removal of the directory.
1640       assert(Dir && "parent must exist");
1641     }
1642   }
1643 
1644   switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
1645   case LMM_AlreadyLoaded:
1646   case LMM_NewlyLoaded:
1647     return false;
1648   case LMM_NoDirectory:
1649   case LMM_InvalidModuleMap:
1650     return true;
1651   }
1652   llvm_unreachable("Unknown load module map result");
1653 }
1654 
1655 HeaderSearch::LoadModuleMapResult
1656 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1657                                     const DirectoryEntry *Dir, FileID ID,
1658                                     unsigned *Offset) {
1659   assert(File && "expected FileEntry");
1660 
1661   // Check whether we've already loaded this module map, and mark it as being
1662   // loaded in case we recursively try to load it from itself.
1663   auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1664   if (!AddResult.second)
1665     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1666 
1667   if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1668     LoadedModuleMaps[File] = false;
1669     return LMM_InvalidModuleMap;
1670   }
1671 
1672   // Try to load a corresponding private module map.
1673   if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1674     if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1675       LoadedModuleMaps[File] = false;
1676       return LMM_InvalidModuleMap;
1677     }
1678   }
1679 
1680   // This directory has a module map.
1681   return LMM_NewlyLoaded;
1682 }
1683 
1684 const FileEntry *
1685 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1686   if (!HSOpts->ImplicitModuleMaps)
1687     return nullptr;
1688   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1689   // module.map at the framework root is also accepted.
1690   SmallString<128> ModuleMapFileName(Dir->getName());
1691   if (IsFramework)
1692     llvm::sys::path::append(ModuleMapFileName, "Modules");
1693   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1694   if (auto F = FileMgr.getFile(ModuleMapFileName))
1695     return *F;
1696 
1697   // Continue to allow module.map
1698   ModuleMapFileName = Dir->getName();
1699   llvm::sys::path::append(ModuleMapFileName, "module.map");
1700   if (auto F = FileMgr.getFile(ModuleMapFileName))
1701     return *F;
1702 
1703   // For frameworks, allow to have a private module map with a preferred
1704   // spelling when a public module map is absent.
1705   if (IsFramework) {
1706     ModuleMapFileName = Dir->getName();
1707     llvm::sys::path::append(ModuleMapFileName, "Modules",
1708                             "module.private.modulemap");
1709     if (auto F = FileMgr.getFile(ModuleMapFileName))
1710       return *F;
1711   }
1712   return nullptr;
1713 }
1714 
1715 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1716                                           const DirectoryEntry *Dir,
1717                                           bool IsSystem) {
1718   if (Module *Module = ModMap.findModule(Name))
1719     return Module;
1720 
1721   // Try to load a module map file.
1722   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1723   case LMM_InvalidModuleMap:
1724     // Try to infer a module map from the framework directory.
1725     if (HSOpts->ImplicitModuleMaps)
1726       ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1727     break;
1728 
1729   case LMM_AlreadyLoaded:
1730   case LMM_NoDirectory:
1731     return nullptr;
1732 
1733   case LMM_NewlyLoaded:
1734     break;
1735   }
1736 
1737   return ModMap.findModule(Name);
1738 }
1739 
1740 HeaderSearch::LoadModuleMapResult
1741 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1742                                 bool IsFramework) {
1743   if (auto Dir = FileMgr.getDirectory(DirName))
1744     return loadModuleMapFile(*Dir, IsSystem, IsFramework);
1745 
1746   return LMM_NoDirectory;
1747 }
1748 
1749 HeaderSearch::LoadModuleMapResult
1750 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1751                                 bool IsFramework) {
1752   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1753   if (KnownDir != DirectoryHasModuleMap.end())
1754     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1755 
1756   if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1757     LoadModuleMapResult Result =
1758         loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1759     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1760     // E.g. Foo.framework/Modules/module.modulemap
1761     //      ^Dir                  ^ModuleMapFile
1762     if (Result == LMM_NewlyLoaded)
1763       DirectoryHasModuleMap[Dir] = true;
1764     else if (Result == LMM_InvalidModuleMap)
1765       DirectoryHasModuleMap[Dir] = false;
1766     return Result;
1767   }
1768   return LMM_InvalidModuleMap;
1769 }
1770 
1771 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1772   Modules.clear();
1773 
1774   if (HSOpts->ImplicitModuleMaps) {
1775     // Load module maps for each of the header search directories.
1776     for (DirectoryLookup &DL : search_dir_range()) {
1777       bool IsSystem = DL.isSystemHeaderDirectory();
1778       if (DL.isFramework()) {
1779         std::error_code EC;
1780         SmallString<128> DirNative;
1781         llvm::sys::path::native(DL.getFrameworkDir()->getName(), DirNative);
1782 
1783         // Search each of the ".framework" directories to load them as modules.
1784         llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1785         for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1786                                            DirEnd;
1787              Dir != DirEnd && !EC; Dir.increment(EC)) {
1788           if (llvm::sys::path::extension(Dir->path()) != ".framework")
1789             continue;
1790 
1791           auto FrameworkDir =
1792               FileMgr.getDirectory(Dir->path());
1793           if (!FrameworkDir)
1794             continue;
1795 
1796           // Load this framework module.
1797           loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
1798                               IsSystem);
1799         }
1800         continue;
1801       }
1802 
1803       // FIXME: Deal with header maps.
1804       if (DL.isHeaderMap())
1805         continue;
1806 
1807       // Try to load a module map file for the search directory.
1808       loadModuleMapFile(DL.getDir(), IsSystem, /*IsFramework*/ false);
1809 
1810       // Try to load module map files for immediate subdirectories of this
1811       // search directory.
1812       loadSubdirectoryModuleMaps(DL);
1813     }
1814   }
1815 
1816   // Populate the list of modules.
1817   llvm::transform(ModMap.modules(), std::back_inserter(Modules),
1818                   [](const auto &NameAndMod) { return NameAndMod.second; });
1819 }
1820 
1821 void HeaderSearch::loadTopLevelSystemModules() {
1822   if (!HSOpts->ImplicitModuleMaps)
1823     return;
1824 
1825   // Load module maps for each of the header search directories.
1826   for (const DirectoryLookup &DL : search_dir_range()) {
1827     // We only care about normal header directories.
1828     if (!DL.isNormalDir())
1829       continue;
1830 
1831     // Try to load a module map file for the search directory.
1832     loadModuleMapFile(DL.getDir(), DL.isSystemHeaderDirectory(),
1833                       DL.isFramework());
1834   }
1835 }
1836 
1837 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1838   assert(HSOpts->ImplicitModuleMaps &&
1839          "Should not be loading subdirectory module maps");
1840 
1841   if (SearchDir.haveSearchedAllModuleMaps())
1842     return;
1843 
1844   std::error_code EC;
1845   SmallString<128> Dir = SearchDir.getDir()->getName();
1846   FileMgr.makeAbsolutePath(Dir);
1847   SmallString<128> DirNative;
1848   llvm::sys::path::native(Dir, DirNative);
1849   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1850   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1851        Dir != DirEnd && !EC; Dir.increment(EC)) {
1852     bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1853     if (IsFramework == SearchDir.isFramework())
1854       loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1855                         SearchDir.isFramework());
1856   }
1857 
1858   SearchDir.setSearchedAllModuleMaps(true);
1859 }
1860 
1861 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1862     const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
1863   // FIXME: We assume that the path name currently cached in the FileEntry is
1864   // the most appropriate one for this analysis (and that it's spelled the
1865   // same way as the corresponding header search path).
1866   return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1867                                          MainFile, IsSystem);
1868 }
1869 
1870 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1871     llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1872     bool *IsSystem) {
1873   using namespace llvm::sys;
1874 
1875   unsigned BestPrefixLength = 0;
1876   // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
1877   // the longest prefix we've seen so for it, returns true and updates the
1878   // `BestPrefixLength` accordingly.
1879   auto CheckDir = [&](llvm::StringRef Dir) -> bool {
1880     llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
1881     if (!WorkingDir.empty() && !path::is_absolute(Dir))
1882       fs::make_absolute(WorkingDir, DirPath);
1883     path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1884     Dir = DirPath;
1885     for (auto NI = path::begin(File), NE = path::end(File),
1886               DI = path::begin(Dir), DE = path::end(Dir);
1887          /*termination condition in loop*/; ++NI, ++DI) {
1888       // '.' components in File are ignored.
1889       while (NI != NE && *NI == ".")
1890         ++NI;
1891       if (NI == NE)
1892         break;
1893 
1894       // '.' components in Dir are ignored.
1895       while (DI != DE && *DI == ".")
1896         ++DI;
1897       if (DI == DE) {
1898         // Dir is a prefix of File, up to '.' components and choice of path
1899         // separators.
1900         unsigned PrefixLength = NI - path::begin(File);
1901         if (PrefixLength > BestPrefixLength) {
1902           BestPrefixLength = PrefixLength;
1903           return true;
1904         }
1905         break;
1906       }
1907 
1908       // Consider all path separators equal.
1909       if (NI->size() == 1 && DI->size() == 1 &&
1910           path::is_separator(NI->front()) && path::is_separator(DI->front()))
1911         continue;
1912 
1913       // Special case Apple .sdk folders since the search path is typically a
1914       // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
1915       // located in `iPhoneSimulator.sdk` (the real folder).
1916       if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
1917         StringRef NBasename = path::stem(*NI);
1918         StringRef DBasename = path::stem(*DI);
1919         if (DBasename.startswith(NBasename))
1920           continue;
1921       }
1922 
1923       if (*NI != *DI)
1924         break;
1925     }
1926     return false;
1927   };
1928 
1929   bool BestPrefixIsFramework = false;
1930   for (const DirectoryLookup &DL : search_dir_range()) {
1931     if (DL.isNormalDir()) {
1932       StringRef Dir = DL.getDir()->getName();
1933       if (CheckDir(Dir)) {
1934         if (IsSystem)
1935           *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
1936         BestPrefixIsFramework = false;
1937       }
1938     } else if (DL.isFramework()) {
1939       StringRef Dir = DL.getFrameworkDir()->getName();
1940       if (CheckDir(Dir)) {
1941         if (IsSystem)
1942           *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
1943         BestPrefixIsFramework = true;
1944       }
1945     }
1946   }
1947 
1948   // Try to shorten include path using TUs directory, if we couldn't find any
1949   // suitable prefix in include search paths.
1950   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {
1951     if (IsSystem)
1952       *IsSystem = false;
1953     BestPrefixIsFramework = false;
1954   }
1955 
1956   // Try resolving resulting filename via reverse search in header maps,
1957   // key from header name is user prefered name for the include file.
1958   StringRef Filename = File.drop_front(BestPrefixLength);
1959   for (const DirectoryLookup &DL : search_dir_range()) {
1960     if (!DL.isHeaderMap())
1961       continue;
1962 
1963     StringRef SpelledFilename =
1964         DL.getHeaderMap()->reverseLookupFilename(Filename);
1965     if (!SpelledFilename.empty()) {
1966       Filename = SpelledFilename;
1967       BestPrefixIsFramework = false;
1968       break;
1969     }
1970   }
1971 
1972   // If the best prefix is a framework path, we need to compute the proper
1973   // include spelling for the framework header.
1974   bool IsPrivateHeader;
1975   SmallString<128> FrameworkName, IncludeSpelling;
1976   if (BestPrefixIsFramework &&
1977       isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,
1978                            IncludeSpelling)) {
1979     Filename = IncludeSpelling;
1980   }
1981   return path::convert_to_slash(Filename);
1982 }
1983