1 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the DirectoryLookup and HeaderSearch interfaces.
12 //===----------------------------------------------------------------------===//
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"
31 #if defined(LLVM_ON_UNIX)
34 using namespace clang;
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));
45 return ControllingMacro;
48 if (!ControllingMacroID || !External)
51 ControllingMacro = External->GetIdentifier(ControllingMacroID);
52 return ControllingMacro;
55 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
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) {
66 NoCurDirSearch = false;
68 ExternalLookup = nullptr;
69 ExternalSource = nullptr;
71 NumMultiIncludeFileOptzn = 0;
72 NumFrameworkLookups = NumSubFrameworkLookups = 0;
75 HeaderSearch::~HeaderSearch() {
77 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
78 delete HeaderMaps[i].second;
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;
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);
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);
99 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
100 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
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;
116 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
117 HeaderMaps.push_back(std::make_pair(FE, HM));
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());
131 std::string HeaderSearch::getModuleFileName(Module *Module) {
132 const FileEntry *ModuleMap =
133 getModuleMap().getModuleMapFileForUniquing(Module);
134 return getModuleFileName(Module->Name, ModuleMap->getName(),
135 /*UsePrebuiltPath*/false);
138 std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
139 StringRef ModuleMapPath,
140 bool UsePrebuiltPath) {
141 if (UsePrebuiltPath) {
142 if (HSOpts->PrebuiltModulePaths.empty())
143 return std::string();
145 // Go though each prebuilt module path and try to find the pcm file.
146 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
147 SmallString<256> Result(Dir);
148 llvm::sys::fs::make_absolute(Result);
150 llvm::sys::path::append(Result, ModuleName + ".pcm");
151 if (getFileMgr().getFile(Result.str()))
152 return Result.str().str();
154 return std::string();
157 // If we don't have a module cache path or aren't supposed to use one, we
158 // can't do anything.
159 if (getModuleCachePath().empty())
160 return std::string();
162 SmallString<256> Result(getModuleCachePath());
163 llvm::sys::fs::make_absolute(Result);
165 if (HSOpts->DisableModuleHash) {
166 llvm::sys::path::append(Result, ModuleName + ".pcm");
168 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
169 // ideally be globally unique to this particular module. Name collisions
170 // in the hash are safe (because any translation unit can only import one
171 // module with each name), but result in a loss of caching.
173 // To avoid false-negatives, we form as canonical a path as we can, and map
174 // to lower-case in case we're on a case-insensitive file system.
175 std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
178 auto *Dir = FileMgr.getDirectory(Parent);
180 return std::string();
181 auto DirName = FileMgr.getCanonicalName(Dir);
182 auto FileName = llvm::sys::path::filename(ModuleMapPath);
184 llvm::hash_code Hash =
185 llvm::hash_combine(DirName.lower(), FileName.lower());
187 SmallString<128> HashStr;
188 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
189 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
191 return Result.str().str();
194 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
195 // Look in the module map to determine if there is a module by this name.
196 Module *Module = ModMap.findModule(ModuleName);
197 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
200 StringRef SearchName = ModuleName;
201 Module = lookupModule(ModuleName, SearchName);
203 // The facility for "private modules" -- adjacent, optional module maps named
204 // module.private.modulemap that are supposed to define private submodules --
205 // is sometimes misused by frameworks that name their associated private
206 // module FooPrivate, rather than as a submodule named Foo.Private as
207 // intended. Here we compensate for such cases by looking in directories named
208 // Foo.framework, when we previously looked and failed to find a
209 // FooPrivate.framework.
210 if (!Module && SearchName.consume_back("Private"))
211 Module = lookupModule(ModuleName, SearchName);
215 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName) {
216 Module *Module = nullptr;
218 // Look through the various header search paths to load any available module
219 // maps, searching for a module map that describes this module.
220 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
221 if (SearchDirs[Idx].isFramework()) {
222 // Search for or infer a module map for a framework. Here we use
223 // SearchName rather than ModuleName, to permit finding private modules
224 // named FooPrivate in buggy frameworks named Foo.
225 SmallString<128> FrameworkDirName;
226 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
227 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
228 if (const DirectoryEntry *FrameworkDir
229 = FileMgr.getDirectory(FrameworkDirName)) {
231 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
232 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
238 // FIXME: Figure out how header maps and module maps will work together.
240 // Only deal with normal search directories.
241 if (!SearchDirs[Idx].isNormalDir())
244 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
245 // Search for a module map file in this directory.
246 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
247 /*IsFramework*/false) == LMM_NewlyLoaded) {
248 // We just loaded a module map file; check whether the module is
250 Module = ModMap.findModule(ModuleName);
255 // Search for a module map in a subdirectory with the same name as the
257 SmallString<128> NestedModuleMapDirName;
258 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
259 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
260 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
261 /*IsFramework*/false) == LMM_NewlyLoaded){
262 // If we just loaded a module map file, look for the module again.
263 Module = ModMap.findModule(ModuleName);
268 // If we've already performed the exhaustive search for module maps in this
269 // search directory, don't do it again.
270 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
273 // Load all module maps in the immediate subdirectories of this search
275 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
277 // Look again for the module.
278 Module = ModMap.findModule(ModuleName);
286 //===----------------------------------------------------------------------===//
287 // File lookup within a DirectoryLookup scope
288 //===----------------------------------------------------------------------===//
290 /// getName - Return the directory or filename corresponding to this lookup
292 StringRef DirectoryLookup::getName() const {
294 return getDir()->getName();
296 return getFrameworkDir()->getName();
297 assert(isHeaderMap() && "Unknown DirectoryLookup");
298 return getHeaderMap()->getFileName();
301 const FileEntry *HeaderSearch::getFileAndSuggestModule(
302 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
303 bool IsSystemHeaderDir, Module *RequestingModule,
304 ModuleMap::KnownHeader *SuggestedModule) {
305 // If we have a module map that might map this header, load it and
306 // check whether we'll have a suggestion for a module.
307 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
311 // If there is a module that corresponds to this header, suggest it.
312 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
313 RequestingModule, SuggestedModule,
320 /// LookupFile - Lookup the specified file in this search path, returning it
321 /// if it exists or returning null if not.
322 const FileEntry *DirectoryLookup::LookupFile(
325 SourceLocation IncludeLoc,
326 SmallVectorImpl<char> *SearchPath,
327 SmallVectorImpl<char> *RelativePath,
328 Module *RequestingModule,
329 ModuleMap::KnownHeader *SuggestedModule,
330 bool &InUserSpecifiedSystemFramework,
332 SmallVectorImpl<char> &MappedName) const {
333 InUserSpecifiedSystemFramework = false;
334 HasBeenMapped = false;
336 SmallString<1024> TmpDir;
338 // Concatenate the requested file onto the directory.
339 TmpDir = getDir()->getName();
340 llvm::sys::path::append(TmpDir, Filename);
342 StringRef SearchPathRef(getDir()->getName());
344 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
347 RelativePath->clear();
348 RelativePath->append(Filename.begin(), Filename.end());
351 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
352 isSystemHeaderDirectory(),
353 RequestingModule, SuggestedModule);
357 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
358 RequestingModule, SuggestedModule,
359 InUserSpecifiedSystemFramework);
361 assert(isHeaderMap() && "Unknown directory lookup");
362 const HeaderMap *HM = getHeaderMap();
363 SmallString<1024> Path;
364 StringRef Dest = HM->lookupFilename(Filename, Path);
368 const FileEntry *Result;
370 // Check if the headermap maps the filename to a framework include
371 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
372 // framework include.
373 if (llvm::sys::path::is_relative(Dest)) {
375 MappedName.append(Dest.begin(), Dest.end());
376 Filename = StringRef(MappedName.begin(), MappedName.size());
377 HasBeenMapped = true;
378 Result = HM->LookupFile(Filename, HS.getFileMgr());
381 Result = HS.getFileMgr().getFile(Dest);
386 StringRef SearchPathRef(getName());
388 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
391 RelativePath->clear();
392 RelativePath->append(Filename.begin(), Filename.end());
398 /// \brief Given a framework directory, find the top-most framework directory.
400 /// \param FileMgr The file manager to use for directory lookups.
401 /// \param DirName The name of the framework directory.
402 /// \param SubmodulePath Will be populated with the submodule path from the
403 /// returned top-level module to the originally named framework.
404 static const DirectoryEntry *
405 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
406 SmallVectorImpl<std::string> &SubmodulePath) {
407 assert(llvm::sys::path::extension(DirName) == ".framework" &&
408 "Not a framework directory");
410 // Note: as an egregious but useful hack we use the real path here, because
411 // frameworks moving between top-level frameworks to embedded frameworks tend
412 // to be symlinked, and we base the logical structure of modules on the
413 // physical layout. In particular, we need to deal with crazy includes like
415 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
417 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
418 // which one should access with, e.g.,
420 // #include <Bar/Wibble.h>
422 // Similar issues occur when a top-level framework has moved into an
423 // embedded framework.
424 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
425 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
427 // Get the parent directory name.
428 DirName = llvm::sys::path::parent_path(DirName);
432 // Determine whether this directory exists.
433 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
437 // If this is a framework directory, then we're a subframework of this
439 if (llvm::sys::path::extension(DirName) == ".framework") {
440 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
441 TopFrameworkDir = Dir;
445 return TopFrameworkDir;
448 static bool needModuleLookup(Module *RequestingModule,
449 bool HasSuggestedModule) {
450 return HasSuggestedModule ||
451 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
454 /// DoFrameworkLookup - Do a lookup of the specified file in the current
455 /// DirectoryLookup, which is a framework directory.
456 const FileEntry *DirectoryLookup::DoFrameworkLookup(
457 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
458 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
459 ModuleMap::KnownHeader *SuggestedModule,
460 bool &InUserSpecifiedSystemFramework) const {
461 FileManager &FileMgr = HS.getFileMgr();
463 // Framework names must have a '/' in the filename.
464 size_t SlashPos = Filename.find('/');
465 if (SlashPos == StringRef::npos) return nullptr;
467 // Find out if this is the home for the specified framework, by checking
468 // HeaderSearch. Possible answers are yes/no and unknown.
469 HeaderSearch::FrameworkCacheEntry &CacheEntry =
470 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
472 // If it is known and in some other directory, fail.
473 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
476 // Otherwise, construct the path to this framework dir.
478 // FrameworkName = "/System/Library/Frameworks/"
479 SmallString<1024> FrameworkName;
480 FrameworkName += getFrameworkDir()->getName();
481 if (FrameworkName.empty() || FrameworkName.back() != '/')
482 FrameworkName.push_back('/');
484 // FrameworkName = "/System/Library/Frameworks/Cocoa"
485 StringRef ModuleName(Filename.begin(), SlashPos);
486 FrameworkName += ModuleName;
488 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
489 FrameworkName += ".framework/";
491 // If the cache entry was unresolved, populate it now.
492 if (!CacheEntry.Directory) {
493 HS.IncrementFrameworkLookupCount();
495 // If the framework dir doesn't exist, we fail.
496 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
497 if (!Dir) return nullptr;
499 // Otherwise, if it does, remember that this is the right direntry for this
501 CacheEntry.Directory = getFrameworkDir();
503 // If this is a user search directory, check if the framework has been
504 // user-specified as a system framework.
505 if (getDirCharacteristic() == SrcMgr::C_User) {
506 SmallString<1024> SystemFrameworkMarker(FrameworkName);
507 SystemFrameworkMarker += ".system_framework";
508 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
509 CacheEntry.IsUserSpecifiedSystemFramework = true;
514 // Set the 'user-specified system framework' flag.
515 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
518 RelativePath->clear();
519 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
522 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
523 unsigned OrigSize = FrameworkName.size();
525 FrameworkName += "Headers/";
529 // Without trailing '/'.
530 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
533 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
534 const FileEntry *FE = FileMgr.getFile(FrameworkName,
535 /*openFile=*/!SuggestedModule);
537 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
538 const char *Private = "Private";
539 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
540 Private+strlen(Private));
542 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
543 Private+strlen(Private));
545 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
548 // If we found the header and are allowed to suggest a module, do so now.
549 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
550 // Find the framework in which this header occurs.
551 StringRef FrameworkPath = FE->getDir()->getName();
552 bool FoundFramework = false;
554 // Determine whether this directory exists.
555 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
559 // If this is a framework directory, then we're a subframework of this
561 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
562 FoundFramework = true;
566 // Get the parent directory name.
567 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
568 if (FrameworkPath.empty())
572 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
573 if (FoundFramework) {
574 if (!HS.findUsableModuleForFrameworkHeader(
575 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
578 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
579 SuggestedModule, IsSystem))
586 void HeaderSearch::setTarget(const TargetInfo &Target) {
587 ModMap.setTarget(Target);
591 //===----------------------------------------------------------------------===//
592 // Header File Location.
593 //===----------------------------------------------------------------------===//
595 /// \brief Return true with a diagnostic if the file that MSVC would have found
596 /// fails to match the one that Clang would have found with MSVC header search
598 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
599 const FileEntry *MSFE, const FileEntry *FE,
600 SourceLocation IncludeLoc) {
601 if (MSFE && FE != MSFE) {
602 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
608 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
609 assert(!Str.empty());
610 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
611 std::copy(Str.begin(), Str.end(), CopyStr);
612 CopyStr[Str.size()] = '\0';
616 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
617 /// return null on failure. isAngled indicates whether the file reference is
618 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
619 /// non-empty, indicates where the \#including file(s) are, in case a relative
620 /// search is needed. Microsoft mode will pass all \#including files.
621 const FileEntry *HeaderSearch::LookupFile(
622 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
623 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
624 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
625 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
626 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
627 bool SkipCache, bool BuildSystemModule) {
629 *SuggestedModule = ModuleMap::KnownHeader();
631 // If 'Filename' is absolute, check to see if it exists and no searching.
632 if (llvm::sys::path::is_absolute(Filename)) {
635 // If this was an #include_next "/absolute/file", fail.
636 if (FromDir) return nullptr;
641 RelativePath->clear();
642 RelativePath->append(Filename.begin(), Filename.end());
644 // Otherwise, just return the file.
645 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
646 /*IsSystemHeaderDir*/false,
647 RequestingModule, SuggestedModule);
650 // This is the header that MSVC's header search would have found.
651 const FileEntry *MSFE = nullptr;
652 ModuleMap::KnownHeader MSSuggestedModule;
654 // Unless disabled, check to see if the file is in the #includer's
655 // directory. This cannot be based on CurDir, because each includer could be
656 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
657 // include of "baz.h" should resolve to "whatever/foo/baz.h".
658 // This search is not done for <> headers.
659 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
660 SmallString<1024> TmpDir;
662 for (const auto &IncluderAndDir : Includers) {
663 const FileEntry *Includer = IncluderAndDir.first;
665 // Concatenate the requested file onto the directory.
666 // FIXME: Portability. Filename concatenation should be in sys::Path.
667 TmpDir = IncluderAndDir.second->getName();
668 TmpDir.push_back('/');
669 TmpDir.append(Filename.begin(), Filename.end());
671 // FIXME: We don't cache the result of getFileInfo across the call to
672 // getFileAndSuggestModule, because it's a reference to an element of
673 // a container that could be reallocated across this call.
675 // If we have no includer, that means we're processing a #include
676 // from a module build. We should treat this as a system header if we're
677 // building a [system] module.
678 bool IncluderIsSystemHeader =
679 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
681 if (const FileEntry *FE = getFileAndSuggestModule(
682 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
683 RequestingModule, SuggestedModule)) {
685 assert(First && "only first includer can have no file");
689 // Leave CurDir unset.
690 // This file is a system header or C++ unfriendly if the old file is.
692 // Note that we only use one of FromHFI/ToHFI at once, due to potential
693 // reallocation of the underlying vector potentially making the first
694 // reference binding dangling.
695 HeaderFileInfo &FromHFI = getFileInfo(Includer);
696 unsigned DirInfo = FromHFI.DirInfo;
697 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
698 StringRef Framework = FromHFI.Framework;
700 HeaderFileInfo &ToHFI = getFileInfo(FE);
701 ToHFI.DirInfo = DirInfo;
702 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
703 ToHFI.Framework = Framework;
706 StringRef SearchPathRef(IncluderAndDir.second->getName());
708 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
711 RelativePath->clear();
712 RelativePath->append(Filename.begin(), Filename.end());
717 // Otherwise, we found the path via MSVC header search rules. If
718 // -Wmsvc-include is enabled, we have to keep searching to see if we
719 // would've found this header in -I or -isystem directories.
720 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
724 if (SuggestedModule) {
725 MSSuggestedModule = *SuggestedModule;
726 *SuggestedModule = ModuleMap::KnownHeader();
737 // If this is a system #include, ignore the user #include locs.
738 unsigned i = isAngled ? AngledDirIdx : 0;
740 // If this is a #include_next request, start searching after the directory the
741 // file was found in.
743 i = FromDir-&SearchDirs[0];
745 // Cache all of the lookups performed by this method. Many headers are
746 // multiply included, and the "pragma once" optimization prevents them from
747 // being relex/pp'd, but they would still have to search through a
748 // (potentially huge) series of SearchDirs to find it.
749 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
751 // If the entry has been previously looked up, the first value will be
752 // non-zero. If the value is equal to i (the start point of our search), then
753 // this is a matching hit.
754 if (!SkipCache && CacheLookup.StartIdx == i+1) {
755 // Skip querying potentially lots of directories for this lookup.
756 i = CacheLookup.HitIdx;
757 if (CacheLookup.MappedName)
758 Filename = CacheLookup.MappedName;
760 // Otherwise, this is the first query, or the previous query didn't match
761 // our search start. We will fill in our found location below, so prime the
762 // start point value.
763 CacheLookup.reset(/*StartIdx=*/i+1);
766 SmallString<64> MappedName;
768 // Check each directory in sequence to see if it contains this file.
769 for (; i != SearchDirs.size(); ++i) {
770 bool InUserSpecifiedSystemFramework = false;
771 bool HasBeenMapped = false;
772 const FileEntry *FE = SearchDirs[i].LookupFile(
773 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
774 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
777 CacheLookup.MappedName =
778 copyString(Filename, LookupFileCache.getAllocator());
782 CurDir = &SearchDirs[i];
784 // This file is a system header or C++ unfriendly if the dir is.
785 HeaderFileInfo &HFI = getFileInfo(FE);
786 HFI.DirInfo = CurDir->getDirCharacteristic();
788 // If the directory characteristic is User but this framework was
789 // user-specified to be treated as a system framework, promote the
791 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
792 HFI.DirInfo = SrcMgr::C_System;
794 // If the filename matches a known system header prefix, override
795 // whether the file is a system header.
796 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
797 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
798 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
804 // If this file is found in a header map and uses the framework style of
805 // includes, then this header is part of a framework we're building.
806 if (CurDir->isIndexHeaderMap()) {
807 size_t SlashPos = Filename.find('/');
808 if (SlashPos != StringRef::npos) {
809 HFI.IndexHeaderMapHeader = 1;
810 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
815 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
817 *SuggestedModule = MSSuggestedModule;
821 // Remember this location for the next lookup we do.
822 CacheLookup.HitIdx = i;
826 // If we are including a file with a quoted include "foo.h" from inside
827 // a header in a framework that is currently being built, and we couldn't
828 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
829 // "Foo" is the name of the framework in which the including header was found.
830 if (!Includers.empty() && Includers.front().first && !isAngled &&
831 Filename.find('/') == StringRef::npos) {
832 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
833 if (IncludingHFI.IndexHeaderMapHeader) {
834 SmallString<128> ScratchFilename;
835 ScratchFilename += IncludingHFI.Framework;
836 ScratchFilename += '/';
837 ScratchFilename += Filename;
839 const FileEntry *FE =
840 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
841 CurDir, Includers.front(), SearchPath, RelativePath,
842 RequestingModule, SuggestedModule);
844 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
846 *SuggestedModule = MSSuggestedModule;
850 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
851 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
852 // FIXME: SuggestedModule.
857 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
859 *SuggestedModule = MSSuggestedModule;
863 // Otherwise, didn't find it. Remember we didn't find this.
864 CacheLookup.HitIdx = SearchDirs.size();
868 /// LookupSubframeworkHeader - Look up a subframework for the specified
869 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
870 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
871 /// is a subframework within Carbon.framework. If so, return the FileEntry
872 /// for the designated file, otherwise return null.
873 const FileEntry *HeaderSearch::
874 LookupSubframeworkHeader(StringRef Filename,
875 const FileEntry *ContextFileEnt,
876 SmallVectorImpl<char> *SearchPath,
877 SmallVectorImpl<char> *RelativePath,
878 Module *RequestingModule,
879 ModuleMap::KnownHeader *SuggestedModule) {
880 assert(ContextFileEnt && "No context file?");
882 // Framework names must have a '/' in the filename. Find it.
883 // FIXME: Should we permit '\' on Windows?
884 size_t SlashPos = Filename.find('/');
885 if (SlashPos == StringRef::npos) return nullptr;
887 // Look up the base framework name of the ContextFileEnt.
888 StringRef ContextName = ContextFileEnt->getName();
890 // If the context info wasn't a framework, couldn't be a subframework.
891 const unsigned DotFrameworkLen = 10;
892 auto FrameworkPos = ContextName.find(".framework");
893 if (FrameworkPos == StringRef::npos ||
894 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
895 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
898 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
900 DotFrameworkLen + 1);
902 // Append Frameworks/HIToolbox.framework/
903 FrameworkName += "Frameworks/";
904 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
905 FrameworkName += ".framework/";
908 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
909 FrameworkCacheEntry())).first;
911 // Some other location?
912 if (CacheLookup.second.Directory &&
913 CacheLookup.first().size() == FrameworkName.size() &&
914 memcmp(CacheLookup.first().data(), &FrameworkName[0],
915 CacheLookup.first().size()) != 0)
918 // Cache subframework.
919 if (!CacheLookup.second.Directory) {
920 ++NumSubFrameworkLookups;
922 // If the framework dir doesn't exist, we fail.
923 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
924 if (!Dir) return nullptr;
926 // Otherwise, if it does, remember that this is the right direntry for this
928 CacheLookup.second.Directory = Dir;
931 const FileEntry *FE = nullptr;
934 RelativePath->clear();
935 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
938 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
939 SmallString<1024> HeadersFilename(FrameworkName);
940 HeadersFilename += "Headers/";
943 // Without trailing '/'.
944 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
947 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
948 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
950 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
951 HeadersFilename = FrameworkName;
952 HeadersFilename += "PrivateHeaders/";
955 // Without trailing '/'.
956 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
959 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
960 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
964 // This file is a system header or C++ unfriendly if the old file is.
966 // Note that the temporary 'DirInfo' is required here, as either call to
967 // getFileInfo could resize the vector and we don't want to rely on order
969 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
970 getFileInfo(FE).DirInfo = DirInfo;
972 FrameworkName.pop_back(); // remove the trailing '/'
973 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
974 SuggestedModule, /*IsSystem*/ false))
980 //===----------------------------------------------------------------------===//
981 // File Info Management.
982 //===----------------------------------------------------------------------===//
984 /// \brief Merge the header file info provided by \p OtherHFI into the current
985 /// header file info (\p HFI)
986 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
987 const HeaderFileInfo &OtherHFI) {
988 assert(OtherHFI.External && "expected to merge external HFI");
990 HFI.isImport |= OtherHFI.isImport;
991 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
992 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
993 HFI.NumIncludes += OtherHFI.NumIncludes;
995 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
996 HFI.ControllingMacro = OtherHFI.ControllingMacro;
997 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1000 HFI.DirInfo = OtherHFI.DirInfo;
1001 HFI.External = (!HFI.IsValid || HFI.External);
1003 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1005 if (HFI.Framework.empty())
1006 HFI.Framework = OtherHFI.Framework;
1009 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1011 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1012 if (FE->getUID() >= FileInfo.size())
1013 FileInfo.resize(FE->getUID() + 1);
1015 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1016 // FIXME: Use a generation count to check whether this is really up to date.
1017 if (ExternalSource && !HFI->Resolved) {
1018 HFI->Resolved = true;
1019 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1021 HFI = &FileInfo[FE->getUID()];
1022 if (ExternalHFI.External)
1023 mergeHeaderFileInfo(*HFI, ExternalHFI);
1026 HFI->IsValid = true;
1027 // We have local information about this header file, so it's no longer
1028 // strictly external.
1029 HFI->External = false;
1033 const HeaderFileInfo *
1034 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1035 bool WantExternal) const {
1036 // If we have an external source, ensure we have the latest information.
1037 // FIXME: Use a generation count to check whether this is really up to date.
1038 HeaderFileInfo *HFI;
1039 if (ExternalSource) {
1040 if (FE->getUID() >= FileInfo.size()) {
1043 FileInfo.resize(FE->getUID() + 1);
1046 HFI = &FileInfo[FE->getUID()];
1047 if (!WantExternal && (!HFI->IsValid || HFI->External))
1049 if (!HFI->Resolved) {
1050 HFI->Resolved = true;
1051 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1053 HFI = &FileInfo[FE->getUID()];
1054 if (ExternalHFI.External)
1055 mergeHeaderFileInfo(*HFI, ExternalHFI);
1057 } else if (FE->getUID() >= FileInfo.size()) {
1060 HFI = &FileInfo[FE->getUID()];
1063 if (!HFI->IsValid || (HFI->External && !WantExternal))
1069 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1070 // Check if we've ever seen this file as a header.
1071 if (auto *HFI = getExistingFileInfo(File))
1072 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1073 HFI->ControllingMacroID;
1077 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1078 ModuleMap::ModuleHeaderRole Role,
1079 bool isCompilingModuleHeader) {
1080 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1082 // Don't mark the file info as non-external if there's nothing to change.
1083 if (!isCompilingModuleHeader) {
1084 if (!isModularHeader)
1086 auto *HFI = getExistingFileInfo(FE);
1087 if (HFI && HFI->isModuleHeader)
1091 auto &HFI = getFileInfo(FE);
1092 HFI.isModuleHeader |= isModularHeader;
1093 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1096 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1097 const FileEntry *File, bool isImport,
1098 bool ModulesEnabled, Module *M) {
1099 ++NumIncluded; // Count # of attempted #includes.
1101 // Get information about this file.
1102 HeaderFileInfo &FileInfo = getFileInfo(File);
1104 // FIXME: this is a workaround for the lack of proper modules-aware support
1105 // for #import / #pragma once
1106 auto TryEnterImported = [&](void) -> bool {
1107 if (!ModulesEnabled)
1109 // Modules with builtins are special; multiple modules use builtins as
1110 // modular headers, example:
1112 // module stddef { header "stddef.h" export * }
1114 // After module map parsing, this expands to:
1117 // header "/path_to_builtin_dirs/stddef.h"
1118 // textual "stddef.h"
1121 // It's common that libc++ and system modules will both define such
1122 // submodules. Make sure cached results for a builtin header won't
1123 // prevent other builtin modules to potentially enter the builtin header.
1124 // Note that builtins are header guarded and the decision to actually
1125 // enter them is postponed to the controlling macros logic below.
1126 bool TryEnterHdr = false;
1127 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1128 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1129 ModuleMap::isBuiltinHeader(
1130 llvm::sys::path::filename(File->getName()));
1132 // Textual headers can be #imported from different modules. Since ObjC
1133 // headers find in the wild might rely only on #import and do not contain
1134 // controlling macros, be conservative and only try to enter textual headers
1135 // if such macro is present.
1136 if (!FileInfo.isModuleHeader &&
1137 FileInfo.getControllingMacro(ExternalLookup))
1142 // If this is a #import directive, check that we have not already imported
1145 // If this has already been imported, don't import it again.
1146 FileInfo.isImport = true;
1148 // Has this already been #import'ed or #include'd?
1149 if (FileInfo.NumIncludes && !TryEnterImported())
1152 // Otherwise, if this is a #include of a file that was previously #import'd
1153 // or if this is the second #include of a #pragma once file, ignore it.
1154 if (FileInfo.isImport && !TryEnterImported())
1158 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1159 // if the macro that guards it is defined, we know the #include has no effect.
1160 if (const IdentifierInfo *ControllingMacro
1161 = FileInfo.getControllingMacro(ExternalLookup)) {
1162 // If the header corresponds to a module, check whether the macro is already
1163 // defined in that module rather than checking in the current set of visible
1165 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1166 : PP.isMacroDefined(ControllingMacro)) {
1167 ++NumMultiIncludeFileOptzn;
1172 // Increment the number of times this file has been included.
1173 ++FileInfo.NumIncludes;
1178 size_t HeaderSearch::getTotalMemory() const {
1179 return SearchDirs.capacity()
1180 + llvm::capacity_in_bytes(FileInfo)
1181 + llvm::capacity_in_bytes(HeaderMaps)
1182 + LookupFileCache.getAllocator().getTotalMemory()
1183 + FrameworkMap.getAllocator().getTotalMemory();
1186 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1187 return FrameworkNames.insert(Framework).first->first();
1190 bool HeaderSearch::hasModuleMap(StringRef FileName,
1191 const DirectoryEntry *Root,
1193 if (!HSOpts->ImplicitModuleMaps)
1196 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1198 StringRef DirName = FileName;
1200 // Get the parent directory name.
1201 DirName = llvm::sys::path::parent_path(DirName);
1202 if (DirName.empty())
1205 // Determine whether this directory exists.
1206 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1210 // Try to load the module map file in this directory.
1211 switch (loadModuleMapFile(Dir, IsSystem,
1212 llvm::sys::path::extension(Dir->getName()) ==
1214 case LMM_NewlyLoaded:
1215 case LMM_AlreadyLoaded:
1216 // Success. All of the directories we stepped through inherit this module
1218 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1219 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1222 case LMM_NoDirectory:
1223 case LMM_InvalidModuleMap:
1227 // If we hit the top of our search, we're done.
1231 // Keep track of all of the directories we checked, so we can mark them as
1232 // having module maps if we eventually do find a module map.
1233 FixUpDirectories.push_back(Dir);
1237 ModuleMap::KnownHeader
1238 HeaderSearch::findModuleForHeader(const FileEntry *File,
1239 bool AllowTextual) const {
1240 if (ExternalSource) {
1241 // Make sure the external source has handled header info about this file,
1242 // which includes whether the file is part of a module.
1243 (void)getExistingFileInfo(File);
1245 return ModMap.findModuleForHeader(File, AllowTextual);
1248 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1249 Module *RequestingModule,
1250 ModuleMap::KnownHeader *SuggestedModule) {
1251 ModuleMap::KnownHeader Module =
1252 HS.findModuleForHeader(File, /*AllowTextual*/true);
1253 if (SuggestedModule)
1254 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1255 ? ModuleMap::KnownHeader()
1258 // If this module specifies [no_undeclared_includes], we cannot find any
1259 // file that's in a non-dependency module.
1260 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1261 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1262 if (!RequestingModule->directlyUses(Module.getModule())) {
1270 bool HeaderSearch::findUsableModuleForHeader(
1271 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1272 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1273 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1274 // If there is a module that corresponds to this header, suggest it.
1275 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1276 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1281 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1282 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1283 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1284 // If we're supposed to suggest a module, look for one now.
1285 if (needModuleLookup(RequestingModule, SuggestedModule)) {
1286 // Find the top-level framework based on this framework.
1287 SmallVector<std::string, 4> SubmodulePath;
1288 const DirectoryEntry *TopFrameworkDir
1289 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1291 // Determine the name of the top-level framework.
1292 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1294 // Load this framework module. If that succeeds, find the suggested module
1295 // for this header, if any.
1296 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1298 // FIXME: This can find a module not part of ModuleName, which is
1299 // important so that we're consistent about whether this header
1300 // corresponds to a module. Possibly we should lock down framework modules
1301 // so that this is not possible.
1302 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1307 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1308 FileManager &FileMgr) {
1309 StringRef Filename = llvm::sys::path::filename(File->getName());
1310 SmallString<128> PrivateFilename(File->getDir()->getName());
1311 if (Filename == "module.map")
1312 llvm::sys::path::append(PrivateFilename, "module_private.map");
1313 else if (Filename == "module.modulemap")
1314 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1317 return FileMgr.getFile(PrivateFilename);
1320 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1321 // Find the directory for the module. For frameworks, that may require going
1322 // up from the 'Modules' directory.
1323 const DirectoryEntry *Dir = nullptr;
1324 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1325 Dir = FileMgr.getDirectory(".");
1327 Dir = File->getDir();
1328 StringRef DirName(Dir->getName());
1329 if (llvm::sys::path::filename(DirName) == "Modules") {
1330 DirName = llvm::sys::path::parent_path(DirName);
1331 if (DirName.endswith(".framework"))
1332 Dir = FileMgr.getDirectory(DirName);
1333 // FIXME: This assert can fail if there's a race between the above check
1334 // and the removal of the directory.
1335 assert(Dir && "parent must exist");
1339 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
1340 case LMM_AlreadyLoaded:
1341 case LMM_NewlyLoaded:
1343 case LMM_NoDirectory:
1344 case LMM_InvalidModuleMap:
1347 llvm_unreachable("Unknown load module map result");
1350 HeaderSearch::LoadModuleMapResult
1351 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1352 const DirectoryEntry *Dir) {
1353 assert(File && "expected FileEntry");
1355 // Check whether we've already loaded this module map, and mark it as being
1356 // loaded in case we recursively try to load it from itself.
1357 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1358 if (!AddResult.second)
1359 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1361 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
1362 LoadedModuleMaps[File] = false;
1363 return LMM_InvalidModuleMap;
1366 // Try to load a corresponding private module map.
1367 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1368 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1369 LoadedModuleMaps[File] = false;
1370 return LMM_InvalidModuleMap;
1374 // This directory has a module map.
1375 return LMM_NewlyLoaded;
1379 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1380 if (!HSOpts->ImplicitModuleMaps)
1382 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1383 // module.map at the framework root is also accepted.
1384 SmallString<128> ModuleMapFileName(Dir->getName());
1386 llvm::sys::path::append(ModuleMapFileName, "Modules");
1387 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1388 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1391 // Continue to allow module.map
1392 ModuleMapFileName = Dir->getName();
1393 llvm::sys::path::append(ModuleMapFileName, "module.map");
1394 return FileMgr.getFile(ModuleMapFileName);
1397 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1398 const DirectoryEntry *Dir,
1400 if (Module *Module = ModMap.findModule(Name))
1403 // Try to load a module map file.
1404 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1405 case LMM_InvalidModuleMap:
1406 // Try to infer a module map from the framework directory.
1407 if (HSOpts->ImplicitModuleMaps)
1408 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1411 case LMM_AlreadyLoaded:
1412 case LMM_NoDirectory:
1415 case LMM_NewlyLoaded:
1419 return ModMap.findModule(Name);
1423 HeaderSearch::LoadModuleMapResult
1424 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1426 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1427 return loadModuleMapFile(Dir, IsSystem, IsFramework);
1429 return LMM_NoDirectory;
1432 HeaderSearch::LoadModuleMapResult
1433 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1435 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1436 if (KnownDir != DirectoryHasModuleMap.end())
1437 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1439 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1440 LoadModuleMapResult Result =
1441 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1442 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1443 // E.g. Foo.framework/Modules/module.modulemap
1444 // ^Dir ^ModuleMapFile
1445 if (Result == LMM_NewlyLoaded)
1446 DirectoryHasModuleMap[Dir] = true;
1447 else if (Result == LMM_InvalidModuleMap)
1448 DirectoryHasModuleMap[Dir] = false;
1451 return LMM_InvalidModuleMap;
1454 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1457 if (HSOpts->ImplicitModuleMaps) {
1458 // Load module maps for each of the header search directories.
1459 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1460 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1461 if (SearchDirs[Idx].isFramework()) {
1463 SmallString<128> DirNative;
1464 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1467 // Search each of the ".framework" directories to load them as modules.
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 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
1474 const DirectoryEntry *FrameworkDir =
1475 FileMgr.getDirectory(Dir->getName());
1479 // Load this framework module.
1480 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1481 FrameworkDir, IsSystem);
1486 // FIXME: Deal with header maps.
1487 if (SearchDirs[Idx].isHeaderMap())
1490 // Try to load a module map file for the search directory.
1491 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1492 /*IsFramework*/ false);
1494 // Try to load module map files for immediate subdirectories of this
1495 // search directory.
1496 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1500 // Populate the list of modules.
1501 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1502 MEnd = ModMap.module_end();
1504 Modules.push_back(M->getValue());
1508 void HeaderSearch::loadTopLevelSystemModules() {
1509 if (!HSOpts->ImplicitModuleMaps)
1512 // Load module maps for each of the header search directories.
1513 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1514 // We only care about normal header directories.
1515 if (!SearchDirs[Idx].isNormalDir()) {
1519 // Try to load a module map file for the search directory.
1520 loadModuleMapFile(SearchDirs[Idx].getDir(),
1521 SearchDirs[Idx].isSystemHeaderDirectory(),
1522 SearchDirs[Idx].isFramework());
1526 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1527 assert(HSOpts->ImplicitModuleMaps &&
1528 "Should not be loading subdirectory module maps");
1530 if (SearchDir.haveSearchedAllModuleMaps())
1534 SmallString<128> DirNative;
1535 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1536 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1537 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1538 Dir != DirEnd && !EC; Dir.increment(EC)) {
1540 llvm::sys::path::extension(Dir->getName()) == ".framework";
1541 if (IsFramework == SearchDir.isFramework())
1542 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
1543 SearchDir.isFramework());
1546 SearchDir.setSearchedAllModuleMaps(true);
1549 std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1551 // FIXME: We assume that the path name currently cached in the FileEntry is
1552 // the most appropriate one for this analysis (and that it's spelled the same
1553 // way as the corresponding header search path).
1554 StringRef Name = File->getName();
1556 unsigned BestPrefixLength = 0;
1557 unsigned BestSearchDir;
1559 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1560 // FIXME: Support this search within frameworks and header maps.
1561 if (!SearchDirs[I].isNormalDir())
1564 StringRef Dir = SearchDirs[I].getDir()->getName();
1565 for (auto NI = llvm::sys::path::begin(Name),
1566 NE = llvm::sys::path::end(Name),
1567 DI = llvm::sys::path::begin(Dir),
1568 DE = llvm::sys::path::end(Dir);
1569 /*termination condition in loop*/; ++NI, ++DI) {
1570 // '.' components in Name are ignored.
1571 while (NI != NE && *NI == ".")
1576 // '.' components in Dir are ignored.
1577 while (DI != DE && *DI == ".")
1580 // Dir is a prefix of Name, up to '.' components and choice of path
1582 unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1583 if (PrefixLength > BestPrefixLength) {
1584 BestPrefixLength = PrefixLength;
1596 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1597 return Name.drop_front(BestPrefixLength);