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