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"
29 #include "llvm/Support/raw_ostream.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 External->updateOutOfDateIdentifier(
41 *const_cast<IdentifierInfo *>(ControllingMacro));
42 return ControllingMacro;
45 if (!ControllingMacroID || !External)
48 ControllingMacro = External->GetIdentifier(ControllingMacroID);
49 return ControllingMacro;
52 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
54 HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
55 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
56 const LangOptions &LangOpts,
57 const TargetInfo *Target)
58 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
59 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this),
63 NoCurDirSearch = false;
65 ExternalLookup = nullptr;
66 ExternalSource = nullptr;
68 NumMultiIncludeFileOptzn = 0;
69 NumFrameworkLookups = NumSubFrameworkLookups = 0;
72 HeaderSearch::~HeaderSearch() {
74 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
75 delete HeaderMaps[i].second;
78 void HeaderSearch::PrintStats() {
79 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
80 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
81 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
82 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
83 NumOnceOnlyFiles += FileInfo[i].isImport;
84 if (MaxNumIncludes < FileInfo[i].NumIncludes)
85 MaxNumIncludes = FileInfo[i].NumIncludes;
86 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
88 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
89 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
90 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
92 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
93 fprintf(stderr, " %d #includes skipped due to"
94 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
96 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
97 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
100 /// CreateHeaderMap - This method returns a HeaderMap for the specified
101 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
102 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
103 // We expect the number of headermaps to be small, and almost always empty.
104 // If it ever grows, use of a linear search should be re-evaluated.
105 if (!HeaderMaps.empty()) {
106 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
107 // Pointer equality comparison of FileEntries works because they are
108 // already uniqued by inode.
109 if (HeaderMaps[i].first == FE)
110 return HeaderMaps[i].second;
113 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
114 HeaderMaps.push_back(std::make_pair(FE, HM));
121 std::string HeaderSearch::getModuleFileName(Module *Module) {
122 const FileEntry *ModuleMap =
123 getModuleMap().getModuleMapFileForUniquing(Module);
124 return getModuleFileName(Module->Name, ModuleMap->getName());
127 std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
128 StringRef ModuleMapPath) {
129 // If we don't have a module cache path, we can't do anything.
130 if (ModuleCachePath.empty())
131 return std::string();
133 SmallString<256> Result(ModuleCachePath);
134 llvm::sys::fs::make_absolute(Result);
136 if (HSOpts->DisableModuleHash) {
137 llvm::sys::path::append(Result, ModuleName + ".pcm");
139 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
140 // ideally be globally unique to this particular module. Name collisions
141 // in the hash are safe (because any translation unit can only import one
142 // module with each name), but result in a loss of caching.
144 // To avoid false-negatives, we form as canonical a path as we can, and map
145 // to lower-case in case we're on a case-insensitive file system.
147 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
149 return std::string();
150 auto DirName = FileMgr.getCanonicalName(Dir);
151 auto FileName = llvm::sys::path::filename(ModuleMapPath);
153 llvm::hash_code Hash =
154 llvm::hash_combine(DirName.lower(), FileName.lower());
156 SmallString<128> HashStr;
157 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
158 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
160 return Result.str().str();
163 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
164 // Look in the module map to determine if there is a module by this name.
165 Module *Module = ModMap.findModule(ModuleName);
166 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
169 // Look through the various header search paths to load any available module
170 // maps, searching for a module map that describes this module.
171 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
172 if (SearchDirs[Idx].isFramework()) {
173 // Search for or infer a module map for a framework.
174 SmallString<128> FrameworkDirName;
175 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
176 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
177 if (const DirectoryEntry *FrameworkDir
178 = FileMgr.getDirectory(FrameworkDirName)) {
180 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
181 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
187 // FIXME: Figure out how header maps and module maps will work together.
189 // Only deal with normal search directories.
190 if (!SearchDirs[Idx].isNormalDir())
193 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
194 // Search for a module map file in this directory.
195 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
196 /*IsFramework*/false) == LMM_NewlyLoaded) {
197 // We just loaded a module map file; check whether the module is
199 Module = ModMap.findModule(ModuleName);
204 // Search for a module map in a subdirectory with the same name as the
206 SmallString<128> NestedModuleMapDirName;
207 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
208 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
209 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
210 /*IsFramework*/false) == LMM_NewlyLoaded){
211 // If we just loaded a module map file, look for the module again.
212 Module = ModMap.findModule(ModuleName);
217 // If we've already performed the exhaustive search for module maps in this
218 // search directory, don't do it again.
219 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
222 // Load all module maps in the immediate subdirectories of this search
224 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
226 // Look again for the module.
227 Module = ModMap.findModule(ModuleName);
235 //===----------------------------------------------------------------------===//
236 // File lookup within a DirectoryLookup scope
237 //===----------------------------------------------------------------------===//
239 /// getName - Return the directory or filename corresponding to this lookup
241 const char *DirectoryLookup::getName() const {
243 return getDir()->getName();
245 return getFrameworkDir()->getName();
246 assert(isHeaderMap() && "Unknown DirectoryLookup");
247 return getHeaderMap()->getFileName();
250 static const FileEntry *
251 getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
252 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
253 ModuleMap::KnownHeader *SuggestedModule) {
254 // If we have a module map that might map this header, load it and
255 // check whether we'll have a suggestion for a module.
256 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
257 if (SuggestedModule) {
258 const FileEntry *File = HS.getFileMgr().getFile(FileName,
261 // If there is a module that corresponds to this header, suggest it.
262 *SuggestedModule = HS.findModuleForHeader(File);
264 // FIXME: This appears to be a no-op. We loaded the module map for this
265 // directory at the start of this function.
266 if (!SuggestedModule->getModule() &&
267 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
268 *SuggestedModule = HS.findModuleForHeader(File);
274 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
277 /// LookupFile - Lookup the specified file in this search path, returning it
278 /// if it exists or returning null if not.
279 const FileEntry *DirectoryLookup::LookupFile(
282 SmallVectorImpl<char> *SearchPath,
283 SmallVectorImpl<char> *RelativePath,
284 ModuleMap::KnownHeader *SuggestedModule,
285 bool &InUserSpecifiedSystemFramework,
287 SmallVectorImpl<char> &MappedName) const {
288 InUserSpecifiedSystemFramework = false;
289 HasBeenMapped = false;
291 SmallString<1024> TmpDir;
293 // Concatenate the requested file onto the directory.
294 TmpDir = getDir()->getName();
295 llvm::sys::path::append(TmpDir, Filename);
297 StringRef SearchPathRef(getDir()->getName());
299 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
302 RelativePath->clear();
303 RelativePath->append(Filename.begin(), Filename.end());
306 return getFileAndSuggestModule(HS, TmpDir, getDir(),
307 isSystemHeaderDirectory(),
312 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
313 SuggestedModule, InUserSpecifiedSystemFramework);
315 assert(isHeaderMap() && "Unknown directory lookup");
316 const HeaderMap *HM = getHeaderMap();
317 SmallString<1024> Path;
318 StringRef Dest = HM->lookupFilename(Filename, Path);
322 const FileEntry *Result;
324 // Check if the headermap maps the filename to a framework include
325 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
326 // framework include.
327 if (llvm::sys::path::is_relative(Dest)) {
329 MappedName.append(Dest.begin(), Dest.end());
330 Filename = StringRef(MappedName.begin(), MappedName.size());
331 HasBeenMapped = true;
332 Result = HM->LookupFile(Filename, HS.getFileMgr());
335 Result = HS.getFileMgr().getFile(Dest);
340 StringRef SearchPathRef(getName());
342 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
345 RelativePath->clear();
346 RelativePath->append(Filename.begin(), Filename.end());
352 /// \brief Given a framework directory, find the top-most framework directory.
354 /// \param FileMgr The file manager to use for directory lookups.
355 /// \param DirName The name of the framework directory.
356 /// \param SubmodulePath Will be populated with the submodule path from the
357 /// returned top-level module to the originally named framework.
358 static const DirectoryEntry *
359 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
360 SmallVectorImpl<std::string> &SubmodulePath) {
361 assert(llvm::sys::path::extension(DirName) == ".framework" &&
362 "Not a framework directory");
364 // Note: as an egregious but useful hack we use the real path here, because
365 // frameworks moving between top-level frameworks to embedded frameworks tend
366 // to be symlinked, and we base the logical structure of modules on the
367 // physical layout. In particular, we need to deal with crazy includes like
369 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
371 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
372 // which one should access with, e.g.,
374 // #include <Bar/Wibble.h>
376 // Similar issues occur when a top-level framework has moved into an
377 // embedded framework.
378 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
379 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
381 // Get the parent directory name.
382 DirName = llvm::sys::path::parent_path(DirName);
386 // Determine whether this directory exists.
387 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
391 // If this is a framework directory, then we're a subframework of this
393 if (llvm::sys::path::extension(DirName) == ".framework") {
394 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
395 TopFrameworkDir = Dir;
399 return TopFrameworkDir;
402 /// DoFrameworkLookup - Do a lookup of the specified file in the current
403 /// DirectoryLookup, which is a framework directory.
404 const FileEntry *DirectoryLookup::DoFrameworkLookup(
407 SmallVectorImpl<char> *SearchPath,
408 SmallVectorImpl<char> *RelativePath,
409 ModuleMap::KnownHeader *SuggestedModule,
410 bool &InUserSpecifiedSystemFramework) const
412 FileManager &FileMgr = HS.getFileMgr();
414 // Framework names must have a '/' in the filename.
415 size_t SlashPos = Filename.find('/');
416 if (SlashPos == StringRef::npos) return nullptr;
418 // Find out if this is the home for the specified framework, by checking
419 // HeaderSearch. Possible answers are yes/no and unknown.
420 HeaderSearch::FrameworkCacheEntry &CacheEntry =
421 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
423 // If it is known and in some other directory, fail.
424 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
427 // Otherwise, construct the path to this framework dir.
429 // FrameworkName = "/System/Library/Frameworks/"
430 SmallString<1024> FrameworkName;
431 FrameworkName += getFrameworkDir()->getName();
432 if (FrameworkName.empty() || FrameworkName.back() != '/')
433 FrameworkName.push_back('/');
435 // FrameworkName = "/System/Library/Frameworks/Cocoa"
436 StringRef ModuleName(Filename.begin(), SlashPos);
437 FrameworkName += ModuleName;
439 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
440 FrameworkName += ".framework/";
442 // If the cache entry was unresolved, populate it now.
443 if (!CacheEntry.Directory) {
444 HS.IncrementFrameworkLookupCount();
446 // If the framework dir doesn't exist, we fail.
447 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
448 if (!Dir) return nullptr;
450 // Otherwise, if it does, remember that this is the right direntry for this
452 CacheEntry.Directory = getFrameworkDir();
454 // If this is a user search directory, check if the framework has been
455 // user-specified as a system framework.
456 if (getDirCharacteristic() == SrcMgr::C_User) {
457 SmallString<1024> SystemFrameworkMarker(FrameworkName);
458 SystemFrameworkMarker += ".system_framework";
459 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
460 CacheEntry.IsUserSpecifiedSystemFramework = true;
465 // Set the 'user-specified system framework' flag.
466 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
469 RelativePath->clear();
470 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
473 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
474 unsigned OrigSize = FrameworkName.size();
476 FrameworkName += "Headers/";
480 // Without trailing '/'.
481 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
484 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
485 const FileEntry *FE = FileMgr.getFile(FrameworkName,
486 /*openFile=*/!SuggestedModule);
488 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
489 const char *Private = "Private";
490 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
491 Private+strlen(Private));
493 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
494 Private+strlen(Private));
496 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
499 // If we found the header and are allowed to suggest a module, do so now.
500 if (FE && SuggestedModule) {
501 // Find the framework in which this header occurs.
502 StringRef FrameworkPath = FE->getDir()->getName();
503 bool FoundFramework = false;
505 // Determine whether this directory exists.
506 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
510 // If this is a framework directory, then we're a subframework of this
512 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
513 FoundFramework = true;
517 // Get the parent directory name.
518 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
519 if (FrameworkPath.empty())
523 if (FoundFramework) {
524 // Find the top-level framework based on this framework.
525 SmallVector<std::string, 4> SubmodulePath;
526 const DirectoryEntry *TopFrameworkDir
527 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
529 // Determine the name of the top-level framework.
530 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
532 // Load this framework module. If that succeeds, find the suggested module
533 // for this header, if any.
534 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
535 HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem);
537 // FIXME: This can find a module not part of ModuleName, which is
538 // important so that we're consistent about whether this header
539 // corresponds to a module. Possibly we should lock down framework modules
540 // so that this is not possible.
541 *SuggestedModule = HS.findModuleForHeader(FE);
543 *SuggestedModule = HS.findModuleForHeader(FE);
549 void HeaderSearch::setTarget(const TargetInfo &Target) {
550 ModMap.setTarget(Target);
554 //===----------------------------------------------------------------------===//
555 // Header File Location.
556 //===----------------------------------------------------------------------===//
558 /// \brief Return true with a diagnostic if the file that MSVC would have found
559 /// fails to match the one that Clang would have found with MSVC header search
561 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
562 const FileEntry *MSFE, const FileEntry *FE,
563 SourceLocation IncludeLoc) {
564 if (MSFE && FE != MSFE) {
565 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
571 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
572 assert(!Str.empty());
573 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
574 std::copy(Str.begin(), Str.end(), CopyStr);
575 CopyStr[Str.size()] = '\0';
579 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
580 /// return null on failure. isAngled indicates whether the file reference is
581 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
582 /// non-empty, indicates where the \#including file(s) are, in case a relative
583 /// search is needed. Microsoft mode will pass all \#including files.
584 const FileEntry *HeaderSearch::LookupFile(
585 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
586 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
587 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
588 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
589 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
591 *SuggestedModule = ModuleMap::KnownHeader();
593 // If 'Filename' is absolute, check to see if it exists and no searching.
594 if (llvm::sys::path::is_absolute(Filename)) {
597 // If this was an #include_next "/absolute/file", fail.
598 if (FromDir) return nullptr;
603 RelativePath->clear();
604 RelativePath->append(Filename.begin(), Filename.end());
606 // Otherwise, just return the file.
607 const FileEntry *File = FileMgr.getFile(Filename, /*openFile=*/true);
608 if (File && SuggestedModule) {
609 // If there is a module that corresponds to this header, suggest it.
610 hasModuleMap(Filename, File->getDir(), /*SystemHeaderDir*/false);
611 *SuggestedModule = findModuleForHeader(File);
616 // This is the header that MSVC's header search would have found.
617 const FileEntry *MSFE = nullptr;
618 ModuleMap::KnownHeader MSSuggestedModule;
620 // Unless disabled, check to see if the file is in the #includer's
621 // directory. This cannot be based on CurDir, because each includer could be
622 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
623 // include of "baz.h" should resolve to "whatever/foo/baz.h".
624 // This search is not done for <> headers.
625 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
626 SmallString<1024> TmpDir;
628 for (const auto &IncluderAndDir : Includers) {
629 const FileEntry *Includer = IncluderAndDir.first;
631 // Concatenate the requested file onto the directory.
632 // FIXME: Portability. Filename concatenation should be in sys::Path.
633 TmpDir = IncluderAndDir.second->getName();
634 TmpDir.push_back('/');
635 TmpDir.append(Filename.begin(), Filename.end());
637 // FIXME: We don't cache the result of getFileInfo across the call to
638 // getFileAndSuggestModule, because it's a reference to an element of
639 // a container that could be reallocated across this call.
641 // FIXME: If we have no includer, that means we're processing a #include
642 // from a module build. We should treat this as a system header if we're
643 // building a [system] module.
644 bool IncluderIsSystemHeader =
645 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
646 if (const FileEntry *FE = getFileAndSuggestModule(
647 *this, TmpDir, IncluderAndDir.second,
648 IncluderIsSystemHeader, SuggestedModule)) {
650 assert(First && "only first includer can have no file");
654 // Leave CurDir unset.
655 // This file is a system header or C++ unfriendly if the old file is.
657 // Note that we only use one of FromHFI/ToHFI at once, due to potential
658 // reallocation of the underlying vector potentially making the first
659 // reference binding dangling.
660 HeaderFileInfo &FromHFI = getFileInfo(Includer);
661 unsigned DirInfo = FromHFI.DirInfo;
662 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
663 StringRef Framework = FromHFI.Framework;
665 HeaderFileInfo &ToHFI = getFileInfo(FE);
666 ToHFI.DirInfo = DirInfo;
667 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
668 ToHFI.Framework = Framework;
671 StringRef SearchPathRef(IncluderAndDir.second->getName());
673 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
676 RelativePath->clear();
677 RelativePath->append(Filename.begin(), Filename.end());
682 // Otherwise, we found the path via MSVC header search rules. If
683 // -Wmsvc-include is enabled, we have to keep searching to see if we
684 // would've found this header in -I or -isystem directories.
685 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
689 if (SuggestedModule) {
690 MSSuggestedModule = *SuggestedModule;
691 *SuggestedModule = ModuleMap::KnownHeader();
702 // If this is a system #include, ignore the user #include locs.
703 unsigned i = isAngled ? AngledDirIdx : 0;
705 // If this is a #include_next request, start searching after the directory the
706 // file was found in.
708 i = FromDir-&SearchDirs[0];
710 // Cache all of the lookups performed by this method. Many headers are
711 // multiply included, and the "pragma once" optimization prevents them from
712 // being relex/pp'd, but they would still have to search through a
713 // (potentially huge) series of SearchDirs to find it.
714 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
716 // If the entry has been previously looked up, the first value will be
717 // non-zero. If the value is equal to i (the start point of our search), then
718 // this is a matching hit.
719 if (!SkipCache && CacheLookup.StartIdx == i+1) {
720 // Skip querying potentially lots of directories for this lookup.
721 i = CacheLookup.HitIdx;
722 if (CacheLookup.MappedName)
723 Filename = CacheLookup.MappedName;
725 // Otherwise, this is the first query, or the previous query didn't match
726 // our search start. We will fill in our found location below, so prime the
727 // start point value.
728 CacheLookup.reset(/*StartIdx=*/i+1);
731 SmallString<64> MappedName;
733 // Check each directory in sequence to see if it contains this file.
734 for (; i != SearchDirs.size(); ++i) {
735 bool InUserSpecifiedSystemFramework = false;
736 bool HasBeenMapped = false;
737 const FileEntry *FE =
738 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
739 SuggestedModule, InUserSpecifiedSystemFramework,
740 HasBeenMapped, MappedName);
742 CacheLookup.MappedName =
743 copyString(Filename, LookupFileCache.getAllocator());
747 CurDir = &SearchDirs[i];
749 // This file is a system header or C++ unfriendly if the dir is.
750 HeaderFileInfo &HFI = getFileInfo(FE);
751 HFI.DirInfo = CurDir->getDirCharacteristic();
753 // If the directory characteristic is User but this framework was
754 // user-specified to be treated as a system framework, promote the
756 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
757 HFI.DirInfo = SrcMgr::C_System;
759 // If the filename matches a known system header prefix, override
760 // whether the file is a system header.
761 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
762 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
763 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
769 // If this file is found in a header map and uses the framework style of
770 // includes, then this header is part of a framework we're building.
771 if (CurDir->isIndexHeaderMap()) {
772 size_t SlashPos = Filename.find('/');
773 if (SlashPos != StringRef::npos) {
774 HFI.IndexHeaderMapHeader = 1;
775 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
780 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
782 *SuggestedModule = MSSuggestedModule;
786 // Remember this location for the next lookup we do.
787 CacheLookup.HitIdx = i;
791 // If we are including a file with a quoted include "foo.h" from inside
792 // a header in a framework that is currently being built, and we couldn't
793 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
794 // "Foo" is the name of the framework in which the including header was found.
795 if (!Includers.empty() && Includers.front().first && !isAngled &&
796 Filename.find('/') == StringRef::npos) {
797 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
798 if (IncludingHFI.IndexHeaderMapHeader) {
799 SmallString<128> ScratchFilename;
800 ScratchFilename += IncludingHFI.Framework;
801 ScratchFilename += '/';
802 ScratchFilename += Filename;
804 const FileEntry *FE = LookupFile(
805 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
806 Includers.front(), SearchPath, RelativePath, SuggestedModule);
808 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
810 *SuggestedModule = MSSuggestedModule;
814 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
815 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
816 // FIXME: SuggestedModule.
821 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
823 *SuggestedModule = MSSuggestedModule;
827 // Otherwise, didn't find it. Remember we didn't find this.
828 CacheLookup.HitIdx = SearchDirs.size();
832 /// LookupSubframeworkHeader - Look up a subframework for the specified
833 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
834 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
835 /// is a subframework within Carbon.framework. If so, return the FileEntry
836 /// for the designated file, otherwise return null.
837 const FileEntry *HeaderSearch::
838 LookupSubframeworkHeader(StringRef Filename,
839 const FileEntry *ContextFileEnt,
840 SmallVectorImpl<char> *SearchPath,
841 SmallVectorImpl<char> *RelativePath,
842 ModuleMap::KnownHeader *SuggestedModule) {
843 assert(ContextFileEnt && "No context file?");
845 // Framework names must have a '/' in the filename. Find it.
846 // FIXME: Should we permit '\' on Windows?
847 size_t SlashPos = Filename.find('/');
848 if (SlashPos == StringRef::npos) return nullptr;
850 // Look up the base framework name of the ContextFileEnt.
851 const char *ContextName = ContextFileEnt->getName();
853 // If the context info wasn't a framework, couldn't be a subframework.
854 const unsigned DotFrameworkLen = 10;
855 const char *FrameworkPos = strstr(ContextName, ".framework");
856 if (FrameworkPos == nullptr ||
857 (FrameworkPos[DotFrameworkLen] != '/' &&
858 FrameworkPos[DotFrameworkLen] != '\\'))
861 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
863 // Append Frameworks/HIToolbox.framework/
864 FrameworkName += "Frameworks/";
865 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
866 FrameworkName += ".framework/";
869 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
870 FrameworkCacheEntry())).first;
872 // Some other location?
873 if (CacheLookup.second.Directory &&
874 CacheLookup.first().size() == FrameworkName.size() &&
875 memcmp(CacheLookup.first().data(), &FrameworkName[0],
876 CacheLookup.first().size()) != 0)
879 // Cache subframework.
880 if (!CacheLookup.second.Directory) {
881 ++NumSubFrameworkLookups;
883 // If the framework dir doesn't exist, we fail.
884 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
885 if (!Dir) return nullptr;
887 // Otherwise, if it does, remember that this is the right direntry for this
889 CacheLookup.second.Directory = Dir;
892 const FileEntry *FE = nullptr;
895 RelativePath->clear();
896 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
899 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
900 SmallString<1024> HeadersFilename(FrameworkName);
901 HeadersFilename += "Headers/";
904 // Without trailing '/'.
905 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
908 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
909 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
911 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
912 HeadersFilename = FrameworkName;
913 HeadersFilename += "PrivateHeaders/";
916 // Without trailing '/'.
917 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
920 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
921 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
925 // This file is a system header or C++ unfriendly if the old file is.
927 // Note that the temporary 'DirInfo' is required here, as either call to
928 // getFileInfo could resize the vector and we don't want to rely on order
930 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
931 getFileInfo(FE).DirInfo = DirInfo;
933 // If we're supposed to suggest a module, look for one now.
934 if (SuggestedModule) {
935 // Find the top-level framework based on this framework.
936 FrameworkName.pop_back(); // remove the trailing '/'
937 SmallVector<std::string, 4> SubmodulePath;
938 const DirectoryEntry *TopFrameworkDir
939 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
941 // Determine the name of the top-level framework.
942 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
944 // Load this framework module. If that succeeds, find the suggested module
945 // for this header, if any.
946 bool IsSystem = false;
947 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
948 *SuggestedModule = findModuleForHeader(FE);
955 //===----------------------------------------------------------------------===//
956 // File Info Management.
957 //===----------------------------------------------------------------------===//
959 /// \brief Merge the header file info provided by \p OtherHFI into the current
960 /// header file info (\p HFI)
961 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
962 const HeaderFileInfo &OtherHFI) {
963 HFI.isImport |= OtherHFI.isImport;
964 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
965 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
966 HFI.NumIncludes += OtherHFI.NumIncludes;
968 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
969 HFI.ControllingMacro = OtherHFI.ControllingMacro;
970 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
973 if (OtherHFI.External) {
974 HFI.DirInfo = OtherHFI.DirInfo;
975 HFI.External = OtherHFI.External;
976 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
979 if (HFI.Framework.empty())
980 HFI.Framework = OtherHFI.Framework;
985 /// getFileInfo - Return the HeaderFileInfo structure for the specified
987 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
988 if (FE->getUID() >= FileInfo.size())
989 FileInfo.resize(FE->getUID()+1);
991 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
992 if (ExternalSource && !HFI.Resolved)
993 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
998 bool HeaderSearch::tryGetFileInfo(const FileEntry *FE,
999 HeaderFileInfo &Result) const {
1000 if (FE->getUID() >= FileInfo.size())
1002 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1010 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1011 // Check if we've ever seen this file as a header.
1012 if (File->getUID() >= FileInfo.size())
1015 // Resolve header file info from the external source, if needed.
1016 HeaderFileInfo &HFI = FileInfo[File->getUID()];
1017 if (ExternalSource && !HFI.Resolved)
1018 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
1020 return HFI.isPragmaOnce || HFI.isImport ||
1021 HFI.ControllingMacro || HFI.ControllingMacroID;
1024 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1025 ModuleMap::ModuleHeaderRole Role,
1026 bool isCompilingModuleHeader) {
1027 if (FE->getUID() >= FileInfo.size())
1028 FileInfo.resize(FE->getUID()+1);
1030 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1031 HFI.isModuleHeader = true;
1032 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1033 HFI.setHeaderRole(Role);
1036 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1037 const FileEntry *File,
1038 bool isImport, Module *M) {
1039 ++NumIncluded; // Count # of attempted #includes.
1041 // Get information about this file.
1042 HeaderFileInfo &FileInfo = getFileInfo(File);
1044 // If this is a #import directive, check that we have not already imported
1047 // If this has already been imported, don't import it again.
1048 FileInfo.isImport = true;
1050 // Has this already been #import'ed or #include'd?
1051 if (FileInfo.NumIncludes) return false;
1053 // Otherwise, if this is a #include of a file that was previously #import'd
1054 // or if this is the second #include of a #pragma once file, ignore it.
1055 if (FileInfo.isImport)
1059 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1060 // if the macro that guards it is defined, we know the #include has no effect.
1061 if (const IdentifierInfo *ControllingMacro
1062 = FileInfo.getControllingMacro(ExternalLookup)) {
1063 // If the header corresponds to a module, check whether the macro is already
1064 // defined in that module rather than checking in the current set of visible
1066 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1067 : PP.isMacroDefined(ControllingMacro)) {
1068 ++NumMultiIncludeFileOptzn;
1073 // Increment the number of times this file has been included.
1074 ++FileInfo.NumIncludes;
1079 size_t HeaderSearch::getTotalMemory() const {
1080 return SearchDirs.capacity()
1081 + llvm::capacity_in_bytes(FileInfo)
1082 + llvm::capacity_in_bytes(HeaderMaps)
1083 + LookupFileCache.getAllocator().getTotalMemory()
1084 + FrameworkMap.getAllocator().getTotalMemory();
1087 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1088 return FrameworkNames.insert(Framework).first->first();
1091 bool HeaderSearch::hasModuleMap(StringRef FileName,
1092 const DirectoryEntry *Root,
1094 if (!HSOpts->ImplicitModuleMaps)
1097 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1099 StringRef DirName = FileName;
1101 // Get the parent directory name.
1102 DirName = llvm::sys::path::parent_path(DirName);
1103 if (DirName.empty())
1106 // Determine whether this directory exists.
1107 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1111 // Try to load the module map file in this directory.
1112 switch (loadModuleMapFile(Dir, IsSystem,
1113 llvm::sys::path::extension(Dir->getName()) ==
1115 case LMM_NewlyLoaded:
1116 case LMM_AlreadyLoaded:
1117 // Success. All of the directories we stepped through inherit this module
1119 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1120 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1123 case LMM_NoDirectory:
1124 case LMM_InvalidModuleMap:
1128 // If we hit the top of our search, we're done.
1132 // Keep track of all of the directories we checked, so we can mark them as
1133 // having module maps if we eventually do find a module map.
1134 FixUpDirectories.push_back(Dir);
1138 ModuleMap::KnownHeader
1139 HeaderSearch::findModuleForHeader(const FileEntry *File) const {
1140 if (ExternalSource) {
1141 // Make sure the external source has handled header info about this file,
1142 // which includes whether the file is part of a module.
1143 (void)getFileInfo(File);
1145 return ModMap.findModuleForHeader(File);
1148 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1149 FileManager &FileMgr) {
1150 StringRef Filename = llvm::sys::path::filename(File->getName());
1151 SmallString<128> PrivateFilename(File->getDir()->getName());
1152 if (Filename == "module.map")
1153 llvm::sys::path::append(PrivateFilename, "module_private.map");
1154 else if (Filename == "module.modulemap")
1155 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1158 return FileMgr.getFile(PrivateFilename);
1161 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1162 // Find the directory for the module. For frameworks, that may require going
1163 // up from the 'Modules' directory.
1164 const DirectoryEntry *Dir = nullptr;
1165 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1166 Dir = FileMgr.getDirectory(".");
1168 Dir = File->getDir();
1169 StringRef DirName(Dir->getName());
1170 if (llvm::sys::path::filename(DirName) == "Modules") {
1171 DirName = llvm::sys::path::parent_path(DirName);
1172 if (DirName.endswith(".framework"))
1173 Dir = FileMgr.getDirectory(DirName);
1174 // FIXME: This assert can fail if there's a race between the above check
1175 // and the removal of the directory.
1176 assert(Dir && "parent must exist");
1180 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
1181 case LMM_AlreadyLoaded:
1182 case LMM_NewlyLoaded:
1184 case LMM_NoDirectory:
1185 case LMM_InvalidModuleMap:
1188 llvm_unreachable("Unknown load module map result");
1191 HeaderSearch::LoadModuleMapResult
1192 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1193 const DirectoryEntry *Dir) {
1194 assert(File && "expected FileEntry");
1196 // Check whether we've already loaded this module map, and mark it as being
1197 // loaded in case we recursively try to load it from itself.
1198 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1199 if (!AddResult.second)
1200 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1202 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
1203 LoadedModuleMaps[File] = false;
1204 return LMM_InvalidModuleMap;
1207 // Try to load a corresponding private module map.
1208 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1209 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1210 LoadedModuleMaps[File] = false;
1211 return LMM_InvalidModuleMap;
1215 // This directory has a module map.
1216 return LMM_NewlyLoaded;
1220 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1221 if (!HSOpts->ImplicitModuleMaps)
1223 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1224 // module.map at the framework root is also accepted.
1225 SmallString<128> ModuleMapFileName(Dir->getName());
1227 llvm::sys::path::append(ModuleMapFileName, "Modules");
1228 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1229 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1232 // Continue to allow module.map
1233 ModuleMapFileName = Dir->getName();
1234 llvm::sys::path::append(ModuleMapFileName, "module.map");
1235 return FileMgr.getFile(ModuleMapFileName);
1238 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1239 const DirectoryEntry *Dir,
1241 if (Module *Module = ModMap.findModule(Name))
1244 // Try to load a module map file.
1245 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1246 case LMM_InvalidModuleMap:
1247 // Try to infer a module map from the framework directory.
1248 if (HSOpts->ImplicitModuleMaps)
1249 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1252 case LMM_AlreadyLoaded:
1253 case LMM_NoDirectory:
1256 case LMM_NewlyLoaded:
1260 return ModMap.findModule(Name);
1264 HeaderSearch::LoadModuleMapResult
1265 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1267 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1268 return loadModuleMapFile(Dir, IsSystem, IsFramework);
1270 return LMM_NoDirectory;
1273 HeaderSearch::LoadModuleMapResult
1274 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1276 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1277 if (KnownDir != DirectoryHasModuleMap.end())
1278 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1280 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1281 LoadModuleMapResult Result =
1282 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1283 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1284 // E.g. Foo.framework/Modules/module.modulemap
1285 // ^Dir ^ModuleMapFile
1286 if (Result == LMM_NewlyLoaded)
1287 DirectoryHasModuleMap[Dir] = true;
1288 else if (Result == LMM_InvalidModuleMap)
1289 DirectoryHasModuleMap[Dir] = false;
1292 return LMM_InvalidModuleMap;
1295 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1298 if (HSOpts->ImplicitModuleMaps) {
1299 // Load module maps for each of the header search directories.
1300 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1301 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1302 if (SearchDirs[Idx].isFramework()) {
1304 SmallString<128> DirNative;
1305 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1308 // Search each of the ".framework" directories to load them as modules.
1309 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd;
1310 Dir != DirEnd && !EC; Dir.increment(EC)) {
1311 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1314 const DirectoryEntry *FrameworkDir =
1315 FileMgr.getDirectory(Dir->path());
1319 // Load this framework module.
1320 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1326 // FIXME: Deal with header maps.
1327 if (SearchDirs[Idx].isHeaderMap())
1330 // Try to load a module map file for the search directory.
1331 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1332 /*IsFramework*/ false);
1334 // Try to load module map files for immediate subdirectories of this
1335 // search directory.
1336 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1340 // Populate the list of modules.
1341 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1342 MEnd = ModMap.module_end();
1344 Modules.push_back(M->getValue());
1348 void HeaderSearch::loadTopLevelSystemModules() {
1349 if (!HSOpts->ImplicitModuleMaps)
1352 // Load module maps for each of the header search directories.
1353 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1354 // We only care about normal header directories.
1355 if (!SearchDirs[Idx].isNormalDir()) {
1359 // Try to load a module map file for the search directory.
1360 loadModuleMapFile(SearchDirs[Idx].getDir(),
1361 SearchDirs[Idx].isSystemHeaderDirectory(),
1362 SearchDirs[Idx].isFramework());
1366 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1367 assert(HSOpts->ImplicitModuleMaps &&
1368 "Should not be loading subdirectory module maps");
1370 if (SearchDir.haveSearchedAllModuleMaps())
1374 SmallString<128> DirNative;
1375 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1376 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd;
1377 Dir != DirEnd && !EC; Dir.increment(EC)) {
1378 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1379 if (IsFramework == SearchDir.isFramework())
1380 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1381 SearchDir.isFramework());
1384 SearchDir.setSearchedAllModuleMaps(true);