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.
176 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
178 return std::string();
179 auto DirName = FileMgr.getCanonicalName(Dir);
180 auto FileName = llvm::sys::path::filename(ModuleMapPath);
182 llvm::hash_code Hash =
183 llvm::hash_combine(DirName.lower(), FileName.lower());
185 SmallString<128> HashStr;
186 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
187 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
189 return Result.str().str();
192 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
193 // Look in the module map to determine if there is a module by this name.
194 Module *Module = ModMap.findModule(ModuleName);
195 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
198 StringRef SearchName = ModuleName;
199 Module = lookupModule(ModuleName, SearchName);
201 // The facility for "private modules" -- adjacent, optional module maps named
202 // module.private.modulemap that are supposed to define private submodules --
203 // is sometimes misused by frameworks that name their associated private
204 // module FooPrivate, rather than as a submodule named Foo.Private as
205 // intended. Here we compensate for such cases by looking in directories named
206 // Foo.framework, when we previously looked and failed to find a
207 // FooPrivate.framework.
208 if (!Module && SearchName.consume_back("Private"))
209 Module = lookupModule(ModuleName, SearchName);
213 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName) {
214 Module *Module = nullptr;
216 // Look through the various header search paths to load any available module
217 // maps, searching for a module map that describes this module.
218 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
219 if (SearchDirs[Idx].isFramework()) {
220 // Search for or infer a module map for a framework. Here we use
221 // SearchName rather than ModuleName, to permit finding private modules
222 // named FooPrivate in buggy frameworks named Foo.
223 SmallString<128> FrameworkDirName;
224 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
225 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
226 if (const DirectoryEntry *FrameworkDir
227 = FileMgr.getDirectory(FrameworkDirName)) {
229 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
230 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
236 // FIXME: Figure out how header maps and module maps will work together.
238 // Only deal with normal search directories.
239 if (!SearchDirs[Idx].isNormalDir())
242 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
243 // Search for a module map file in this directory.
244 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
245 /*IsFramework*/false) == LMM_NewlyLoaded) {
246 // We just loaded a module map file; check whether the module is
248 Module = ModMap.findModule(ModuleName);
253 // Search for a module map in a subdirectory with the same name as the
255 SmallString<128> NestedModuleMapDirName;
256 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
257 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
258 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
259 /*IsFramework*/false) == LMM_NewlyLoaded){
260 // If we just loaded a module map file, look for the module again.
261 Module = ModMap.findModule(ModuleName);
266 // If we've already performed the exhaustive search for module maps in this
267 // search directory, don't do it again.
268 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
271 // Load all module maps in the immediate subdirectories of this search
273 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
275 // Look again for the module.
276 Module = ModMap.findModule(ModuleName);
284 //===----------------------------------------------------------------------===//
285 // File lookup within a DirectoryLookup scope
286 //===----------------------------------------------------------------------===//
288 /// getName - Return the directory or filename corresponding to this lookup
290 StringRef DirectoryLookup::getName() const {
292 return getDir()->getName();
294 return getFrameworkDir()->getName();
295 assert(isHeaderMap() && "Unknown DirectoryLookup");
296 return getHeaderMap()->getFileName();
299 const FileEntry *HeaderSearch::getFileAndSuggestModule(
300 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
301 bool IsSystemHeaderDir, Module *RequestingModule,
302 ModuleMap::KnownHeader *SuggestedModule) {
303 // If we have a module map that might map this header, load it and
304 // check whether we'll have a suggestion for a module.
305 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
309 // If there is a module that corresponds to this header, suggest it.
310 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
311 RequestingModule, SuggestedModule,
318 /// LookupFile - Lookup the specified file in this search path, returning it
319 /// if it exists or returning null if not.
320 const FileEntry *DirectoryLookup::LookupFile(
323 SourceLocation IncludeLoc,
324 SmallVectorImpl<char> *SearchPath,
325 SmallVectorImpl<char> *RelativePath,
326 Module *RequestingModule,
327 ModuleMap::KnownHeader *SuggestedModule,
328 bool &InUserSpecifiedSystemFramework,
330 SmallVectorImpl<char> &MappedName) const {
331 InUserSpecifiedSystemFramework = false;
332 HasBeenMapped = false;
334 SmallString<1024> TmpDir;
336 // Concatenate the requested file onto the directory.
337 TmpDir = getDir()->getName();
338 llvm::sys::path::append(TmpDir, Filename);
340 StringRef SearchPathRef(getDir()->getName());
342 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
345 RelativePath->clear();
346 RelativePath->append(Filename.begin(), Filename.end());
349 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
350 isSystemHeaderDirectory(),
351 RequestingModule, SuggestedModule);
355 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
356 RequestingModule, SuggestedModule,
357 InUserSpecifiedSystemFramework);
359 assert(isHeaderMap() && "Unknown directory lookup");
360 const HeaderMap *HM = getHeaderMap();
361 SmallString<1024> Path;
362 StringRef Dest = HM->lookupFilename(Filename, Path);
366 const FileEntry *Result;
368 // Check if the headermap maps the filename to a framework include
369 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
370 // framework include.
371 if (llvm::sys::path::is_relative(Dest)) {
373 MappedName.append(Dest.begin(), Dest.end());
374 Filename = StringRef(MappedName.begin(), MappedName.size());
375 HasBeenMapped = true;
376 Result = HM->LookupFile(Filename, HS.getFileMgr());
379 Result = HS.getFileMgr().getFile(Dest);
384 StringRef SearchPathRef(getName());
386 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
389 RelativePath->clear();
390 RelativePath->append(Filename.begin(), Filename.end());
396 /// \brief Given a framework directory, find the top-most framework directory.
398 /// \param FileMgr The file manager to use for directory lookups.
399 /// \param DirName The name of the framework directory.
400 /// \param SubmodulePath Will be populated with the submodule path from the
401 /// returned top-level module to the originally named framework.
402 static const DirectoryEntry *
403 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
404 SmallVectorImpl<std::string> &SubmodulePath) {
405 assert(llvm::sys::path::extension(DirName) == ".framework" &&
406 "Not a framework directory");
408 // Note: as an egregious but useful hack we use the real path here, because
409 // frameworks moving between top-level frameworks to embedded frameworks tend
410 // to be symlinked, and we base the logical structure of modules on the
411 // physical layout. In particular, we need to deal with crazy includes like
413 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
415 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
416 // which one should access with, e.g.,
418 // #include <Bar/Wibble.h>
420 // Similar issues occur when a top-level framework has moved into an
421 // embedded framework.
422 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
423 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
425 // Get the parent directory name.
426 DirName = llvm::sys::path::parent_path(DirName);
430 // Determine whether this directory exists.
431 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
435 // If this is a framework directory, then we're a subframework of this
437 if (llvm::sys::path::extension(DirName) == ".framework") {
438 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
439 TopFrameworkDir = Dir;
443 return TopFrameworkDir;
446 static bool needModuleLookup(Module *RequestingModule,
447 bool HasSuggestedModule) {
448 return HasSuggestedModule ||
449 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
452 /// DoFrameworkLookup - Do a lookup of the specified file in the current
453 /// DirectoryLookup, which is a framework directory.
454 const FileEntry *DirectoryLookup::DoFrameworkLookup(
455 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
456 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
457 ModuleMap::KnownHeader *SuggestedModule,
458 bool &InUserSpecifiedSystemFramework) const {
459 FileManager &FileMgr = HS.getFileMgr();
461 // Framework names must have a '/' in the filename.
462 size_t SlashPos = Filename.find('/');
463 if (SlashPos == StringRef::npos) return nullptr;
465 // Find out if this is the home for the specified framework, by checking
466 // HeaderSearch. Possible answers are yes/no and unknown.
467 HeaderSearch::FrameworkCacheEntry &CacheEntry =
468 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
470 // If it is known and in some other directory, fail.
471 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
474 // Otherwise, construct the path to this framework dir.
476 // FrameworkName = "/System/Library/Frameworks/"
477 SmallString<1024> FrameworkName;
478 FrameworkName += getFrameworkDir()->getName();
479 if (FrameworkName.empty() || FrameworkName.back() != '/')
480 FrameworkName.push_back('/');
482 // FrameworkName = "/System/Library/Frameworks/Cocoa"
483 StringRef ModuleName(Filename.begin(), SlashPos);
484 FrameworkName += ModuleName;
486 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
487 FrameworkName += ".framework/";
489 // If the cache entry was unresolved, populate it now.
490 if (!CacheEntry.Directory) {
491 HS.IncrementFrameworkLookupCount();
493 // If the framework dir doesn't exist, we fail.
494 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
495 if (!Dir) return nullptr;
497 // Otherwise, if it does, remember that this is the right direntry for this
499 CacheEntry.Directory = getFrameworkDir();
501 // If this is a user search directory, check if the framework has been
502 // user-specified as a system framework.
503 if (getDirCharacteristic() == SrcMgr::C_User) {
504 SmallString<1024> SystemFrameworkMarker(FrameworkName);
505 SystemFrameworkMarker += ".system_framework";
506 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
507 CacheEntry.IsUserSpecifiedSystemFramework = true;
512 // Set the 'user-specified system framework' flag.
513 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
516 RelativePath->clear();
517 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
520 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
521 unsigned OrigSize = FrameworkName.size();
523 FrameworkName += "Headers/";
527 // Without trailing '/'.
528 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
531 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
532 const FileEntry *FE = FileMgr.getFile(FrameworkName,
533 /*openFile=*/!SuggestedModule);
535 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
536 const char *Private = "Private";
537 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
538 Private+strlen(Private));
540 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
541 Private+strlen(Private));
543 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
546 // If we found the header and are allowed to suggest a module, do so now.
547 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
548 // Find the framework in which this header occurs.
549 StringRef FrameworkPath = FE->getDir()->getName();
550 bool FoundFramework = false;
552 // Determine whether this directory exists.
553 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
557 // If this is a framework directory, then we're a subframework of this
559 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
560 FoundFramework = true;
564 // Get the parent directory name.
565 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
566 if (FrameworkPath.empty())
570 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
571 if (FoundFramework) {
572 if (!HS.findUsableModuleForFrameworkHeader(
573 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
576 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
577 SuggestedModule, IsSystem))
584 void HeaderSearch::setTarget(const TargetInfo &Target) {
585 ModMap.setTarget(Target);
589 //===----------------------------------------------------------------------===//
590 // Header File Location.
591 //===----------------------------------------------------------------------===//
593 /// \brief Return true with a diagnostic if the file that MSVC would have found
594 /// fails to match the one that Clang would have found with MSVC header search
596 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
597 const FileEntry *MSFE, const FileEntry *FE,
598 SourceLocation IncludeLoc) {
599 if (MSFE && FE != MSFE) {
600 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
606 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
607 assert(!Str.empty());
608 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
609 std::copy(Str.begin(), Str.end(), CopyStr);
610 CopyStr[Str.size()] = '\0';
614 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
615 /// return null on failure. isAngled indicates whether the file reference is
616 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
617 /// non-empty, indicates where the \#including file(s) are, in case a relative
618 /// search is needed. Microsoft mode will pass all \#including files.
619 const FileEntry *HeaderSearch::LookupFile(
620 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
621 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
622 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
623 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
624 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
625 bool SkipCache, bool BuildSystemModule) {
627 *SuggestedModule = ModuleMap::KnownHeader();
629 // If 'Filename' is absolute, check to see if it exists and no searching.
630 if (llvm::sys::path::is_absolute(Filename)) {
633 // If this was an #include_next "/absolute/file", fail.
634 if (FromDir) return nullptr;
639 RelativePath->clear();
640 RelativePath->append(Filename.begin(), Filename.end());
642 // Otherwise, just return the file.
643 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
644 /*IsSystemHeaderDir*/false,
645 RequestingModule, SuggestedModule);
648 // This is the header that MSVC's header search would have found.
649 const FileEntry *MSFE = nullptr;
650 ModuleMap::KnownHeader MSSuggestedModule;
652 // Unless disabled, check to see if the file is in the #includer's
653 // directory. This cannot be based on CurDir, because each includer could be
654 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
655 // include of "baz.h" should resolve to "whatever/foo/baz.h".
656 // This search is not done for <> headers.
657 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
658 SmallString<1024> TmpDir;
660 for (const auto &IncluderAndDir : Includers) {
661 const FileEntry *Includer = IncluderAndDir.first;
663 // Concatenate the requested file onto the directory.
664 // FIXME: Portability. Filename concatenation should be in sys::Path.
665 TmpDir = IncluderAndDir.second->getName();
666 TmpDir.push_back('/');
667 TmpDir.append(Filename.begin(), Filename.end());
669 // FIXME: We don't cache the result of getFileInfo across the call to
670 // getFileAndSuggestModule, because it's a reference to an element of
671 // a container that could be reallocated across this call.
673 // If we have no includer, that means we're processing a #include
674 // from a module build. We should treat this as a system header if we're
675 // building a [system] module.
676 bool IncluderIsSystemHeader =
677 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
679 if (const FileEntry *FE = getFileAndSuggestModule(
680 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
681 RequestingModule, SuggestedModule)) {
683 assert(First && "only first includer can have no file");
687 // Leave CurDir unset.
688 // This file is a system header or C++ unfriendly if the old file is.
690 // Note that we only use one of FromHFI/ToHFI at once, due to potential
691 // reallocation of the underlying vector potentially making the first
692 // reference binding dangling.
693 HeaderFileInfo &FromHFI = getFileInfo(Includer);
694 unsigned DirInfo = FromHFI.DirInfo;
695 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
696 StringRef Framework = FromHFI.Framework;
698 HeaderFileInfo &ToHFI = getFileInfo(FE);
699 ToHFI.DirInfo = DirInfo;
700 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
701 ToHFI.Framework = Framework;
704 StringRef SearchPathRef(IncluderAndDir.second->getName());
706 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
709 RelativePath->clear();
710 RelativePath->append(Filename.begin(), Filename.end());
715 // Otherwise, we found the path via MSVC header search rules. If
716 // -Wmsvc-include is enabled, we have to keep searching to see if we
717 // would've found this header in -I or -isystem directories.
718 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
722 if (SuggestedModule) {
723 MSSuggestedModule = *SuggestedModule;
724 *SuggestedModule = ModuleMap::KnownHeader();
735 // If this is a system #include, ignore the user #include locs.
736 unsigned i = isAngled ? AngledDirIdx : 0;
738 // If this is a #include_next request, start searching after the directory the
739 // file was found in.
741 i = FromDir-&SearchDirs[0];
743 // Cache all of the lookups performed by this method. Many headers are
744 // multiply included, and the "pragma once" optimization prevents them from
745 // being relex/pp'd, but they would still have to search through a
746 // (potentially huge) series of SearchDirs to find it.
747 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
749 // If the entry has been previously looked up, the first value will be
750 // non-zero. If the value is equal to i (the start point of our search), then
751 // this is a matching hit.
752 if (!SkipCache && CacheLookup.StartIdx == i+1) {
753 // Skip querying potentially lots of directories for this lookup.
754 i = CacheLookup.HitIdx;
755 if (CacheLookup.MappedName)
756 Filename = CacheLookup.MappedName;
758 // Otherwise, this is the first query, or the previous query didn't match
759 // our search start. We will fill in our found location below, so prime the
760 // start point value.
761 CacheLookup.reset(/*StartIdx=*/i+1);
764 SmallString<64> MappedName;
766 // Check each directory in sequence to see if it contains this file.
767 for (; i != SearchDirs.size(); ++i) {
768 bool InUserSpecifiedSystemFramework = false;
769 bool HasBeenMapped = false;
770 const FileEntry *FE = SearchDirs[i].LookupFile(
771 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
772 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
775 CacheLookup.MappedName =
776 copyString(Filename, LookupFileCache.getAllocator());
780 CurDir = &SearchDirs[i];
782 // This file is a system header or C++ unfriendly if the dir is.
783 HeaderFileInfo &HFI = getFileInfo(FE);
784 HFI.DirInfo = CurDir->getDirCharacteristic();
786 // If the directory characteristic is User but this framework was
787 // user-specified to be treated as a system framework, promote the
789 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
790 HFI.DirInfo = SrcMgr::C_System;
792 // If the filename matches a known system header prefix, override
793 // whether the file is a system header.
794 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
795 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
796 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
802 // If this file is found in a header map and uses the framework style of
803 // includes, then this header is part of a framework we're building.
804 if (CurDir->isIndexHeaderMap()) {
805 size_t SlashPos = Filename.find('/');
806 if (SlashPos != StringRef::npos) {
807 HFI.IndexHeaderMapHeader = 1;
808 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
813 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
815 *SuggestedModule = MSSuggestedModule;
819 // Remember this location for the next lookup we do.
820 CacheLookup.HitIdx = i;
824 // If we are including a file with a quoted include "foo.h" from inside
825 // a header in a framework that is currently being built, and we couldn't
826 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
827 // "Foo" is the name of the framework in which the including header was found.
828 if (!Includers.empty() && Includers.front().first && !isAngled &&
829 Filename.find('/') == StringRef::npos) {
830 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
831 if (IncludingHFI.IndexHeaderMapHeader) {
832 SmallString<128> ScratchFilename;
833 ScratchFilename += IncludingHFI.Framework;
834 ScratchFilename += '/';
835 ScratchFilename += Filename;
837 const FileEntry *FE =
838 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
839 CurDir, Includers.front(), SearchPath, RelativePath,
840 RequestingModule, SuggestedModule);
842 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
844 *SuggestedModule = MSSuggestedModule;
848 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
849 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
850 // FIXME: SuggestedModule.
855 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
857 *SuggestedModule = MSSuggestedModule;
861 // Otherwise, didn't find it. Remember we didn't find this.
862 CacheLookup.HitIdx = SearchDirs.size();
866 /// LookupSubframeworkHeader - Look up a subframework for the specified
867 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
868 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
869 /// is a subframework within Carbon.framework. If so, return the FileEntry
870 /// for the designated file, otherwise return null.
871 const FileEntry *HeaderSearch::
872 LookupSubframeworkHeader(StringRef Filename,
873 const FileEntry *ContextFileEnt,
874 SmallVectorImpl<char> *SearchPath,
875 SmallVectorImpl<char> *RelativePath,
876 Module *RequestingModule,
877 ModuleMap::KnownHeader *SuggestedModule) {
878 assert(ContextFileEnt && "No context file?");
880 // Framework names must have a '/' in the filename. Find it.
881 // FIXME: Should we permit '\' on Windows?
882 size_t SlashPos = Filename.find('/');
883 if (SlashPos == StringRef::npos) return nullptr;
885 // Look up the base framework name of the ContextFileEnt.
886 StringRef ContextName = ContextFileEnt->getName();
888 // If the context info wasn't a framework, couldn't be a subframework.
889 const unsigned DotFrameworkLen = 10;
890 auto FrameworkPos = ContextName.find(".framework");
891 if (FrameworkPos == StringRef::npos ||
892 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
893 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
896 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
898 DotFrameworkLen + 1);
900 // Append Frameworks/HIToolbox.framework/
901 FrameworkName += "Frameworks/";
902 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
903 FrameworkName += ".framework/";
906 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
907 FrameworkCacheEntry())).first;
909 // Some other location?
910 if (CacheLookup.second.Directory &&
911 CacheLookup.first().size() == FrameworkName.size() &&
912 memcmp(CacheLookup.first().data(), &FrameworkName[0],
913 CacheLookup.first().size()) != 0)
916 // Cache subframework.
917 if (!CacheLookup.second.Directory) {
918 ++NumSubFrameworkLookups;
920 // If the framework dir doesn't exist, we fail.
921 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
922 if (!Dir) return nullptr;
924 // Otherwise, if it does, remember that this is the right direntry for this
926 CacheLookup.second.Directory = Dir;
929 const FileEntry *FE = nullptr;
932 RelativePath->clear();
933 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
936 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
937 SmallString<1024> HeadersFilename(FrameworkName);
938 HeadersFilename += "Headers/";
941 // Without trailing '/'.
942 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
945 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
946 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
948 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
949 HeadersFilename = FrameworkName;
950 HeadersFilename += "PrivateHeaders/";
953 // Without trailing '/'.
954 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
957 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
958 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
962 // This file is a system header or C++ unfriendly if the old file is.
964 // Note that the temporary 'DirInfo' is required here, as either call to
965 // getFileInfo could resize the vector and we don't want to rely on order
967 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
968 getFileInfo(FE).DirInfo = DirInfo;
970 FrameworkName.pop_back(); // remove the trailing '/'
971 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
972 SuggestedModule, /*IsSystem*/ false))
978 //===----------------------------------------------------------------------===//
979 // File Info Management.
980 //===----------------------------------------------------------------------===//
982 /// \brief Merge the header file info provided by \p OtherHFI into the current
983 /// header file info (\p HFI)
984 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
985 const HeaderFileInfo &OtherHFI) {
986 assert(OtherHFI.External && "expected to merge external HFI");
988 HFI.isImport |= OtherHFI.isImport;
989 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
990 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
991 HFI.NumIncludes += OtherHFI.NumIncludes;
993 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
994 HFI.ControllingMacro = OtherHFI.ControllingMacro;
995 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
998 HFI.DirInfo = OtherHFI.DirInfo;
999 HFI.External = (!HFI.IsValid || HFI.External);
1001 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1003 if (HFI.Framework.empty())
1004 HFI.Framework = OtherHFI.Framework;
1007 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1009 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1010 if (FE->getUID() >= FileInfo.size())
1011 FileInfo.resize(FE->getUID() + 1);
1013 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1014 // FIXME: Use a generation count to check whether this is really up to date.
1015 if (ExternalSource && !HFI->Resolved) {
1016 HFI->Resolved = true;
1017 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1019 HFI = &FileInfo[FE->getUID()];
1020 if (ExternalHFI.External)
1021 mergeHeaderFileInfo(*HFI, ExternalHFI);
1024 HFI->IsValid = true;
1025 // We have local information about this header file, so it's no longer
1026 // strictly external.
1027 HFI->External = false;
1031 const HeaderFileInfo *
1032 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1033 bool WantExternal) const {
1034 // If we have an external source, ensure we have the latest information.
1035 // FIXME: Use a generation count to check whether this is really up to date.
1036 HeaderFileInfo *HFI;
1037 if (ExternalSource) {
1038 if (FE->getUID() >= FileInfo.size()) {
1041 FileInfo.resize(FE->getUID() + 1);
1044 HFI = &FileInfo[FE->getUID()];
1045 if (!WantExternal && (!HFI->IsValid || HFI->External))
1047 if (!HFI->Resolved) {
1048 HFI->Resolved = true;
1049 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1051 HFI = &FileInfo[FE->getUID()];
1052 if (ExternalHFI.External)
1053 mergeHeaderFileInfo(*HFI, ExternalHFI);
1055 } else if (FE->getUID() >= FileInfo.size()) {
1058 HFI = &FileInfo[FE->getUID()];
1061 if (!HFI->IsValid || (HFI->External && !WantExternal))
1067 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1068 // Check if we've ever seen this file as a header.
1069 if (auto *HFI = getExistingFileInfo(File))
1070 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1071 HFI->ControllingMacroID;
1075 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1076 ModuleMap::ModuleHeaderRole Role,
1077 bool isCompilingModuleHeader) {
1078 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1080 // Don't mark the file info as non-external if there's nothing to change.
1081 if (!isCompilingModuleHeader) {
1082 if (!isModularHeader)
1084 auto *HFI = getExistingFileInfo(FE);
1085 if (HFI && HFI->isModuleHeader)
1089 auto &HFI = getFileInfo(FE);
1090 HFI.isModuleHeader |= isModularHeader;
1091 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1094 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1095 const FileEntry *File, bool isImport,
1096 bool ModulesEnabled, Module *M) {
1097 ++NumIncluded; // Count # of attempted #includes.
1099 // Get information about this file.
1100 HeaderFileInfo &FileInfo = getFileInfo(File);
1102 // FIXME: this is a workaround for the lack of proper modules-aware support
1103 // for #import / #pragma once
1104 auto TryEnterImported = [&](void) -> bool {
1105 if (!ModulesEnabled)
1107 // Modules with builtins are special; multiple modules use builtins as
1108 // modular headers, example:
1110 // module stddef { header "stddef.h" export * }
1112 // After module map parsing, this expands to:
1115 // header "/path_to_builtin_dirs/stddef.h"
1116 // textual "stddef.h"
1119 // It's common that libc++ and system modules will both define such
1120 // submodules. Make sure cached results for a builtin header won't
1121 // prevent other builtin modules to potentially enter the builtin header.
1122 // Note that builtins are header guarded and the decision to actually
1123 // enter them is postponed to the controlling macros logic below.
1124 bool TryEnterHdr = false;
1125 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1126 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1127 ModuleMap::isBuiltinHeader(
1128 llvm::sys::path::filename(File->getName()));
1130 // Textual headers can be #imported from different modules. Since ObjC
1131 // headers find in the wild might rely only on #import and do not contain
1132 // controlling macros, be conservative and only try to enter textual headers
1133 // if such macro is present.
1134 if (!FileInfo.isModuleHeader &&
1135 FileInfo.getControllingMacro(ExternalLookup))
1140 // If this is a #import directive, check that we have not already imported
1143 // If this has already been imported, don't import it again.
1144 FileInfo.isImport = true;
1146 // Has this already been #import'ed or #include'd?
1147 if (FileInfo.NumIncludes && !TryEnterImported())
1150 // Otherwise, if this is a #include of a file that was previously #import'd
1151 // or if this is the second #include of a #pragma once file, ignore it.
1152 if (FileInfo.isImport && !TryEnterImported())
1156 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1157 // if the macro that guards it is defined, we know the #include has no effect.
1158 if (const IdentifierInfo *ControllingMacro
1159 = FileInfo.getControllingMacro(ExternalLookup)) {
1160 // If the header corresponds to a module, check whether the macro is already
1161 // defined in that module rather than checking in the current set of visible
1163 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1164 : PP.isMacroDefined(ControllingMacro)) {
1165 ++NumMultiIncludeFileOptzn;
1170 // Increment the number of times this file has been included.
1171 ++FileInfo.NumIncludes;
1176 size_t HeaderSearch::getTotalMemory() const {
1177 return SearchDirs.capacity()
1178 + llvm::capacity_in_bytes(FileInfo)
1179 + llvm::capacity_in_bytes(HeaderMaps)
1180 + LookupFileCache.getAllocator().getTotalMemory()
1181 + FrameworkMap.getAllocator().getTotalMemory();
1184 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1185 return FrameworkNames.insert(Framework).first->first();
1188 bool HeaderSearch::hasModuleMap(StringRef FileName,
1189 const DirectoryEntry *Root,
1191 if (!HSOpts->ImplicitModuleMaps)
1194 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1196 StringRef DirName = FileName;
1198 // Get the parent directory name.
1199 DirName = llvm::sys::path::parent_path(DirName);
1200 if (DirName.empty())
1203 // Determine whether this directory exists.
1204 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1208 // Try to load the module map file in this directory.
1209 switch (loadModuleMapFile(Dir, IsSystem,
1210 llvm::sys::path::extension(Dir->getName()) ==
1212 case LMM_NewlyLoaded:
1213 case LMM_AlreadyLoaded:
1214 // Success. All of the directories we stepped through inherit this module
1216 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1217 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1220 case LMM_NoDirectory:
1221 case LMM_InvalidModuleMap:
1225 // If we hit the top of our search, we're done.
1229 // Keep track of all of the directories we checked, so we can mark them as
1230 // having module maps if we eventually do find a module map.
1231 FixUpDirectories.push_back(Dir);
1235 ModuleMap::KnownHeader
1236 HeaderSearch::findModuleForHeader(const FileEntry *File,
1237 bool AllowTextual) const {
1238 if (ExternalSource) {
1239 // Make sure the external source has handled header info about this file,
1240 // which includes whether the file is part of a module.
1241 (void)getExistingFileInfo(File);
1243 return ModMap.findModuleForHeader(File, AllowTextual);
1246 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1247 Module *RequestingModule,
1248 ModuleMap::KnownHeader *SuggestedModule) {
1249 ModuleMap::KnownHeader Module =
1250 HS.findModuleForHeader(File, /*AllowTextual*/true);
1251 if (SuggestedModule)
1252 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1253 ? ModuleMap::KnownHeader()
1256 // If this module specifies [no_undeclared_includes], we cannot find any
1257 // file that's in a non-dependency module.
1258 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1259 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1260 if (!RequestingModule->directlyUses(Module.getModule())) {
1268 bool HeaderSearch::findUsableModuleForHeader(
1269 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1270 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1271 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1272 // If there is a module that corresponds to this header, suggest it.
1273 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1274 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1279 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1280 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1281 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1282 // If we're supposed to suggest a module, look for one now.
1283 if (needModuleLookup(RequestingModule, SuggestedModule)) {
1284 // Find the top-level framework based on this framework.
1285 SmallVector<std::string, 4> SubmodulePath;
1286 const DirectoryEntry *TopFrameworkDir
1287 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1289 // Determine the name of the top-level framework.
1290 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1292 // Load this framework module. If that succeeds, find the suggested module
1293 // for this header, if any.
1294 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1296 // FIXME: This can find a module not part of ModuleName, which is
1297 // important so that we're consistent about whether this header
1298 // corresponds to a module. Possibly we should lock down framework modules
1299 // so that this is not possible.
1300 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1305 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1306 FileManager &FileMgr) {
1307 StringRef Filename = llvm::sys::path::filename(File->getName());
1308 SmallString<128> PrivateFilename(File->getDir()->getName());
1309 if (Filename == "module.map")
1310 llvm::sys::path::append(PrivateFilename, "module_private.map");
1311 else if (Filename == "module.modulemap")
1312 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1315 return FileMgr.getFile(PrivateFilename);
1318 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1319 // Find the directory for the module. For frameworks, that may require going
1320 // up from the 'Modules' directory.
1321 const DirectoryEntry *Dir = nullptr;
1322 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1323 Dir = FileMgr.getDirectory(".");
1325 Dir = File->getDir();
1326 StringRef DirName(Dir->getName());
1327 if (llvm::sys::path::filename(DirName) == "Modules") {
1328 DirName = llvm::sys::path::parent_path(DirName);
1329 if (DirName.endswith(".framework"))
1330 Dir = FileMgr.getDirectory(DirName);
1331 // FIXME: This assert can fail if there's a race between the above check
1332 // and the removal of the directory.
1333 assert(Dir && "parent must exist");
1337 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
1338 case LMM_AlreadyLoaded:
1339 case LMM_NewlyLoaded:
1341 case LMM_NoDirectory:
1342 case LMM_InvalidModuleMap:
1345 llvm_unreachable("Unknown load module map result");
1348 HeaderSearch::LoadModuleMapResult
1349 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1350 const DirectoryEntry *Dir) {
1351 assert(File && "expected FileEntry");
1353 // Check whether we've already loaded this module map, and mark it as being
1354 // loaded in case we recursively try to load it from itself.
1355 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1356 if (!AddResult.second)
1357 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1359 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
1360 LoadedModuleMaps[File] = false;
1361 return LMM_InvalidModuleMap;
1364 // Try to load a corresponding private module map.
1365 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1366 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1367 LoadedModuleMaps[File] = false;
1368 return LMM_InvalidModuleMap;
1372 // This directory has a module map.
1373 return LMM_NewlyLoaded;
1377 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1378 if (!HSOpts->ImplicitModuleMaps)
1380 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1381 // module.map at the framework root is also accepted.
1382 SmallString<128> ModuleMapFileName(Dir->getName());
1384 llvm::sys::path::append(ModuleMapFileName, "Modules");
1385 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1386 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1389 // Continue to allow module.map
1390 ModuleMapFileName = Dir->getName();
1391 llvm::sys::path::append(ModuleMapFileName, "module.map");
1392 return FileMgr.getFile(ModuleMapFileName);
1395 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1396 const DirectoryEntry *Dir,
1398 if (Module *Module = ModMap.findModule(Name))
1401 // Try to load a module map file.
1402 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1403 case LMM_InvalidModuleMap:
1404 // Try to infer a module map from the framework directory.
1405 if (HSOpts->ImplicitModuleMaps)
1406 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1409 case LMM_AlreadyLoaded:
1410 case LMM_NoDirectory:
1413 case LMM_NewlyLoaded:
1417 return ModMap.findModule(Name);
1421 HeaderSearch::LoadModuleMapResult
1422 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1424 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1425 return loadModuleMapFile(Dir, IsSystem, IsFramework);
1427 return LMM_NoDirectory;
1430 HeaderSearch::LoadModuleMapResult
1431 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1433 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1434 if (KnownDir != DirectoryHasModuleMap.end())
1435 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1437 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1438 LoadModuleMapResult Result =
1439 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1440 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1441 // E.g. Foo.framework/Modules/module.modulemap
1442 // ^Dir ^ModuleMapFile
1443 if (Result == LMM_NewlyLoaded)
1444 DirectoryHasModuleMap[Dir] = true;
1445 else if (Result == LMM_InvalidModuleMap)
1446 DirectoryHasModuleMap[Dir] = false;
1449 return LMM_InvalidModuleMap;
1452 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1455 if (HSOpts->ImplicitModuleMaps) {
1456 // Load module maps for each of the header search directories.
1457 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1458 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1459 if (SearchDirs[Idx].isFramework()) {
1461 SmallString<128> DirNative;
1462 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1465 // Search each of the ".framework" directories to load them as modules.
1466 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1467 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1468 Dir != DirEnd && !EC; Dir.increment(EC)) {
1469 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
1472 const DirectoryEntry *FrameworkDir =
1473 FileMgr.getDirectory(Dir->getName());
1477 // Load this framework module.
1478 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1479 FrameworkDir, IsSystem);
1484 // FIXME: Deal with header maps.
1485 if (SearchDirs[Idx].isHeaderMap())
1488 // Try to load a module map file for the search directory.
1489 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1490 /*IsFramework*/ false);
1492 // Try to load module map files for immediate subdirectories of this
1493 // search directory.
1494 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1498 // Populate the list of modules.
1499 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1500 MEnd = ModMap.module_end();
1502 Modules.push_back(M->getValue());
1506 void HeaderSearch::loadTopLevelSystemModules() {
1507 if (!HSOpts->ImplicitModuleMaps)
1510 // Load module maps for each of the header search directories.
1511 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1512 // We only care about normal header directories.
1513 if (!SearchDirs[Idx].isNormalDir()) {
1517 // Try to load a module map file for the search directory.
1518 loadModuleMapFile(SearchDirs[Idx].getDir(),
1519 SearchDirs[Idx].isSystemHeaderDirectory(),
1520 SearchDirs[Idx].isFramework());
1524 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1525 assert(HSOpts->ImplicitModuleMaps &&
1526 "Should not be loading subdirectory module maps");
1528 if (SearchDir.haveSearchedAllModuleMaps())
1532 SmallString<128> DirNative;
1533 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1534 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1535 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1536 Dir != DirEnd && !EC; Dir.increment(EC)) {
1538 llvm::sys::path::extension(Dir->getName()) == ".framework";
1539 if (IsFramework == SearchDir.isFramework())
1540 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
1541 SearchDir.isFramework());
1544 SearchDir.setSearchedAllModuleMaps(true);
1547 std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1549 // FIXME: We assume that the path name currently cached in the FileEntry is
1550 // the most appropriate one for this analysis (and that it's spelled the same
1551 // way as the corresponding header search path).
1552 StringRef Name = File->getName();
1554 unsigned BestPrefixLength = 0;
1555 unsigned BestSearchDir;
1557 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1558 // FIXME: Support this search within frameworks and header maps.
1559 if (!SearchDirs[I].isNormalDir())
1562 StringRef Dir = SearchDirs[I].getDir()->getName();
1563 for (auto NI = llvm::sys::path::begin(Name),
1564 NE = llvm::sys::path::end(Name),
1565 DI = llvm::sys::path::begin(Dir),
1566 DE = llvm::sys::path::end(Dir);
1567 /*termination condition in loop*/; ++NI, ++DI) {
1568 // '.' components in Name are ignored.
1569 while (NI != NE && *NI == ".")
1574 // '.' components in Dir are ignored.
1575 while (DI != DE && *DI == ".")
1578 // Dir is a prefix of Name, up to '.' components and choice of path
1580 unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1581 if (PrefixLength > BestPrefixLength) {
1582 BestPrefixLength = PrefixLength;
1594 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1595 return Name.drop_front(BestPrefixLength);