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