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