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