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