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/Diagnostic.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Lex/HeaderMap.h"
19 #include "clang/Lex/HeaderSearchOptions.h"
20 #include "clang/Lex/Lexer.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/Capacity.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
27 #if defined(LLVM_ON_UNIX)
30 using namespace clang;
32 const IdentifierInfo *
33 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
35 return ControllingMacro;
37 if (!ControllingMacroID || !External)
40 ControllingMacro = External->GetIdentifier(ControllingMacroID);
41 return ControllingMacro;
44 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
46 HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
47 FileManager &FM, DiagnosticsEngine &Diags,
48 const LangOptions &LangOpts,
49 const TargetInfo *Target)
50 : HSOpts(HSOpts), FileMgr(FM), FrameworkMap(64),
51 ModMap(FileMgr, *Diags.getClient(), LangOpts, Target, *this)
55 NoCurDirSearch = false;
60 NumMultiIncludeFileOptzn = 0;
61 NumFrameworkLookups = NumSubFrameworkLookups = 0;
64 HeaderSearch::~HeaderSearch() {
66 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
67 delete HeaderMaps[i].second;
70 void HeaderSearch::PrintStats() {
71 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
72 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
73 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
74 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
75 NumOnceOnlyFiles += FileInfo[i].isImport;
76 if (MaxNumIncludes < FileInfo[i].NumIncludes)
77 MaxNumIncludes = FileInfo[i].NumIncludes;
78 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
80 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
81 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
82 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
84 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
85 fprintf(stderr, " %d #includes skipped due to"
86 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
88 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
89 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
92 /// CreateHeaderMap - This method returns a HeaderMap for the specified
93 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
94 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
95 // We expect the number of headermaps to be small, and almost always empty.
96 // If it ever grows, use of a linear search should be re-evaluated.
97 if (!HeaderMaps.empty()) {
98 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
99 // Pointer equality comparison of FileEntries works because they are
100 // already uniqued by inode.
101 if (HeaderMaps[i].first == FE)
102 return HeaderMaps[i].second;
105 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
106 HeaderMaps.push_back(std::make_pair(FE, HM));
113 std::string HeaderSearch::getModuleFileName(Module *Module) {
114 // If we don't have a module cache path, we can't do anything.
115 if (ModuleCachePath.empty())
116 return std::string();
119 SmallString<256> Result(ModuleCachePath);
120 llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
121 return Result.str().str();
124 std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
125 // If we don't have a module cache path, we can't do anything.
126 if (ModuleCachePath.empty())
127 return std::string();
130 SmallString<256> Result(ModuleCachePath);
131 llvm::sys::path::append(Result, ModuleName + ".pcm");
132 return Result.str().str();
135 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
136 // Look in the module map to determine if there is a module by this name.
137 Module *Module = ModMap.findModule(ModuleName);
138 if (Module || !AllowSearch)
141 // Look through the various header search paths to load any available module
142 // maps, searching for a module map that describes this module.
143 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
144 if (SearchDirs[Idx].isFramework()) {
145 // Search for or infer a module map for a framework.
146 SmallString<128> FrameworkDirName;
147 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
148 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
149 if (const DirectoryEntry *FrameworkDir
150 = FileMgr.getDirectory(FrameworkDirName)) {
152 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
153 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
159 // FIXME: Figure out how header maps and module maps will work together.
161 // Only deal with normal search directories.
162 if (!SearchDirs[Idx].isNormalDir())
165 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
166 // Search for a module map file in this directory.
167 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem)
168 == LMM_NewlyLoaded) {
169 // We just loaded a module map file; check whether the module is
171 Module = ModMap.findModule(ModuleName);
176 // Search for a module map in a subdirectory with the same name as the
178 SmallString<128> NestedModuleMapDirName;
179 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
180 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
181 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem) == LMM_NewlyLoaded){
182 // If we just loaded a module map file, look for the module again.
183 Module = ModMap.findModule(ModuleName);
188 // If we've already performed the exhaustive search for module maps in this
189 // search directory, don't do it again.
190 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
193 // Load all module maps in the immediate subdirectories of this search
195 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
197 // Look again for the module.
198 Module = ModMap.findModule(ModuleName);
206 //===----------------------------------------------------------------------===//
207 // File lookup within a DirectoryLookup scope
208 //===----------------------------------------------------------------------===//
210 /// getName - Return the directory or filename corresponding to this lookup
212 const char *DirectoryLookup::getName() const {
214 return getDir()->getName();
216 return getFrameworkDir()->getName();
217 assert(isHeaderMap() && "Unknown DirectoryLookup");
218 return getHeaderMap()->getFileName();
222 /// LookupFile - Lookup the specified file in this search path, returning it
223 /// if it exists or returning null if not.
224 const FileEntry *DirectoryLookup::LookupFile(
227 SmallVectorImpl<char> *SearchPath,
228 SmallVectorImpl<char> *RelativePath,
229 ModuleMap::KnownHeader *SuggestedModule,
230 bool &InUserSpecifiedSystemFramework) const {
231 InUserSpecifiedSystemFramework = false;
233 SmallString<1024> TmpDir;
235 // Concatenate the requested file onto the directory.
236 TmpDir = getDir()->getName();
237 llvm::sys::path::append(TmpDir, Filename);
238 if (SearchPath != NULL) {
239 StringRef SearchPathRef(getDir()->getName());
241 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
243 if (RelativePath != NULL) {
244 RelativePath->clear();
245 RelativePath->append(Filename.begin(), Filename.end());
248 // If we have a module map that might map this header, load it and
249 // check whether we'll have a suggestion for a module.
250 if (SuggestedModule &&
251 HS.hasModuleMap(TmpDir, getDir(), isSystemHeaderDirectory())) {
252 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
257 // If there is a module that corresponds to this header,
259 *SuggestedModule = HS.findModuleForHeader(File);
263 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
267 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
268 SuggestedModule, InUserSpecifiedSystemFramework);
270 assert(isHeaderMap() && "Unknown directory lookup");
271 const FileEntry * const Result = getHeaderMap()->LookupFile(
272 Filename, HS.getFileMgr());
274 if (SearchPath != NULL) {
275 StringRef SearchPathRef(getName());
277 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
279 if (RelativePath != NULL) {
280 RelativePath->clear();
281 RelativePath->append(Filename.begin(), Filename.end());
287 /// \brief Given a framework directory, find the top-most framework directory.
289 /// \param FileMgr The file manager to use for directory lookups.
290 /// \param DirName The name of the framework directory.
291 /// \param SubmodulePath Will be populated with the submodule path from the
292 /// returned top-level module to the originally named framework.
293 static const DirectoryEntry *
294 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
295 SmallVectorImpl<std::string> &SubmodulePath) {
296 assert(llvm::sys::path::extension(DirName) == ".framework" &&
297 "Not a framework directory");
299 // Note: as an egregious but useful hack we use the real path here, because
300 // frameworks moving between top-level frameworks to embedded frameworks tend
301 // to be symlinked, and we base the logical structure of modules on the
302 // physical layout. In particular, we need to deal with crazy includes like
304 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
306 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
307 // which one should access with, e.g.,
309 // #include <Bar/Wibble.h>
311 // Similar issues occur when a top-level framework has moved into an
312 // embedded framework.
313 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
314 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
316 // Get the parent directory name.
317 DirName = llvm::sys::path::parent_path(DirName);
321 // Determine whether this directory exists.
322 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
326 // If this is a framework directory, then we're a subframework of this
328 if (llvm::sys::path::extension(DirName) == ".framework") {
329 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
330 TopFrameworkDir = Dir;
334 return TopFrameworkDir;
337 /// DoFrameworkLookup - Do a lookup of the specified file in the current
338 /// DirectoryLookup, which is a framework directory.
339 const FileEntry *DirectoryLookup::DoFrameworkLookup(
342 SmallVectorImpl<char> *SearchPath,
343 SmallVectorImpl<char> *RelativePath,
344 ModuleMap::KnownHeader *SuggestedModule,
345 bool &InUserSpecifiedSystemFramework) const
347 FileManager &FileMgr = HS.getFileMgr();
349 // Framework names must have a '/' in the filename.
350 size_t SlashPos = Filename.find('/');
351 if (SlashPos == StringRef::npos) return 0;
353 // Find out if this is the home for the specified framework, by checking
354 // HeaderSearch. Possible answers are yes/no and unknown.
355 HeaderSearch::FrameworkCacheEntry &CacheEntry =
356 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
358 // If it is known and in some other directory, fail.
359 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
362 // Otherwise, construct the path to this framework dir.
364 // FrameworkName = "/System/Library/Frameworks/"
365 SmallString<1024> FrameworkName;
366 FrameworkName += getFrameworkDir()->getName();
367 if (FrameworkName.empty() || FrameworkName.back() != '/')
368 FrameworkName.push_back('/');
370 // FrameworkName = "/System/Library/Frameworks/Cocoa"
371 StringRef ModuleName(Filename.begin(), SlashPos);
372 FrameworkName += ModuleName;
374 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
375 FrameworkName += ".framework/";
377 // If the cache entry was unresolved, populate it now.
378 if (CacheEntry.Directory == 0) {
379 HS.IncrementFrameworkLookupCount();
381 // If the framework dir doesn't exist, we fail.
382 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
383 if (Dir == 0) return 0;
385 // Otherwise, if it does, remember that this is the right direntry for this
387 CacheEntry.Directory = getFrameworkDir();
389 // If this is a user search directory, check if the framework has been
390 // user-specified as a system framework.
391 if (getDirCharacteristic() == SrcMgr::C_User) {
392 SmallString<1024> SystemFrameworkMarker(FrameworkName);
393 SystemFrameworkMarker += ".system_framework";
394 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
395 CacheEntry.IsUserSpecifiedSystemFramework = true;
400 // Set the 'user-specified system framework' flag.
401 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
403 if (RelativePath != NULL) {
404 RelativePath->clear();
405 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
408 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
409 unsigned OrigSize = FrameworkName.size();
411 FrameworkName += "Headers/";
413 if (SearchPath != NULL) {
415 // Without trailing '/'.
416 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
419 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
420 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
421 /*openFile=*/!SuggestedModule);
423 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
424 const char *Private = "Private";
425 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
426 Private+strlen(Private));
427 if (SearchPath != NULL)
428 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
429 Private+strlen(Private));
431 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
434 // If we found the header and are allowed to suggest a module, do so now.
435 if (FE && SuggestedModule) {
436 // Find the framework in which this header occurs.
437 StringRef FrameworkPath = FE->getName();
438 bool FoundFramework = false;
440 // Get the parent directory name.
441 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
442 if (FrameworkPath.empty())
445 // Determine whether this directory exists.
446 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
450 // If this is a framework directory, then we're a subframework of this
452 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
453 FoundFramework = true;
458 if (FoundFramework) {
459 // Find the top-level framework based on this framework.
460 SmallVector<std::string, 4> SubmodulePath;
461 const DirectoryEntry *TopFrameworkDir
462 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
464 // Determine the name of the top-level framework.
465 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
467 // Load this framework module. If that succeeds, find the suggested module
468 // for this header, if any.
469 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
470 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
471 *SuggestedModule = HS.findModuleForHeader(FE);
474 *SuggestedModule = HS.findModuleForHeader(FE);
480 void HeaderSearch::setTarget(const TargetInfo &Target) {
481 ModMap.setTarget(Target);
485 //===----------------------------------------------------------------------===//
486 // Header File Location.
487 //===----------------------------------------------------------------------===//
490 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
491 /// return null on failure. isAngled indicates whether the file reference is
492 /// for system \#include's or not (i.e. using <> instead of ""). CurFileEnt, if
493 /// non-null, indicates where the \#including file is, in case a relative search
495 const FileEntry *HeaderSearch::LookupFile(
498 const DirectoryLookup *FromDir,
499 const DirectoryLookup *&CurDir,
500 const FileEntry *CurFileEnt,
501 SmallVectorImpl<char> *SearchPath,
502 SmallVectorImpl<char> *RelativePath,
503 ModuleMap::KnownHeader *SuggestedModule,
507 *SuggestedModule = ModuleMap::KnownHeader();
509 // If 'Filename' is absolute, check to see if it exists and no searching.
510 if (llvm::sys::path::is_absolute(Filename)) {
513 // If this was an #include_next "/absolute/file", fail.
514 if (FromDir) return 0;
516 if (SearchPath != NULL)
518 if (RelativePath != NULL) {
519 RelativePath->clear();
520 RelativePath->append(Filename.begin(), Filename.end());
522 // Otherwise, just return the file.
523 return FileMgr.getFile(Filename, /*openFile=*/true);
526 // Unless disabled, check to see if the file is in the #includer's
527 // directory. This has to be based on CurFileEnt, not CurDir, because
528 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
529 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
530 // This search is not done for <> headers.
531 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
532 SmallString<1024> TmpDir;
533 // Concatenate the requested file onto the directory.
534 // FIXME: Portability. Filename concatenation should be in sys::Path.
535 TmpDir += CurFileEnt->getDir()->getName();
536 TmpDir.push_back('/');
537 TmpDir.append(Filename.begin(), Filename.end());
538 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
539 // Leave CurDir unset.
540 // This file is a system header or C++ unfriendly if the old file is.
542 // Note that we only use one of FromHFI/ToHFI at once, due to potential
543 // reallocation of the underlying vector potentially making the first
544 // reference binding dangling.
545 HeaderFileInfo &FromHFI = getFileInfo(CurFileEnt);
546 unsigned DirInfo = FromHFI.DirInfo;
547 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
548 StringRef Framework = FromHFI.Framework;
550 HeaderFileInfo &ToHFI = getFileInfo(FE);
551 ToHFI.DirInfo = DirInfo;
552 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
553 ToHFI.Framework = Framework;
555 if (SearchPath != NULL) {
556 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
558 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
560 if (RelativePath != NULL) {
561 RelativePath->clear();
562 RelativePath->append(Filename.begin(), Filename.end());
570 // If this is a system #include, ignore the user #include locs.
571 unsigned i = isAngled ? AngledDirIdx : 0;
573 // If this is a #include_next request, start searching after the directory the
574 // file was found in.
576 i = FromDir-&SearchDirs[0];
578 // Cache all of the lookups performed by this method. Many headers are
579 // multiply included, and the "pragma once" optimization prevents them from
580 // being relex/pp'd, but they would still have to search through a
581 // (potentially huge) series of SearchDirs to find it.
582 std::pair<unsigned, unsigned> &CacheLookup =
583 LookupFileCache.GetOrCreateValue(Filename).getValue();
585 // If the entry has been previously looked up, the first value will be
586 // non-zero. If the value is equal to i (the start point of our search), then
587 // this is a matching hit.
588 if (!SkipCache && CacheLookup.first == i+1) {
589 // Skip querying potentially lots of directories for this lookup.
590 i = CacheLookup.second;
592 // Otherwise, this is the first query, or the previous query didn't match
593 // our search start. We will fill in our found location below, so prime the
594 // start point value.
595 CacheLookup.first = i+1;
598 // Check each directory in sequence to see if it contains this file.
599 for (; i != SearchDirs.size(); ++i) {
600 bool InUserSpecifiedSystemFramework = false;
601 const FileEntry *FE =
602 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
603 SuggestedModule, InUserSpecifiedSystemFramework);
606 CurDir = &SearchDirs[i];
608 // This file is a system header or C++ unfriendly if the dir is.
609 HeaderFileInfo &HFI = getFileInfo(FE);
610 HFI.DirInfo = CurDir->getDirCharacteristic();
612 // If the directory characteristic is User but this framework was
613 // user-specified to be treated as a system framework, promote the
615 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
616 HFI.DirInfo = SrcMgr::C_System;
618 // If the filename matches a known system header prefix, override
619 // whether the file is a system header.
620 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
621 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
622 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
628 // If this file is found in a header map and uses the framework style of
629 // includes, then this header is part of a framework we're building.
630 if (CurDir->isIndexHeaderMap()) {
631 size_t SlashPos = Filename.find('/');
632 if (SlashPos != StringRef::npos) {
633 HFI.IndexHeaderMapHeader = 1;
634 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
639 // Remember this location for the next lookup we do.
640 CacheLookup.second = i;
644 // If we are including a file with a quoted include "foo.h" from inside
645 // a header in a framework that is currently being built, and we couldn't
646 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
647 // "Foo" is the name of the framework in which the including header was found.
648 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
649 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
650 if (IncludingHFI.IndexHeaderMapHeader) {
651 SmallString<128> ScratchFilename;
652 ScratchFilename += IncludingHFI.Framework;
653 ScratchFilename += '/';
654 ScratchFilename += Filename;
656 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
657 FromDir, CurDir, CurFileEnt,
658 SearchPath, RelativePath,
660 std::pair<unsigned, unsigned> &CacheLookup
661 = LookupFileCache.GetOrCreateValue(Filename).getValue();
663 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
668 // Otherwise, didn't find it. Remember we didn't find this.
669 CacheLookup.second = SearchDirs.size();
673 /// LookupSubframeworkHeader - Look up a subframework for the specified
674 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
675 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
676 /// is a subframework within Carbon.framework. If so, return the FileEntry
677 /// for the designated file, otherwise return null.
678 const FileEntry *HeaderSearch::
679 LookupSubframeworkHeader(StringRef Filename,
680 const FileEntry *ContextFileEnt,
681 SmallVectorImpl<char> *SearchPath,
682 SmallVectorImpl<char> *RelativePath,
683 ModuleMap::KnownHeader *SuggestedModule) {
684 assert(ContextFileEnt && "No context file?");
686 // Framework names must have a '/' in the filename. Find it.
687 // FIXME: Should we permit '\' on Windows?
688 size_t SlashPos = Filename.find('/');
689 if (SlashPos == StringRef::npos) return 0;
691 // Look up the base framework name of the ContextFileEnt.
692 const char *ContextName = ContextFileEnt->getName();
694 // If the context info wasn't a framework, couldn't be a subframework.
695 const unsigned DotFrameworkLen = 10;
696 const char *FrameworkPos = strstr(ContextName, ".framework");
697 if (FrameworkPos == 0 ||
698 (FrameworkPos[DotFrameworkLen] != '/' &&
699 FrameworkPos[DotFrameworkLen] != '\\'))
702 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
704 // Append Frameworks/HIToolbox.framework/
705 FrameworkName += "Frameworks/";
706 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
707 FrameworkName += ".framework/";
709 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
710 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
712 // Some other location?
713 if (CacheLookup.getValue().Directory &&
714 CacheLookup.getKeyLength() == FrameworkName.size() &&
715 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
716 CacheLookup.getKeyLength()) != 0)
719 // Cache subframework.
720 if (CacheLookup.getValue().Directory == 0) {
721 ++NumSubFrameworkLookups;
723 // If the framework dir doesn't exist, we fail.
724 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
725 if (Dir == 0) return 0;
727 // Otherwise, if it does, remember that this is the right direntry for this
729 CacheLookup.getValue().Directory = Dir;
732 const FileEntry *FE = 0;
734 if (RelativePath != NULL) {
735 RelativePath->clear();
736 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
739 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
740 SmallString<1024> HeadersFilename(FrameworkName);
741 HeadersFilename += "Headers/";
742 if (SearchPath != NULL) {
744 // Without trailing '/'.
745 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
748 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
749 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
751 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
752 HeadersFilename = FrameworkName;
753 HeadersFilename += "PrivateHeaders/";
754 if (SearchPath != NULL) {
756 // Without trailing '/'.
757 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
760 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
761 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
765 // This file is a system header or C++ unfriendly if the old file is.
767 // Note that the temporary 'DirInfo' is required here, as either call to
768 // getFileInfo could resize the vector and we don't want to rely on order
770 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
771 getFileInfo(FE).DirInfo = DirInfo;
773 // If we're supposed to suggest a module, look for one now.
774 if (SuggestedModule) {
775 // Find the top-level framework based on this framework.
776 FrameworkName.pop_back(); // remove the trailing '/'
777 SmallVector<std::string, 4> SubmodulePath;
778 const DirectoryEntry *TopFrameworkDir
779 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
781 // Determine the name of the top-level framework.
782 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
784 // Load this framework module. If that succeeds, find the suggested module
785 // for this header, if any.
786 bool IsSystem = false;
787 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
788 *SuggestedModule = findModuleForHeader(FE);
795 /// \brief Helper static function to normalize a path for injection into
796 /// a synthetic header.
797 /*static*/ std::string
798 HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
799 // Implicit include paths should be resolved relative to the current
800 // working directory first, and then use the regular header search
801 // mechanism. The proper way to handle this is to have the
802 // predefines buffer located at the current working directory, but
803 // it has no file entry. For now, workaround this by using an
804 // absolute path if we find the file here, and otherwise letting
805 // header search handle it.
806 SmallString<128> Path(File);
807 llvm::sys::fs::make_absolute(Path);
809 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
812 FileMgr.getFile(File);
814 return Lexer::Stringify(Path.str());
817 //===----------------------------------------------------------------------===//
818 // File Info Management.
819 //===----------------------------------------------------------------------===//
821 /// \brief Merge the header file info provided by \p OtherHFI into the current
822 /// header file info (\p HFI)
823 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
824 const HeaderFileInfo &OtherHFI) {
825 HFI.isImport |= OtherHFI.isImport;
826 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
827 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
828 HFI.NumIncludes += OtherHFI.NumIncludes;
830 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
831 HFI.ControllingMacro = OtherHFI.ControllingMacro;
832 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
835 if (OtherHFI.External) {
836 HFI.DirInfo = OtherHFI.DirInfo;
837 HFI.External = OtherHFI.External;
838 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
841 if (HFI.Framework.empty())
842 HFI.Framework = OtherHFI.Framework;
847 /// getFileInfo - Return the HeaderFileInfo structure for the specified
849 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
850 if (FE->getUID() >= FileInfo.size())
851 FileInfo.resize(FE->getUID()+1);
853 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
854 if (ExternalSource && !HFI.Resolved)
855 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
859 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
860 // Check if we've ever seen this file as a header.
861 if (File->getUID() >= FileInfo.size())
864 // Resolve header file info from the external source, if needed.
865 HeaderFileInfo &HFI = FileInfo[File->getUID()];
866 if (ExternalSource && !HFI.Resolved)
867 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
869 return HFI.isPragmaOnce || HFI.isImport ||
870 HFI.ControllingMacro || HFI.ControllingMacroID;
873 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
874 ModuleMap::ModuleHeaderRole Role,
875 bool isCompilingModuleHeader) {
876 if (FE->getUID() >= FileInfo.size())
877 FileInfo.resize(FE->getUID()+1);
879 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
880 HFI.isModuleHeader = true;
881 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
882 HFI.setHeaderRole(Role);
885 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
886 ++NumIncluded; // Count # of attempted #includes.
888 // Get information about this file.
889 HeaderFileInfo &FileInfo = getFileInfo(File);
891 // If this is a #import directive, check that we have not already imported
894 // If this has already been imported, don't import it again.
895 FileInfo.isImport = true;
897 // Has this already been #import'ed or #include'd?
898 if (FileInfo.NumIncludes) return false;
900 // Otherwise, if this is a #include of a file that was previously #import'd
901 // or if this is the second #include of a #pragma once file, ignore it.
902 if (FileInfo.isImport)
906 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
907 // if the macro that guards it is defined, we know the #include has no effect.
908 if (const IdentifierInfo *ControllingMacro
909 = FileInfo.getControllingMacro(ExternalLookup))
910 if (ControllingMacro->hasMacroDefinition()) {
911 ++NumMultiIncludeFileOptzn;
915 // Increment the number of times this file has been included.
916 ++FileInfo.NumIncludes;
921 size_t HeaderSearch::getTotalMemory() const {
922 return SearchDirs.capacity()
923 + llvm::capacity_in_bytes(FileInfo)
924 + llvm::capacity_in_bytes(HeaderMaps)
925 + LookupFileCache.getAllocator().getTotalMemory()
926 + FrameworkMap.getAllocator().getTotalMemory();
929 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
930 return FrameworkNames.GetOrCreateValue(Framework).getKey();
933 bool HeaderSearch::hasModuleMap(StringRef FileName,
934 const DirectoryEntry *Root,
936 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
938 StringRef DirName = FileName;
940 // Get the parent directory name.
941 DirName = llvm::sys::path::parent_path(DirName);
945 // Determine whether this directory exists.
946 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
950 // Try to load the module map file in this directory.
951 switch (loadModuleMapFile(Dir, IsSystem)) {
952 case LMM_NewlyLoaded:
953 case LMM_AlreadyLoaded:
954 // Success. All of the directories we stepped through inherit this module
956 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
957 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
961 case LMM_NoDirectory:
962 case LMM_InvalidModuleMap:
966 // If we hit the top of our search, we're done.
970 // Keep track of all of the directories we checked, so we can mark them as
971 // having module maps if we eventually do find a module map.
972 FixUpDirectories.push_back(Dir);
976 ModuleMap::KnownHeader
977 HeaderSearch::findModuleForHeader(const FileEntry *File) const {
978 if (ExternalSource) {
979 // Make sure the external source has handled header info about this file,
980 // which includes whether the file is part of a module.
981 (void)getFileInfo(File);
983 return ModMap.findModuleForHeader(File);
986 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
987 const DirectoryEntry *Dir = File->getDir();
989 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
990 = DirectoryHasModuleMap.find(Dir);
991 if (KnownDir != DirectoryHasModuleMap.end())
992 return !KnownDir->second;
994 bool Result = ModMap.parseModuleMapFile(File, IsSystem);
995 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
996 // If the file we loaded was a module.map, look for the corresponding
997 // module_private.map.
998 SmallString<128> PrivateFilename(Dir->getName());
999 llvm::sys::path::append(PrivateFilename, "module_private.map");
1000 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
1001 Result = ModMap.parseModuleMapFile(PrivateFile, IsSystem);
1004 DirectoryHasModuleMap[Dir] = !Result;
1008 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1009 const DirectoryEntry *Dir,
1011 if (Module *Module = ModMap.findModule(Name))
1014 // Try to load a module map file.
1015 switch (loadModuleMapFile(Dir, IsSystem)) {
1016 case LMM_InvalidModuleMap:
1019 case LMM_AlreadyLoaded:
1020 case LMM_NoDirectory:
1023 case LMM_NewlyLoaded:
1024 return ModMap.findModule(Name);
1027 // Figure out the top-level framework directory and the submodule path from
1028 // that top-level framework to the requested framework.
1029 SmallVector<std::string, 2> SubmodulePath;
1030 SubmodulePath.push_back(Name);
1031 const DirectoryEntry *TopFrameworkDir
1032 = ::getTopFrameworkDir(FileMgr, Dir->getName(), SubmodulePath);
1035 // Try to infer a module map from the top-level framework directory.
1036 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
1043 // Follow the submodule path to find the requested (sub)framework module
1044 // within the top-level framework module.
1045 SubmodulePath.pop_back();
1046 while (!SubmodulePath.empty() && Result) {
1047 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
1048 SubmodulePath.pop_back();
1054 HeaderSearch::LoadModuleMapResult
1055 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem) {
1056 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1057 return loadModuleMapFile(Dir, IsSystem);
1059 return LMM_NoDirectory;
1062 HeaderSearch::LoadModuleMapResult
1063 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem) {
1064 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1065 = DirectoryHasModuleMap.find(Dir);
1066 if (KnownDir != DirectoryHasModuleMap.end())
1067 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1069 SmallString<128> ModuleMapFileName;
1070 ModuleMapFileName += Dir->getName();
1071 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
1072 llvm::sys::path::append(ModuleMapFileName, "module.map");
1073 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
1074 // We have found a module map file. Try to parse it.
1075 if (ModMap.parseModuleMapFile(ModuleMapFile, IsSystem)) {
1076 // No suitable module map.
1077 DirectoryHasModuleMap[Dir] = false;
1078 return LMM_InvalidModuleMap;
1081 // This directory has a module map.
1082 DirectoryHasModuleMap[Dir] = true;
1084 // Check whether there is a private module map that we need to load as well.
1085 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
1086 ModuleMapFileName.end());
1087 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
1088 if (const FileEntry *PrivateModuleMapFile
1089 = FileMgr.getFile(ModuleMapFileName)) {
1090 if (ModMap.parseModuleMapFile(PrivateModuleMapFile, IsSystem)) {
1091 // No suitable module map.
1092 DirectoryHasModuleMap[Dir] = false;
1093 return LMM_InvalidModuleMap;
1097 return LMM_NewlyLoaded;
1100 // No suitable module map.
1101 DirectoryHasModuleMap[Dir] = false;
1102 return LMM_InvalidModuleMap;
1105 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1108 // Load module maps for each of the header search directories.
1109 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1110 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1111 if (SearchDirs[Idx].isFramework()) {
1112 llvm::error_code EC;
1113 SmallString<128> DirNative;
1114 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1117 // Search each of the ".framework" directories to load them as modules.
1118 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1119 Dir != DirEnd && !EC; Dir.increment(EC)) {
1120 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1123 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1127 // Load this framework module.
1128 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1134 // FIXME: Deal with header maps.
1135 if (SearchDirs[Idx].isHeaderMap())
1138 // Try to load a module map file for the search directory.
1139 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem);
1141 // Try to load module map files for immediate subdirectories of this search
1143 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1146 // Populate the list of modules.
1147 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1148 MEnd = ModMap.module_end();
1150 Modules.push_back(M->getValue());
1154 void HeaderSearch::loadTopLevelSystemModules() {
1155 // Load module maps for each of the header search directories.
1156 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1157 // We only care about normal system header directories.
1158 if (!SearchDirs[Idx].isNormalDir() ||
1159 SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_System) {
1163 // Try to load a module map file for the search directory.
1164 loadModuleMapFile(SearchDirs[Idx].getDir(),
1165 SearchDirs[Idx].isSystemHeaderDirectory());
1169 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1170 if (SearchDir.haveSearchedAllModuleMaps())
1173 llvm::error_code EC;
1174 SmallString<128> DirNative;
1175 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1176 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1177 Dir != DirEnd && !EC; Dir.increment(EC)) {
1178 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory());
1181 SearchDir.setSearchedAllModuleMaps(true);