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