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