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/HeaderMap.h"
18 #include "clang/Lex/HeaderSearchOptions.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/Lexer.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/Hashing.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/Capacity.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
29 #if defined(LLVM_ON_UNIX)
32 using namespace clang;
34 const IdentifierInfo *
35 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
37 return ControllingMacro;
39 if (!ControllingMacroID || !External)
42 ControllingMacro = External->GetIdentifier(ControllingMacroID);
43 return ControllingMacro;
46 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
48 HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
49 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
50 const LangOptions &LangOpts,
51 const TargetInfo *Target)
52 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
53 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this),
57 NoCurDirSearch = false;
59 ExternalLookup = nullptr;
60 ExternalSource = nullptr;
62 NumMultiIncludeFileOptzn = 0;
63 NumFrameworkLookups = NumSubFrameworkLookups = 0;
66 HeaderSearch::~HeaderSearch() {
68 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
69 delete HeaderMaps[i].second;
72 void HeaderSearch::PrintStats() {
73 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
74 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
75 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
76 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
77 NumOnceOnlyFiles += FileInfo[i].isImport;
78 if (MaxNumIncludes < FileInfo[i].NumIncludes)
79 MaxNumIncludes = FileInfo[i].NumIncludes;
80 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
82 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
83 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
84 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
86 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
87 fprintf(stderr, " %d #includes skipped due to"
88 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
90 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
91 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
94 /// CreateHeaderMap - This method returns a HeaderMap for the specified
95 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
96 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
97 // We expect the number of headermaps to be small, and almost always empty.
98 // If it ever grows, use of a linear search should be re-evaluated.
99 if (!HeaderMaps.empty()) {
100 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
101 // Pointer equality comparison of FileEntries works because they are
102 // already uniqued by inode.
103 if (HeaderMaps[i].first == FE)
104 return HeaderMaps[i].second;
107 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
108 HeaderMaps.push_back(std::make_pair(FE, HM));
115 std::string HeaderSearch::getModuleFileName(Module *Module) {
116 const FileEntry *ModuleMap =
117 getModuleMap().getModuleMapFileForUniquing(Module);
118 return getModuleFileName(Module->Name, ModuleMap->getName());
121 std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
122 StringRef ModuleMapPath) {
123 // If we don't have a module cache path, we can't do anything.
124 if (ModuleCachePath.empty())
125 return std::string();
127 SmallString<256> Result(ModuleCachePath);
128 llvm::sys::fs::make_absolute(Result);
130 if (HSOpts->DisableModuleHash) {
131 llvm::sys::path::append(Result, ModuleName + ".pcm");
133 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
134 // be globally unique to this particular module. To avoid false-negatives
135 // on case-insensitive filesystems, we use lower-case, which is safe because
136 // to cause a collision the modules must have the same name, which is an
137 // error if they are imported in the same translation.
138 SmallString<256> AbsModuleMapPath(ModuleMapPath);
139 llvm::sys::fs::make_absolute(AbsModuleMapPath);
140 llvm::sys::path::native(AbsModuleMapPath);
141 llvm::APInt Code(64, llvm::hash_value(AbsModuleMapPath.str().lower()));
142 SmallString<128> HashStr;
143 Code.toStringUnsigned(HashStr, /*Radix*/36);
144 llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
146 return Result.str().str();
149 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
150 // Look in the module map to determine if there is a module by this name.
151 Module *Module = ModMap.findModule(ModuleName);
152 if (Module || !AllowSearch || !LangOpts.ModulesImplicitMaps)
155 // Look through the various header search paths to load any available module
156 // maps, searching for a module map that describes this module.
157 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
158 if (SearchDirs[Idx].isFramework()) {
159 // Search for or infer a module map for a framework.
160 SmallString<128> FrameworkDirName;
161 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
162 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
163 if (const DirectoryEntry *FrameworkDir
164 = FileMgr.getDirectory(FrameworkDirName)) {
166 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
167 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
173 // FIXME: Figure out how header maps and module maps will work together.
175 // Only deal with normal search directories.
176 if (!SearchDirs[Idx].isNormalDir())
179 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
180 // Search for a module map file in this directory.
181 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
182 /*IsFramework*/false) == LMM_NewlyLoaded) {
183 // We just loaded a module map file; check whether the module is
185 Module = ModMap.findModule(ModuleName);
190 // Search for a module map in a subdirectory with the same name as the
192 SmallString<128> NestedModuleMapDirName;
193 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
194 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
195 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
196 /*IsFramework*/false) == LMM_NewlyLoaded){
197 // If we just loaded a module map file, look for the module again.
198 Module = ModMap.findModule(ModuleName);
203 // If we've already performed the exhaustive search for module maps in this
204 // search directory, don't do it again.
205 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
208 // Load all module maps in the immediate subdirectories of this search
210 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
212 // Look again for the module.
213 Module = ModMap.findModule(ModuleName);
221 //===----------------------------------------------------------------------===//
222 // File lookup within a DirectoryLookup scope
223 //===----------------------------------------------------------------------===//
225 /// getName - Return the directory or filename corresponding to this lookup
227 const char *DirectoryLookup::getName() const {
229 return getDir()->getName();
231 return getFrameworkDir()->getName();
232 assert(isHeaderMap() && "Unknown DirectoryLookup");
233 return getHeaderMap()->getFileName();
236 static const FileEntry *
237 getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
238 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
239 ModuleMap::KnownHeader *SuggestedModule) {
240 // If we have a module map that might map this header, load it and
241 // check whether we'll have a suggestion for a module.
242 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
243 if (SuggestedModule) {
244 const FileEntry *File = HS.getFileMgr().getFile(FileName,
247 // If there is a module that corresponds to this header, suggest it.
248 *SuggestedModule = HS.findModuleForHeader(File);
250 // FIXME: This appears to be a no-op. We loaded the module map for this
251 // directory at the start of this function.
252 if (!SuggestedModule->getModule() &&
253 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
254 *SuggestedModule = HS.findModuleForHeader(File);
260 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
263 /// LookupFile - Lookup the specified file in this search path, returning it
264 /// if it exists or returning null if not.
265 const FileEntry *DirectoryLookup::LookupFile(
268 SmallVectorImpl<char> *SearchPath,
269 SmallVectorImpl<char> *RelativePath,
270 ModuleMap::KnownHeader *SuggestedModule,
271 bool &InUserSpecifiedSystemFramework,
273 SmallVectorImpl<char> &MappedName) const {
274 InUserSpecifiedSystemFramework = false;
275 HasBeenMapped = false;
277 SmallString<1024> TmpDir;
279 // Concatenate the requested file onto the directory.
280 TmpDir = getDir()->getName();
281 llvm::sys::path::append(TmpDir, Filename);
283 StringRef SearchPathRef(getDir()->getName());
285 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
288 RelativePath->clear();
289 RelativePath->append(Filename.begin(), Filename.end());
292 return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
293 isSystemHeaderDirectory(),
298 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
299 SuggestedModule, InUserSpecifiedSystemFramework);
301 assert(isHeaderMap() && "Unknown directory lookup");
302 const HeaderMap *HM = getHeaderMap();
303 SmallString<1024> Path;
304 StringRef Dest = HM->lookupFilename(Filename, Path);
308 const FileEntry *Result;
310 // Check if the headermap maps the filename to a framework include
311 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
312 // framework include.
313 if (llvm::sys::path::is_relative(Dest)) {
315 MappedName.append(Dest.begin(), Dest.end());
316 Filename = StringRef(MappedName.begin(), MappedName.size());
317 HasBeenMapped = true;
318 Result = HM->LookupFile(Filename, HS.getFileMgr());
321 Result = HS.getFileMgr().getFile(Dest);
326 StringRef SearchPathRef(getName());
328 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
331 RelativePath->clear();
332 RelativePath->append(Filename.begin(), Filename.end());
338 /// \brief Given a framework directory, find the top-most framework directory.
340 /// \param FileMgr The file manager to use for directory lookups.
341 /// \param DirName The name of the framework directory.
342 /// \param SubmodulePath Will be populated with the submodule path from the
343 /// returned top-level module to the originally named framework.
344 static const DirectoryEntry *
345 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
346 SmallVectorImpl<std::string> &SubmodulePath) {
347 assert(llvm::sys::path::extension(DirName) == ".framework" &&
348 "Not a framework directory");
350 // Note: as an egregious but useful hack we use the real path here, because
351 // frameworks moving between top-level frameworks to embedded frameworks tend
352 // to be symlinked, and we base the logical structure of modules on the
353 // physical layout. In particular, we need to deal with crazy includes like
355 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
357 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
358 // which one should access with, e.g.,
360 // #include <Bar/Wibble.h>
362 // Similar issues occur when a top-level framework has moved into an
363 // embedded framework.
364 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
365 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
367 // Get the parent directory name.
368 DirName = llvm::sys::path::parent_path(DirName);
372 // Determine whether this directory exists.
373 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
377 // If this is a framework directory, then we're a subframework of this
379 if (llvm::sys::path::extension(DirName) == ".framework") {
380 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
381 TopFrameworkDir = Dir;
385 return TopFrameworkDir;
388 /// DoFrameworkLookup - Do a lookup of the specified file in the current
389 /// DirectoryLookup, which is a framework directory.
390 const FileEntry *DirectoryLookup::DoFrameworkLookup(
393 SmallVectorImpl<char> *SearchPath,
394 SmallVectorImpl<char> *RelativePath,
395 ModuleMap::KnownHeader *SuggestedModule,
396 bool &InUserSpecifiedSystemFramework) const
398 FileManager &FileMgr = HS.getFileMgr();
400 // Framework names must have a '/' in the filename.
401 size_t SlashPos = Filename.find('/');
402 if (SlashPos == StringRef::npos) return nullptr;
404 // Find out if this is the home for the specified framework, by checking
405 // HeaderSearch. Possible answers are yes/no and unknown.
406 HeaderSearch::FrameworkCacheEntry &CacheEntry =
407 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
409 // If it is known and in some other directory, fail.
410 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
413 // Otherwise, construct the path to this framework dir.
415 // FrameworkName = "/System/Library/Frameworks/"
416 SmallString<1024> FrameworkName;
417 FrameworkName += getFrameworkDir()->getName();
418 if (FrameworkName.empty() || FrameworkName.back() != '/')
419 FrameworkName.push_back('/');
421 // FrameworkName = "/System/Library/Frameworks/Cocoa"
422 StringRef ModuleName(Filename.begin(), SlashPos);
423 FrameworkName += ModuleName;
425 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
426 FrameworkName += ".framework/";
428 // If the cache entry was unresolved, populate it now.
429 if (!CacheEntry.Directory) {
430 HS.IncrementFrameworkLookupCount();
432 // If the framework dir doesn't exist, we fail.
433 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
434 if (!Dir) return nullptr;
436 // Otherwise, if it does, remember that this is the right direntry for this
438 CacheEntry.Directory = getFrameworkDir();
440 // If this is a user search directory, check if the framework has been
441 // user-specified as a system framework.
442 if (getDirCharacteristic() == SrcMgr::C_User) {
443 SmallString<1024> SystemFrameworkMarker(FrameworkName);
444 SystemFrameworkMarker += ".system_framework";
445 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
446 CacheEntry.IsUserSpecifiedSystemFramework = true;
451 // Set the 'user-specified system framework' flag.
452 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
455 RelativePath->clear();
456 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
459 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
460 unsigned OrigSize = FrameworkName.size();
462 FrameworkName += "Headers/";
466 // Without trailing '/'.
467 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
470 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
471 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
472 /*openFile=*/!SuggestedModule);
474 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
475 const char *Private = "Private";
476 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
477 Private+strlen(Private));
479 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
480 Private+strlen(Private));
482 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
485 // If we found the header and are allowed to suggest a module, do so now.
486 if (FE && SuggestedModule) {
487 // Find the framework in which this header occurs.
488 StringRef FrameworkPath = FE->getDir()->getName();
489 bool FoundFramework = false;
491 // Determine whether this directory exists.
492 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
496 // If this is a framework directory, then we're a subframework of this
498 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
499 FoundFramework = true;
503 // Get the parent directory name.
504 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
505 if (FrameworkPath.empty())
509 if (FoundFramework) {
510 // Find the top-level framework based on this framework.
511 SmallVector<std::string, 4> SubmodulePath;
512 const DirectoryEntry *TopFrameworkDir
513 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
515 // Determine the name of the top-level framework.
516 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
518 // Load this framework module. If that succeeds, find the suggested module
519 // for this header, if any.
520 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
521 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
522 *SuggestedModule = HS.findModuleForHeader(FE);
525 *SuggestedModule = HS.findModuleForHeader(FE);
531 void HeaderSearch::setTarget(const TargetInfo &Target) {
532 ModMap.setTarget(Target);
536 //===----------------------------------------------------------------------===//
537 // Header File Location.
538 //===----------------------------------------------------------------------===//
540 /// \brief Return true with a diagnostic if the file that MSVC would have found
541 /// fails to match the one that Clang would have found with MSVC header search
543 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
544 const FileEntry *MSFE, const FileEntry *FE,
545 SourceLocation IncludeLoc) {
546 if (MSFE && FE != MSFE) {
547 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
553 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
554 assert(!Str.empty());
555 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
556 std::copy(Str.begin(), Str.end(), CopyStr);
557 CopyStr[Str.size()] = '\0';
561 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
562 /// return null on failure. isAngled indicates whether the file reference is
563 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
564 /// non-empty, indicates where the \#including file(s) are, in case a relative
565 /// search is needed. Microsoft mode will pass all \#including files.
566 const FileEntry *HeaderSearch::LookupFile(
567 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
568 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
569 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
570 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
571 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
573 *SuggestedModule = ModuleMap::KnownHeader();
575 // If 'Filename' is absolute, check to see if it exists and no searching.
576 if (llvm::sys::path::is_absolute(Filename)) {
579 // If this was an #include_next "/absolute/file", fail.
580 if (FromDir) return nullptr;
585 RelativePath->clear();
586 RelativePath->append(Filename.begin(), Filename.end());
588 // Otherwise, just return the file.
589 return FileMgr.getFile(Filename, /*openFile=*/true);
592 // This is the header that MSVC's header search would have found.
593 const FileEntry *MSFE = nullptr;
594 ModuleMap::KnownHeader MSSuggestedModule;
596 // Unless disabled, check to see if the file is in the #includer's
597 // directory. This cannot be based on CurDir, because each includer could be
598 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
599 // include of "baz.h" should resolve to "whatever/foo/baz.h".
600 // This search is not done for <> headers.
601 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
602 SmallString<1024> TmpDir;
604 for (const auto &IncluderAndDir : Includers) {
605 const FileEntry *Includer = IncluderAndDir.first;
607 // Concatenate the requested file onto the directory.
608 // FIXME: Portability. Filename concatenation should be in sys::Path.
609 TmpDir = IncluderAndDir.second->getName();
610 TmpDir.push_back('/');
611 TmpDir.append(Filename.begin(), Filename.end());
613 // FIXME: We don't cache the result of getFileInfo across the call to
614 // getFileAndSuggestModule, because it's a reference to an element of
615 // a container that could be reallocated across this call.
617 // FIXME: If we have no includer, that means we're processing a #include
618 // from a module build. We should treat this as a system header if we're
619 // building a [system] module.
620 bool IncluderIsSystemHeader =
621 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
622 if (const FileEntry *FE = getFileAndSuggestModule(
623 *this, TmpDir.str(), IncluderAndDir.second,
624 IncluderIsSystemHeader, SuggestedModule)) {
626 assert(First && "only first includer can have no file");
630 // Leave CurDir unset.
631 // This file is a system header or C++ unfriendly if the old file is.
633 // Note that we only use one of FromHFI/ToHFI at once, due to potential
634 // reallocation of the underlying vector potentially making the first
635 // reference binding dangling.
636 HeaderFileInfo &FromHFI = getFileInfo(Includer);
637 unsigned DirInfo = FromHFI.DirInfo;
638 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
639 StringRef Framework = FromHFI.Framework;
641 HeaderFileInfo &ToHFI = getFileInfo(FE);
642 ToHFI.DirInfo = DirInfo;
643 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
644 ToHFI.Framework = Framework;
647 StringRef SearchPathRef(IncluderAndDir.second->getName());
649 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
652 RelativePath->clear();
653 RelativePath->append(Filename.begin(), Filename.end());
658 // Otherwise, we found the path via MSVC header search rules. If
659 // -Wmsvc-include is enabled, we have to keep searching to see if we
660 // would've found this header in -I or -isystem directories.
661 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
665 if (SuggestedModule) {
666 MSSuggestedModule = *SuggestedModule;
667 *SuggestedModule = ModuleMap::KnownHeader();
678 // If this is a system #include, ignore the user #include locs.
679 unsigned i = isAngled ? AngledDirIdx : 0;
681 // If this is a #include_next request, start searching after the directory the
682 // file was found in.
684 i = FromDir-&SearchDirs[0];
686 // Cache all of the lookups performed by this method. Many headers are
687 // multiply included, and the "pragma once" optimization prevents them from
688 // being relex/pp'd, but they would still have to search through a
689 // (potentially huge) series of SearchDirs to find it.
690 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
692 // If the entry has been previously looked up, the first value will be
693 // non-zero. If the value is equal to i (the start point of our search), then
694 // this is a matching hit.
695 if (!SkipCache && CacheLookup.StartIdx == i+1) {
696 // Skip querying potentially lots of directories for this lookup.
697 i = CacheLookup.HitIdx;
698 if (CacheLookup.MappedName)
699 Filename = CacheLookup.MappedName;
701 // Otherwise, this is the first query, or the previous query didn't match
702 // our search start. We will fill in our found location below, so prime the
703 // start point value.
704 CacheLookup.reset(/*StartIdx=*/i+1);
707 SmallString<64> MappedName;
709 // Check each directory in sequence to see if it contains this file.
710 for (; i != SearchDirs.size(); ++i) {
711 bool InUserSpecifiedSystemFramework = false;
712 bool HasBeenMapped = false;
713 const FileEntry *FE =
714 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
715 SuggestedModule, InUserSpecifiedSystemFramework,
716 HasBeenMapped, MappedName);
718 CacheLookup.MappedName =
719 copyString(Filename, LookupFileCache.getAllocator());
723 CurDir = &SearchDirs[i];
725 // This file is a system header or C++ unfriendly if the dir is.
726 HeaderFileInfo &HFI = getFileInfo(FE);
727 HFI.DirInfo = CurDir->getDirCharacteristic();
729 // If the directory characteristic is User but this framework was
730 // user-specified to be treated as a system framework, promote the
732 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
733 HFI.DirInfo = SrcMgr::C_System;
735 // If the filename matches a known system header prefix, override
736 // whether the file is a system header.
737 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
738 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
739 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
745 // If this file is found in a header map and uses the framework style of
746 // includes, then this header is part of a framework we're building.
747 if (CurDir->isIndexHeaderMap()) {
748 size_t SlashPos = Filename.find('/');
749 if (SlashPos != StringRef::npos) {
750 HFI.IndexHeaderMapHeader = 1;
751 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
756 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
758 *SuggestedModule = MSSuggestedModule;
762 // Remember this location for the next lookup we do.
763 CacheLookup.HitIdx = i;
767 // If we are including a file with a quoted include "foo.h" from inside
768 // a header in a framework that is currently being built, and we couldn't
769 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
770 // "Foo" is the name of the framework in which the including header was found.
771 if (!Includers.empty() && Includers.front().first && !isAngled &&
772 Filename.find('/') == StringRef::npos) {
773 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
774 if (IncludingHFI.IndexHeaderMapHeader) {
775 SmallString<128> ScratchFilename;
776 ScratchFilename += IncludingHFI.Framework;
777 ScratchFilename += '/';
778 ScratchFilename += Filename;
780 const FileEntry *FE = LookupFile(
781 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
782 Includers.front(), SearchPath, RelativePath, SuggestedModule);
784 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
786 *SuggestedModule = MSSuggestedModule;
790 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
791 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
792 // FIXME: SuggestedModule.
797 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
799 *SuggestedModule = MSSuggestedModule;
803 // Otherwise, didn't find it. Remember we didn't find this.
804 CacheLookup.HitIdx = SearchDirs.size();
808 /// LookupSubframeworkHeader - Look up a subframework for the specified
809 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
810 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
811 /// is a subframework within Carbon.framework. If so, return the FileEntry
812 /// for the designated file, otherwise return null.
813 const FileEntry *HeaderSearch::
814 LookupSubframeworkHeader(StringRef Filename,
815 const FileEntry *ContextFileEnt,
816 SmallVectorImpl<char> *SearchPath,
817 SmallVectorImpl<char> *RelativePath,
818 ModuleMap::KnownHeader *SuggestedModule) {
819 assert(ContextFileEnt && "No context file?");
821 // Framework names must have a '/' in the filename. Find it.
822 // FIXME: Should we permit '\' on Windows?
823 size_t SlashPos = Filename.find('/');
824 if (SlashPos == StringRef::npos) return nullptr;
826 // Look up the base framework name of the ContextFileEnt.
827 const char *ContextName = ContextFileEnt->getName();
829 // If the context info wasn't a framework, couldn't be a subframework.
830 const unsigned DotFrameworkLen = 10;
831 const char *FrameworkPos = strstr(ContextName, ".framework");
832 if (FrameworkPos == nullptr ||
833 (FrameworkPos[DotFrameworkLen] != '/' &&
834 FrameworkPos[DotFrameworkLen] != '\\'))
837 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
839 // Append Frameworks/HIToolbox.framework/
840 FrameworkName += "Frameworks/";
841 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
842 FrameworkName += ".framework/";
845 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
846 FrameworkCacheEntry())).first;
848 // Some other location?
849 if (CacheLookup.second.Directory &&
850 CacheLookup.first().size() == FrameworkName.size() &&
851 memcmp(CacheLookup.first().data(), &FrameworkName[0],
852 CacheLookup.first().size()) != 0)
855 // Cache subframework.
856 if (!CacheLookup.second.Directory) {
857 ++NumSubFrameworkLookups;
859 // If the framework dir doesn't exist, we fail.
860 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
861 if (!Dir) return nullptr;
863 // Otherwise, if it does, remember that this is the right direntry for this
865 CacheLookup.second.Directory = Dir;
868 const FileEntry *FE = nullptr;
871 RelativePath->clear();
872 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
875 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
876 SmallString<1024> HeadersFilename(FrameworkName);
877 HeadersFilename += "Headers/";
880 // Without trailing '/'.
881 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
884 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
885 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
887 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
888 HeadersFilename = FrameworkName;
889 HeadersFilename += "PrivateHeaders/";
892 // Without trailing '/'.
893 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
896 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
897 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
901 // This file is a system header or C++ unfriendly if the old file is.
903 // Note that the temporary 'DirInfo' is required here, as either call to
904 // getFileInfo could resize the vector and we don't want to rely on order
906 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
907 getFileInfo(FE).DirInfo = DirInfo;
909 // If we're supposed to suggest a module, look for one now.
910 if (SuggestedModule) {
911 // Find the top-level framework based on this framework.
912 FrameworkName.pop_back(); // remove the trailing '/'
913 SmallVector<std::string, 4> SubmodulePath;
914 const DirectoryEntry *TopFrameworkDir
915 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
917 // Determine the name of the top-level framework.
918 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
920 // Load this framework module. If that succeeds, find the suggested module
921 // for this header, if any.
922 bool IsSystem = false;
923 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
924 *SuggestedModule = findModuleForHeader(FE);
931 //===----------------------------------------------------------------------===//
932 // File Info Management.
933 //===----------------------------------------------------------------------===//
935 /// \brief Merge the header file info provided by \p OtherHFI into the current
936 /// header file info (\p HFI)
937 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
938 const HeaderFileInfo &OtherHFI) {
939 HFI.isImport |= OtherHFI.isImport;
940 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
941 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
942 HFI.NumIncludes += OtherHFI.NumIncludes;
944 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
945 HFI.ControllingMacro = OtherHFI.ControllingMacro;
946 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
949 if (OtherHFI.External) {
950 HFI.DirInfo = OtherHFI.DirInfo;
951 HFI.External = OtherHFI.External;
952 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
955 if (HFI.Framework.empty())
956 HFI.Framework = OtherHFI.Framework;
961 /// getFileInfo - Return the HeaderFileInfo structure for the specified
963 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
964 if (FE->getUID() >= FileInfo.size())
965 FileInfo.resize(FE->getUID()+1);
967 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
968 if (ExternalSource && !HFI.Resolved)
969 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
974 bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
975 if (FE->getUID() >= FileInfo.size())
977 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
985 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
986 // Check if we've ever seen this file as a header.
987 if (File->getUID() >= FileInfo.size())
990 // Resolve header file info from the external source, if needed.
991 HeaderFileInfo &HFI = FileInfo[File->getUID()];
992 if (ExternalSource && !HFI.Resolved)
993 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
995 return HFI.isPragmaOnce || HFI.isImport ||
996 HFI.ControllingMacro || HFI.ControllingMacroID;
999 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1000 ModuleMap::ModuleHeaderRole Role,
1001 bool isCompilingModuleHeader) {
1002 if (FE->getUID() >= FileInfo.size())
1003 FileInfo.resize(FE->getUID()+1);
1005 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1006 HFI.isModuleHeader = true;
1007 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
1008 HFI.setHeaderRole(Role);
1011 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1012 ++NumIncluded; // Count # of attempted #includes.
1014 // Get information about this file.
1015 HeaderFileInfo &FileInfo = getFileInfo(File);
1017 // If this is a #import directive, check that we have not already imported
1020 // If this has already been imported, don't import it again.
1021 FileInfo.isImport = true;
1023 // Has this already been #import'ed or #include'd?
1024 if (FileInfo.NumIncludes) return false;
1026 // Otherwise, if this is a #include of a file that was previously #import'd
1027 // or if this is the second #include of a #pragma once file, ignore it.
1028 if (FileInfo.isImport)
1032 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1033 // if the macro that guards it is defined, we know the #include has no effect.
1034 if (const IdentifierInfo *ControllingMacro
1035 = FileInfo.getControllingMacro(ExternalLookup))
1036 if (ControllingMacro->hasMacroDefinition()) {
1037 ++NumMultiIncludeFileOptzn;
1041 // Increment the number of times this file has been included.
1042 ++FileInfo.NumIncludes;
1047 size_t HeaderSearch::getTotalMemory() const {
1048 return SearchDirs.capacity()
1049 + llvm::capacity_in_bytes(FileInfo)
1050 + llvm::capacity_in_bytes(HeaderMaps)
1051 + LookupFileCache.getAllocator().getTotalMemory()
1052 + FrameworkMap.getAllocator().getTotalMemory();
1055 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1056 return FrameworkNames.insert(Framework).first->first();
1059 bool HeaderSearch::hasModuleMap(StringRef FileName,
1060 const DirectoryEntry *Root,
1062 if (!enabledModules() || !LangOpts.ModulesImplicitMaps)
1065 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1067 StringRef DirName = FileName;
1069 // Get the parent directory name.
1070 DirName = llvm::sys::path::parent_path(DirName);
1071 if (DirName.empty())
1074 // Determine whether this directory exists.
1075 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1079 // Try to load the module map file in this directory.
1080 switch (loadModuleMapFile(Dir, IsSystem,
1081 llvm::sys::path::extension(Dir->getName()) ==
1083 case LMM_NewlyLoaded:
1084 case LMM_AlreadyLoaded:
1085 // Success. All of the directories we stepped through inherit this module
1087 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1088 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1091 case LMM_NoDirectory:
1092 case LMM_InvalidModuleMap:
1096 // If we hit the top of our search, we're done.
1100 // Keep track of all of the directories we checked, so we can mark them as
1101 // having module maps if we eventually do find a module map.
1102 FixUpDirectories.push_back(Dir);
1106 ModuleMap::KnownHeader
1107 HeaderSearch::findModuleForHeader(const FileEntry *File) const {
1108 if (ExternalSource) {
1109 // Make sure the external source has handled header info about this file,
1110 // which includes whether the file is part of a module.
1111 (void)getFileInfo(File);
1113 return ModMap.findModuleForHeader(File);
1116 static const FileEntry *getPrivateModuleMap(StringRef ModuleMapPath,
1117 const DirectoryEntry *Directory,
1118 FileManager &FileMgr) {
1119 StringRef Filename = llvm::sys::path::filename(ModuleMapPath);
1120 SmallString<128> PrivateFilename(Directory->getName());
1121 if (Filename == "module.map")
1122 llvm::sys::path::append(PrivateFilename, "module_private.map");
1123 else if (Filename == "module.modulemap")
1124 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1127 return FileMgr.getFile(PrivateFilename);
1130 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1131 switch (loadModuleMapFileImpl(File, IsSystem)) {
1132 case LMM_AlreadyLoaded:
1133 case LMM_NewlyLoaded:
1135 case LMM_NoDirectory:
1136 case LMM_InvalidModuleMap:
1139 llvm_unreachable("Unknown load module map result");
1142 HeaderSearch::LoadModuleMapResult
1143 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem) {
1144 assert(File && "expected FileEntry");
1146 // Check whether we've already loaded this module map, and mark it as being
1147 // loaded in case we recursively try to load it from itself.
1148 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1149 if (!AddResult.second)
1150 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1152 if (ModMap.parseModuleMapFile(File, IsSystem)) {
1153 LoadedModuleMaps[File] = false;
1154 return LMM_InvalidModuleMap;
1157 // Try to load a corresponding private module map.
1158 if (const FileEntry *PMMFile =
1159 getPrivateModuleMap(File->getName(), File->getDir(), FileMgr)) {
1160 if (ModMap.parseModuleMapFile(PMMFile, IsSystem)) {
1161 LoadedModuleMaps[File] = false;
1162 return LMM_InvalidModuleMap;
1166 // This directory has a module map.
1167 return LMM_NewlyLoaded;
1171 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1172 if (!LangOpts.ModulesImplicitMaps)
1174 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1175 // module.map at the framework root is also accepted.
1176 SmallString<128> ModuleMapFileName(Dir->getName());
1178 llvm::sys::path::append(ModuleMapFileName, "Modules");
1179 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1180 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1183 // Continue to allow module.map
1184 ModuleMapFileName = Dir->getName();
1185 llvm::sys::path::append(ModuleMapFileName, "module.map");
1186 return FileMgr.getFile(ModuleMapFileName);
1189 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1190 const DirectoryEntry *Dir,
1192 if (Module *Module = ModMap.findModule(Name))
1195 // Try to load a module map file.
1196 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1197 case LMM_InvalidModuleMap:
1200 case LMM_AlreadyLoaded:
1201 case LMM_NoDirectory:
1204 case LMM_NewlyLoaded:
1205 return ModMap.findModule(Name);
1209 // Try to infer a module map from the framework directory.
1210 if (LangOpts.ModulesImplicitMaps)
1211 return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
1217 HeaderSearch::LoadModuleMapResult
1218 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1220 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1221 return loadModuleMapFile(Dir, IsSystem, IsFramework);
1223 return LMM_NoDirectory;
1226 HeaderSearch::LoadModuleMapResult
1227 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1229 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1230 if (KnownDir != DirectoryHasModuleMap.end())
1231 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1233 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1234 LoadModuleMapResult Result = loadModuleMapFileImpl(ModuleMapFile, IsSystem);
1235 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1236 // E.g. Foo.framework/Modules/module.modulemap
1237 // ^Dir ^ModuleMapFile
1238 if (Result == LMM_NewlyLoaded)
1239 DirectoryHasModuleMap[Dir] = true;
1240 else if (Result == LMM_InvalidModuleMap)
1241 DirectoryHasModuleMap[Dir] = false;
1244 return LMM_InvalidModuleMap;
1247 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1250 if (LangOpts.ModulesImplicitMaps) {
1251 // Load module maps for each of the header search directories.
1252 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1253 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1254 if (SearchDirs[Idx].isFramework()) {
1256 SmallString<128> DirNative;
1257 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1260 // Search each of the ".framework" directories to load them as modules.
1261 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1262 Dir != DirEnd && !EC; Dir.increment(EC)) {
1263 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1266 const DirectoryEntry *FrameworkDir =
1267 FileMgr.getDirectory(Dir->path());
1271 // Load this framework module.
1272 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1278 // FIXME: Deal with header maps.
1279 if (SearchDirs[Idx].isHeaderMap())
1282 // Try to load a module map file for the search directory.
1283 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1284 /*IsFramework*/ false);
1286 // Try to load module map files for immediate subdirectories of this
1287 // search directory.
1288 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1292 // Populate the list of modules.
1293 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1294 MEnd = ModMap.module_end();
1296 Modules.push_back(M->getValue());
1300 void HeaderSearch::loadTopLevelSystemModules() {
1301 if (!LangOpts.ModulesImplicitMaps)
1304 // Load module maps for each of the header search directories.
1305 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1306 // We only care about normal header directories.
1307 if (!SearchDirs[Idx].isNormalDir()) {
1311 // Try to load a module map file for the search directory.
1312 loadModuleMapFile(SearchDirs[Idx].getDir(),
1313 SearchDirs[Idx].isSystemHeaderDirectory(),
1314 SearchDirs[Idx].isFramework());
1318 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1319 assert(LangOpts.ModulesImplicitMaps &&
1320 "Should not be loading subdirectory module maps");
1322 if (SearchDir.haveSearchedAllModuleMaps())
1326 SmallString<128> DirNative;
1327 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1328 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1329 Dir != DirEnd && !EC; Dir.increment(EC)) {
1330 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1331 SearchDir.isFramework());
1334 SearchDir.setSearchedAllModuleMaps(true);