blob: ff63bdb31b5ccc5dbdb82f2826c7d4ea5025224c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencer5f016e22007-07-11 17:01:13 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattner822da612007-12-17 06:36:45 +000015#include "clang/Lex/HeaderMap.h"
Chandler Carruthcb381ea2011-12-09 01:33:57 +000016#include "clang/Lex/Lexer.h"
Douglas Gregora30cfe52011-11-11 19:10:28 +000017#include "clang/Basic/Diagnostic.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000018#include "clang/Basic/FileManager.h"
19#include "clang/Basic/IdentifierTable.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000020#include "llvm/Support/FileSystem.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000021#include "llvm/Support/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/ADT/SmallString.h"
Ted Kremenekeabea452011-07-27 18:41:18 +000023#include "llvm/Support/Capacity.h"
Chris Lattner3daed522009-03-02 22:20:04 +000024#include <cstdio>
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Douglas Gregor8c5a7602009-04-25 23:30:02 +000027const IdentifierInfo *
28HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
29 if (ControllingMacro)
30 return ControllingMacro;
31
32 if (!ControllingMacroID || !External)
33 return 0;
34
35 ControllingMacro = External->GetIdentifier(ControllingMacroID);
36 return ControllingMacro;
37}
38
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000039ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
40
Douglas Gregor51f564f2011-12-31 04:05:44 +000041HeaderSearch::HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags,
42 const LangOptions &LangOpts)
Douglas Gregora30cfe52011-11-11 19:10:28 +000043 : FileMgr(FM), Diags(Diags), FrameworkMap(64),
Douglas Gregor51f564f2011-12-31 04:05:44 +000044 ModMap(FileMgr, *Diags.getClient(), LangOpts)
Douglas Gregor8e238062011-11-11 00:35:06 +000045{
Nico Weber74a5fd82011-05-24 04:31:14 +000046 AngledDirIdx = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000047 SystemDirIdx = 0;
48 NoCurDirSearch = false;
Mike Stump1eb44332009-09-09 15:08:12 +000049
Douglas Gregor8c5a7602009-04-25 23:30:02 +000050 ExternalLookup = 0;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000051 ExternalSource = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000052 NumIncluded = 0;
53 NumMultiIncludeFileOptzn = 0;
54 NumFrameworkLookups = NumSubFrameworkLookups = 0;
55}
56
Chris Lattner822da612007-12-17 06:36:45 +000057HeaderSearch::~HeaderSearch() {
58 // Delete headermaps.
59 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
60 delete HeaderMaps[i].second;
61}
Mike Stump1eb44332009-09-09 15:08:12 +000062
Reid Spencer5f016e22007-07-11 17:01:13 +000063void HeaderSearch::PrintStats() {
64 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
65 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
66 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
67 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
68 NumOnceOnlyFiles += FileInfo[i].isImport;
69 if (MaxNumIncludes < FileInfo[i].NumIncludes)
70 MaxNumIncludes = FileInfo[i].NumIncludes;
71 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
72 }
73 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
74 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
75 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Reid Spencer5f016e22007-07-11 17:01:13 +000077 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
78 fprintf(stderr, " %d #includes skipped due to"
79 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump1eb44332009-09-09 15:08:12 +000080
Reid Spencer5f016e22007-07-11 17:01:13 +000081 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
82 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
83}
84
Chris Lattner822da612007-12-17 06:36:45 +000085/// CreateHeaderMap - This method returns a HeaderMap for the specified
86/// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000087const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000088 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000089 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000090 if (!HeaderMaps.empty()) {
91 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000092 // Pointer equality comparison of FileEntries works because they are
93 // already uniqued by inode.
Mike Stump1eb44332009-09-09 15:08:12 +000094 if (HeaderMaps[i].first == FE)
Chris Lattner822da612007-12-17 06:36:45 +000095 return HeaderMaps[i].second;
96 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Chris Lattner39b49bc2010-11-23 08:35:12 +000098 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattner822da612007-12-17 06:36:45 +000099 HeaderMaps.push_back(std::make_pair(FE, HM));
100 return HM;
101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner822da612007-12-17 06:36:45 +0000103 return 0;
104}
105
Douglas Gregor21cae202011-09-12 23:31:24 +0000106const FileEntry *HeaderSearch::lookupModule(StringRef ModuleName,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000107 Module *&Module,
Douglas Gregora4d36a62011-11-28 23:16:06 +0000108 std::string *ModuleFileName) {
109 Module = 0;
110
Douglas Gregor9a6da692011-09-12 20:41:59 +0000111 // If we don't have a module cache path, we can't do anything.
Douglas Gregor6e975c42011-09-13 23:15:45 +0000112 if (ModuleCachePath.empty()) {
113 if (ModuleFileName)
114 ModuleFileName->clear();
Douglas Gregor9a6da692011-09-12 20:41:59 +0000115 return 0;
Douglas Gregor6e975c42011-09-13 23:15:45 +0000116 }
117
Douglas Gregor21cae202011-09-12 23:31:24 +0000118 // Try to find the module path.
Douglas Gregor9a6da692011-09-12 20:41:59 +0000119 llvm::SmallString<256> FileName(ModuleCachePath);
120 llvm::sys::path::append(FileName, ModuleName + ".pcm");
Douglas Gregor6e975c42011-09-13 23:15:45 +0000121 if (ModuleFileName)
122 *ModuleFileName = FileName.str();
Douglas Gregora4d36a62011-11-28 23:16:06 +0000123
Douglas Gregorcf70d782011-11-12 00:05:07 +0000124 // Look in the module map to determine if there is a module by this name.
Douglas Gregora4d36a62011-11-28 23:16:06 +0000125 Module = ModMap.findModule(ModuleName);
Douglas Gregorcf70d782011-11-12 00:05:07 +0000126 if (!Module) {
127 // Look through the various header search paths to load any avaiable module
128 // maps, searching for a module map that describes this module.
129 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregora4d36a62011-11-28 23:16:06 +0000130 if (SearchDirs[Idx].isFramework()) {
131 // Search for or infer a module map for a framework.
132 llvm::SmallString<128> FrameworkDirName;
133 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
134 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
135 if (const DirectoryEntry *FrameworkDir
136 = FileMgr.getDirectory(FrameworkDirName)) {
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000137 bool IsSystem
138 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
139 Module = getFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregora4d36a62011-11-28 23:16:06 +0000140 if (Module)
141 break;
142 }
143 }
144
145 // FIXME: Figure out how header maps and module maps will work together.
146
147 // Only deal with normal search directories.
Douglas Gregorcf70d782011-11-12 00:05:07 +0000148 if (!SearchDirs[Idx].isNormalDir())
149 continue;
150
Douglas Gregor26697972011-11-12 00:22:19 +0000151 // Search for a module map file in this directory.
152 if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) {
153 // We just loaded a module map file; check whether the module is
154 // available now.
Douglas Gregorcf70d782011-11-12 00:05:07 +0000155 Module = ModMap.findModule(ModuleName);
156 if (Module)
157 break;
158 }
Douglas Gregor26697972011-11-12 00:22:19 +0000159
Douglas Gregorcf70d782011-11-12 00:05:07 +0000160 // Search for a module map in a subdirectory with the same name as the
161 // module.
162 llvm::SmallString<128> NestedModuleMapDirName;
163 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
164 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Douglas Gregor26697972011-11-12 00:22:19 +0000165 if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) {
166 // If we just loaded a module map file, look for the module again.
Douglas Gregorcf70d782011-11-12 00:05:07 +0000167 Module = ModMap.findModule(ModuleName);
168 if (Module)
169 break;
170 }
171 }
172 }
173
Douglas Gregora4d36a62011-11-28 23:16:06 +0000174 // Look for the module file in the module cache.
175 // FIXME: If we didn't find a description of the module itself, should we
176 // even try to find the module in the cache?
177 return getFileMgr().getFile(FileName, /*OpenFile=*/false,
178 /*CacheFailure=*/false);
Douglas Gregor9a6da692011-09-12 20:41:59 +0000179}
180
Chris Lattnerdf772332007-12-17 07:52:39 +0000181//===----------------------------------------------------------------------===//
182// File lookup within a DirectoryLookup scope
183//===----------------------------------------------------------------------===//
184
Chris Lattner3af66a92007-12-17 17:57:27 +0000185/// getName - Return the directory or filename corresponding to this lookup
186/// object.
187const char *DirectoryLookup::getName() const {
188 if (isNormalDir())
189 return getDir()->getName();
190 if (isFramework())
191 return getFrameworkDir()->getName();
192 assert(isHeaderMap() && "Unknown DirectoryLookup");
193 return getHeaderMap()->getFileName();
194}
195
196
Chris Lattnerdf772332007-12-17 07:52:39 +0000197/// LookupFile - Lookup the specified file in this search path, returning it
198/// if it exists or returning null if not.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000199const FileEntry *DirectoryLookup::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000200 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000201 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000202 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000203 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000204 Module **SuggestedModule) const {
Chris Lattnerdf772332007-12-17 07:52:39 +0000205 llvm::SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000206 if (isNormalDir()) {
207 // Concatenate the requested file onto the directory.
Eli Friedmana6e023c2011-07-08 20:17:28 +0000208 TmpDir = getDir()->getName();
209 llvm::sys::path::append(TmpDir, Filename);
Manuel Klimek74124942011-04-26 21:50:03 +0000210 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000211 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000212 SearchPath->clear();
213 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
214 }
215 if (RelativePath != NULL) {
216 RelativePath->clear();
217 RelativePath->append(Filename.begin(), Filename.end());
218 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000219
220 // If we have a module map that might map this header, load it and
221 // check whether we'll have a suggestion for a module.
222 if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
223 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
224 /*openFile=*/false);
225 if (!File)
226 return File;
227
228 // If there is a module that corresponds to this header,
229 // suggest it.
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000230 *SuggestedModule = HS.findModuleForHeader(File);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000231 return File;
232 }
233
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000234 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattnerafded5b2007-12-17 08:13:48 +0000237 if (isFramework())
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000238 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000239 SuggestedModule);
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000241 assert(isHeaderMap() && "Unknown directory lookup");
Manuel Klimek74124942011-04-26 21:50:03 +0000242 const FileEntry * const Result = getHeaderMap()->LookupFile(
243 Filename, HS.getFileMgr());
244 if (Result) {
245 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000246 StringRef SearchPathRef(getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000247 SearchPath->clear();
248 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
249 }
250 if (RelativePath != NULL) {
251 RelativePath->clear();
252 RelativePath->append(Filename.begin(), Filename.end());
253 }
254 }
255 return Result;
Chris Lattnerdf772332007-12-17 07:52:39 +0000256}
257
258
Chris Lattnerafded5b2007-12-17 08:13:48 +0000259/// DoFrameworkLookup - Do a lookup of the specified file in the current
260/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000261const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000262 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000263 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000264 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000265 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000266 Module **SuggestedModule) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000267{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000268 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000271 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000272 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerafded5b2007-12-17 08:13:48 +0000274 // Find out if this is the home for the specified framework, by checking
275 // HeaderSearch. Possible answer are yes/no and unknown.
Mike Stump1eb44332009-09-09 15:08:12 +0000276 const DirectoryEntry *&FrameworkDirCache =
Chris Lattnera1394812010-01-10 01:35:12 +0000277 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattnerafded5b2007-12-17 08:13:48 +0000279 // If it is known and in some other directory, fail.
280 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerafded5b2007-12-17 08:13:48 +0000283 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 // FrameworkName = "/System/Library/Frameworks/"
286 llvm::SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000287 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 if (FrameworkName.empty() || FrameworkName.back() != '/')
289 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000292 StringRef ModuleName(Filename.begin(), SlashPos);
293 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
296 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattnerafded5b2007-12-17 08:13:48 +0000298 // If the cache entry is still unresolved, query to see if the cache entry is
299 // still unresolved. If so, check its existence now.
300 if (FrameworkDirCache == 0) {
301 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // If the framework dir doesn't exist, we fail.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000304 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000305 bool Exists;
306 if (llvm::sys::fs::exists(FrameworkName.str(), Exists) || !Exists)
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 // Otherwise, if it does, remember that this is the right direntry for this
310 // framework.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000311 FrameworkDirCache = getFrameworkDir();
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Manuel Klimek74124942011-04-26 21:50:03 +0000314 if (RelativePath != NULL) {
315 RelativePath->clear();
316 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
317 }
318
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000319 // If we're allowed to look for modules, try to load or create the module
320 // corresponding to this framework.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000321 Module *Module = 0;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000322 if (SuggestedModule) {
323 if (const DirectoryEntry *FrameworkDir
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000324 = FileMgr.getDirectory(FrameworkName)) {
325 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
326 Module = HS.getFrameworkModule(ModuleName, FrameworkDir, IsSystem);
327 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000328 }
329
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
331 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000334
335 if (SearchPath != NULL) {
336 SearchPath->clear();
337 // Without trailing '/'.
338 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
339 }
340
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000341 // Determine whether this is the module we're building or not.
Douglas Gregor09833922011-12-06 17:31:28 +0000342 bool AutomaticImport = Module;
Chris Lattnera1394812010-01-10 01:35:12 +0000343 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000344 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000345 /*openFile=*/!AutomaticImport)) {
346 if (AutomaticImport)
Douglas Gregor09833922011-12-06 17:31:28 +0000347 *SuggestedModule = HS.findModuleForHeader(FE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 return FE;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000349 }
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
352 const char *Private = "Private";
Mike Stump1eb44332009-09-09 15:08:12 +0000353 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 Private+strlen(Private));
Manuel Klimek74124942011-04-26 21:50:03 +0000355 if (SearchPath != NULL)
356 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
357 Private+strlen(Private));
358
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000359 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
360 /*openFile=*/!AutomaticImport);
361 if (FE && AutomaticImport)
Douglas Gregor09833922011-12-06 17:31:28 +0000362 *SuggestedModule = HS.findModuleForHeader(FE);
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000363 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
Chris Lattnerdf772332007-12-17 07:52:39 +0000366
Chris Lattnerafded5b2007-12-17 08:13:48 +0000367//===----------------------------------------------------------------------===//
368// Header File Location.
369//===----------------------------------------------------------------------===//
370
371
Reid Spencer5f016e22007-07-11 17:01:13 +0000372/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
373/// return null on failure. isAngled indicates whether the file reference is
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000374/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
375/// non-null, indicates where the #including file is, in case a relative search
376/// is needed.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000377const FileEntry *HeaderSearch::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000378 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000379 bool isAngled,
380 const DirectoryLookup *FromDir,
381 const DirectoryLookup *&CurDir,
382 const FileEntry *CurFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000383 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000384 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000385 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000386 bool SkipCache)
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000387{
388 if (SuggestedModule)
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000389 *SuggestedModule = 0;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000392 if (llvm::sys::path::is_absolute(Filename)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 CurDir = 0;
394
395 // If this was an #include_next "/absolute/file", fail.
396 if (FromDir) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Manuel Klimek74124942011-04-26 21:50:03 +0000398 if (SearchPath != NULL)
399 SearchPath->clear();
400 if (RelativePath != NULL) {
401 RelativePath->clear();
402 RelativePath->append(Filename.begin(), Filename.end());
403 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000405 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000408 // Unless disabled, check to see if the file is in the #includer's
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000409 // directory. This has to be based on CurFileEnt, not CurDir, because
410 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
Chris Lattnerdf772332007-12-17 07:52:39 +0000411 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
412 // This search is not done for <> headers.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000413 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
414 llvm::SmallString<1024> TmpDir;
415 // Concatenate the requested file onto the directory.
416 // FIXME: Portability. Filename concatenation should be in sys::Path.
417 TmpDir += CurFileEnt->getDir()->getName();
418 TmpDir.push_back('/');
419 TmpDir.append(Filename.begin(), Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000420 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 // Leave CurDir unset.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000422 // This file is a system header or C++ unfriendly if the old file is.
423 //
424 // Note that the temporary 'DirInfo' is required here, as either call to
425 // getFileInfo could resize the vector and we don't want to rely on order
426 // of evaluation.
427 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000428 getFileInfo(FE).DirInfo = DirInfo;
Manuel Klimek74124942011-04-26 21:50:03 +0000429 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000431 SearchPath->clear();
432 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
433 }
434 if (RelativePath != NULL) {
435 RelativePath->clear();
436 RelativePath->append(Filename.begin(), Filename.end());
437 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 return FE;
439 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 CurDir = 0;
443
444 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000445 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 // If this is a #include_next request, start searching after the directory the
448 // file was found in.
449 if (FromDir)
450 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner9960ae82007-07-22 07:28:00 +0000452 // Cache all of the lookups performed by this method. Many headers are
453 // multiply included, and the "pragma once" optimization prevents them from
454 // being relex/pp'd, but they would still have to search through a
455 // (potentially huge) series of SearchDirs to find it.
456 std::pair<unsigned, unsigned> &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000457 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000458
459 // If the entry has been previously looked up, the first value will be
460 // non-zero. If the value is equal to i (the start point of our search), then
461 // this is a matching hit.
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000462 if (!SkipCache && CacheLookup.first == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000463 // Skip querying potentially lots of directories for this lookup.
464 i = CacheLookup.second;
465 } else {
466 // Otherwise, this is the first query, or the previous query didn't match
467 // our search start. We will fill in our found location below, so prime the
468 // start point value.
469 CacheLookup.first = i+1;
470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 // Check each directory in sequence to see if it contains this file.
473 for (; i != SearchDirs.size(); ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000474 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000475 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000476 SuggestedModule);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000477 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Chris Lattnerafded5b2007-12-17 08:13:48 +0000479 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattnerafded5b2007-12-17 08:13:48 +0000481 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000482 HeaderFileInfo &HFI = getFileInfo(FE);
483 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000485 // If this file is found in a header map and uses the framework style of
486 // includes, then this header is part of a framework we're building.
487 if (CurDir->isIndexHeaderMap()) {
488 size_t SlashPos = Filename.find('/');
489 if (SlashPos != StringRef::npos) {
490 HFI.IndexHeaderMapHeader = 1;
491 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
492 SlashPos));
493 }
494 }
495
Chris Lattnerafded5b2007-12-17 08:13:48 +0000496 // Remember this location for the next lookup we do.
497 CacheLookup.second = i;
498 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000501 // If we are including a file with a quoted include "foo.h" from inside
502 // a header in a framework that is currently being built, and we couldn't
503 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
504 // "Foo" is the name of the framework in which the including header was found.
505 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
506 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
507 if (IncludingHFI.IndexHeaderMapHeader) {
508 llvm::SmallString<128> ScratchFilename;
509 ScratchFilename += IncludingHFI.Framework;
510 ScratchFilename += '/';
511 ScratchFilename += Filename;
512
513 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
514 FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000515 SearchPath, RelativePath,
516 SuggestedModule);
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000517 std::pair<unsigned, unsigned> &CacheLookup
518 = LookupFileCache.GetOrCreateValue(Filename).getValue();
519 CacheLookup.second
520 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
521 return Result;
522 }
523 }
524
Chris Lattner9960ae82007-07-22 07:28:00 +0000525 // Otherwise, didn't find it. Remember we didn't find this.
526 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 return 0;
528}
529
530/// LookupSubframeworkHeader - Look up a subframework for the specified
531/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
532/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
533/// is a subframework within Carbon.framework. If so, return the FileEntry
534/// for the designated file, otherwise return null.
535const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000536LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000537 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000538 SmallVectorImpl<char> *SearchPath,
539 SmallVectorImpl<char> *RelativePath) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000540 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000543 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000544 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000545 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 // Look up the base framework name of the ContextFileEnt.
548 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000551 const unsigned DotFrameworkLen = 10;
552 const char *FrameworkPos = strstr(ContextName, ".framework");
553 if (FrameworkPos == 0 ||
554 (FrameworkPos[DotFrameworkLen] != '/' &&
555 FrameworkPos[DotFrameworkLen] != '\\'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000557
558 llvm::SmallString<1024> FrameworkName(ContextName,
Douglas Gregorefda0e82011-12-09 16:48:01 +0000559 FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000560
561 // Append Frameworks/HIToolbox.framework/
562 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000563 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 FrameworkName += ".framework/";
565
566 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000567 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 // Some other location?
570 if (CacheLookup.getValue() &&
571 CacheLookup.getKeyLength() == FrameworkName.size() &&
572 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
573 CacheLookup.getKeyLength()) != 0)
574 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 // Cache subframework.
577 if (CacheLookup.getValue() == 0) {
578 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000581 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 // Otherwise, if it does, remember that this is the right direntry for this
585 // framework.
586 CacheLookup.setValue(Dir);
587 }
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 const FileEntry *FE = 0;
590
Manuel Klimek74124942011-04-26 21:50:03 +0000591 if (RelativePath != NULL) {
592 RelativePath->clear();
593 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
594 }
595
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
597 llvm::SmallString<1024> HeadersFilename(FrameworkName);
598 HeadersFilename += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000599 if (SearchPath != NULL) {
600 SearchPath->clear();
601 // Without trailing '/'.
602 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
603 }
604
Chris Lattnera1394812010-01-10 01:35:12 +0000605 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000606 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
609 HeadersFilename = FrameworkName;
610 HeadersFilename += "PrivateHeaders/";
Manuel Klimek74124942011-04-26 21:50:03 +0000611 if (SearchPath != NULL) {
612 SearchPath->clear();
613 // Without trailing '/'.
614 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
615 }
616
Chris Lattnera1394812010-01-10 01:35:12 +0000617 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000618 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 return 0;
620 }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000623 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000624 // Note that the temporary 'DirInfo' is required here, as either call to
625 // getFileInfo could resize the vector and we don't want to rely on order
626 // of evaluation.
627 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
628 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 return FE;
630}
631
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000632/// \brief Helper static function to normalize a path for injection into
633/// a synthetic header.
634/*static*/ std::string
635HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
636 // Implicit include paths should be resolved relative to the current
637 // working directory first, and then use the regular header search
638 // mechanism. The proper way to handle this is to have the
639 // predefines buffer located at the current working directory, but
640 // it has no file entry. For now, workaround this by using an
641 // absolute path if we find the file here, and otherwise letting
642 // header search handle it.
643 llvm::SmallString<128> Path(File);
644 llvm::sys::fs::make_absolute(Path);
645 bool exists;
646 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
647 Path = File;
648 else if (exists)
649 FileMgr.getFile(File);
650
651 return Lexer::Stringify(Path.str());
652}
653
Reid Spencer5f016e22007-07-11 17:01:13 +0000654//===----------------------------------------------------------------------===//
655// File Info Management.
656//===----------------------------------------------------------------------===//
657
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000658/// \brief Merge the header file info provided by \p OtherHFI into the current
659/// header file info (\p HFI)
660static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
661 const HeaderFileInfo &OtherHFI) {
662 HFI.isImport |= OtherHFI.isImport;
663 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
664 HFI.NumIncludes += OtherHFI.NumIncludes;
665
666 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
667 HFI.ControllingMacro = OtherHFI.ControllingMacro;
668 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
669 }
670
671 if (OtherHFI.External) {
672 HFI.DirInfo = OtherHFI.DirInfo;
673 HFI.External = OtherHFI.External;
674 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
675 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000676
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000677 if (HFI.Framework.empty())
678 HFI.Framework = OtherHFI.Framework;
679
680 HFI.Resolved = true;
681}
682
Steve Naroff83d63c72009-04-24 20:03:17 +0000683/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000684/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000685HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 if (FE->getUID() >= FileInfo.size())
687 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000688
689 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000690 if (ExternalSource && !HFI.Resolved)
691 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000692 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +0000693}
Reid Spencer5f016e22007-07-11 17:01:13 +0000694
Douglas Gregordd3e5542011-05-04 00:14:37 +0000695bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
696 // Check if we've ever seen this file as a header.
697 if (File->getUID() >= FileInfo.size())
698 return false;
699
700 // Resolve header file info from the external source, if needed.
701 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000702 if (ExternalSource && !HFI.Resolved)
703 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +0000704
705 return HFI.isPragmaOnce || HFI.ControllingMacro || HFI.ControllingMacroID;
706}
707
Steve Naroff83d63c72009-04-24 20:03:17 +0000708void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
709 if (UID >= FileInfo.size())
710 FileInfo.resize(UID+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000711 HFI.Resolved = true;
Steve Naroff83d63c72009-04-24 20:03:17 +0000712 FileInfo[UID] = HFI;
713}
714
Reid Spencer5f016e22007-07-11 17:01:13 +0000715/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
716/// #include, #include_next, or #import directive. Return false if #including
717/// the file will have no effect or true if we should include it.
718bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
719 ++NumIncluded; // Count # of attempted #includes.
720
721 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +0000722 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 // If this is a #import directive, check that we have not already imported
725 // this header.
726 if (isImport) {
727 // If this has already been imported, don't import it again.
728 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 // Has this already been #import'ed or #include'd?
731 if (FileInfo.NumIncludes) return false;
732 } else {
733 // Otherwise, if this is a #include of a file that was previously #import'd
734 // or if this is the second #include of a #pragma once file, ignore it.
735 if (FileInfo.isImport)
736 return false;
737 }
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
740 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +0000741 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000742 = FileInfo.getControllingMacro(ExternalLookup))
743 if (ControllingMacro->hasMacroDefinition()) {
744 ++NumMultiIncludeFileOptzn;
745 return false;
746 }
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 // Increment the number of times this file has been included.
749 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 return true;
752}
753
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000754size_t HeaderSearch::getTotalMemory() const {
755 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +0000756 + llvm::capacity_in_bytes(FileInfo)
757 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000758 + LookupFileCache.getAllocator().getTotalMemory()
759 + FrameworkMap.getAllocator().getTotalMemory();
760}
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000761
762StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
763 return FrameworkNames.GetOrCreateValue(Framework).getKey();
764}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000765
766bool HeaderSearch::hasModuleMap(StringRef FileName,
767 const DirectoryEntry *Root) {
768 llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
769
770 StringRef DirName = FileName;
771 do {
772 // Get the parent directory name.
773 DirName = llvm::sys::path::parent_path(DirName);
774 if (DirName.empty())
775 return false;
776
777 // Determine whether this directory exists.
778 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
779 if (!Dir)
780 return false;
781
Douglas Gregorcf70d782011-11-12 00:05:07 +0000782 // Try to load the module map file in this directory.
Douglas Gregor26697972011-11-12 00:22:19 +0000783 switch (loadModuleMapFile(Dir)) {
784 case LMM_NewlyLoaded:
785 case LMM_AlreadyLoaded:
Douglas Gregorcf70d782011-11-12 00:05:07 +0000786 // Success. All of the directories we stepped through inherit this module
787 // map file.
Douglas Gregora30cfe52011-11-11 19:10:28 +0000788 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
789 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
790
791 return true;
Douglas Gregor26697972011-11-12 00:22:19 +0000792
793 case LMM_NoDirectory:
794 case LMM_InvalidModuleMap:
795 break;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000796 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000797
Douglas Gregorcf70d782011-11-12 00:05:07 +0000798 // If we hit the top of our search, we're done.
799 if (Dir == Root)
800 return false;
801
Douglas Gregora30cfe52011-11-11 19:10:28 +0000802 // Keep track of all of the directories we checked, so we can mark them as
803 // having module maps if we eventually do find a module map.
804 FixUpDirectories.push_back(Dir);
805 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000806}
807
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000808Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000809 if (Module *Mod = ModMap.findModuleForHeader(File))
810 return Mod;
Douglas Gregor65f3b5e2011-11-11 22:18:48 +0000811
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000812 return 0;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000813}
814
Douglas Gregordb1cde72011-11-16 00:09:06 +0000815bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
816 const DirectoryEntry *Dir = File->getDir();
817
818 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
819 = DirectoryHasModuleMap.find(Dir);
820 if (KnownDir != DirectoryHasModuleMap.end())
821 return !KnownDir->second;
822
823 bool Result = ModMap.parseModuleMapFile(File);
Douglas Gregor4813442c2011-12-07 21:25:07 +0000824 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
825 // If the file we loaded was a module.map, look for the corresponding
826 // module_private.map.
827 llvm::SmallString<128> PrivateFilename(Dir->getName());
828 llvm::sys::path::append(PrivateFilename, "module_private.map");
829 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
830 Result = ModMap.parseModuleMapFile(PrivateFile);
831 }
832
833 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000834 return Result;
835}
836
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000837Module *HeaderSearch::getModule(StringRef Name, bool AllowSearch) {
838 if (Module *Module = ModMap.findModule(Name))
Douglas Gregordb1cde72011-11-16 00:09:06 +0000839 return Module;
840
841 if (!AllowSearch)
842 return 0;
843
844 for (unsigned I = 0, N = SearchDirs.size(); I != N; ++I) {
845 if (!SearchDirs[I].isNormalDir())
846 continue;
847
848 switch (loadModuleMapFile(SearchDirs[I].getDir())) {
849 case LMM_AlreadyLoaded:
850 case LMM_InvalidModuleMap:
851 case LMM_NoDirectory:
852 break;
853
854 case LMM_NewlyLoaded:
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000855 if (Module *Module = ModMap.findModule(Name))
Douglas Gregordb1cde72011-11-16 00:09:06 +0000856 return Module;
857 break;
858 }
859 }
860
861 return 0;
862}
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000863
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000864Module *HeaderSearch::getFrameworkModule(StringRef Name,
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000865 const DirectoryEntry *Dir,
866 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000867 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000868 return Module;
869
870 // Try to load a module map file.
871 switch (loadModuleMapFile(Dir)) {
872 case LMM_InvalidModuleMap:
873 break;
874
875 case LMM_AlreadyLoaded:
876 case LMM_NoDirectory:
877 return 0;
878
879 case LMM_NewlyLoaded:
880 return ModMap.findModule(Name);
881 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000882
883 // The top-level framework directory, from which we'll infer a framework
884 // module.
885 const DirectoryEntry *TopFrameworkDir = Dir;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000886
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000887 // The path from the module we're actually looking for back to the top-level
888 // framework name.
889 llvm::SmallVector<StringRef, 2> SubmodulePath;
890 SubmodulePath.push_back(Name);
891
892 // Walk the directory structure to find any enclosing frameworks.
893 StringRef DirName = Dir->getName();
894 do {
895 // Get the parent directory name.
896 DirName = llvm::sys::path::parent_path(DirName);
897 if (DirName.empty())
898 break;
899
900 // Determine whether this directory exists.
901 Dir = FileMgr.getDirectory(DirName);
902 if (!Dir)
903 break;
904
905 // If this is a framework directory, then we're a subframework of this
906 // framework.
907 if (llvm::sys::path::extension(DirName) == ".framework") {
908 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
909 TopFrameworkDir = Dir;
910 }
911 } while (true);
912
913 // Try to infer a module map from the top-level framework directory.
914 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000915 TopFrameworkDir,
916 IsSystem,
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000917 /*Parent=*/0);
918
919 // Follow the submodule path to find the requested (sub)framework module
920 // within the top-level framework module.
921 SubmodulePath.pop_back();
922 while (!SubmodulePath.empty() && Result) {
923 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
924 SubmodulePath.pop_back();
925 }
926 return Result;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000927}
928
Douglas Gregordb1cde72011-11-16 00:09:06 +0000929
Douglas Gregor26697972011-11-12 00:22:19 +0000930HeaderSearch::LoadModuleMapResult
931HeaderSearch::loadModuleMapFile(StringRef DirName) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000932 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
933 return loadModuleMapFile(Dir);
934
Douglas Gregor26697972011-11-12 00:22:19 +0000935 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000936}
937
Douglas Gregor26697972011-11-12 00:22:19 +0000938HeaderSearch::LoadModuleMapResult
939HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000940 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
941 = DirectoryHasModuleMap.find(Dir);
942 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +0000943 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000944
945 llvm::SmallString<128> ModuleMapFileName;
946 ModuleMapFileName += Dir->getName();
Douglas Gregor587986e2011-12-07 02:23:45 +0000947 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregorcf70d782011-11-12 00:05:07 +0000948 llvm::sys::path::append(ModuleMapFileName, "module.map");
949 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
950 // We have found a module map file. Try to parse it.
Douglas Gregor587986e2011-12-07 02:23:45 +0000951 if (ModMap.parseModuleMapFile(ModuleMapFile)) {
952 // No suitable module map.
953 DirectoryHasModuleMap[Dir] = false;
954 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000955 }
Douglas Gregor587986e2011-12-07 02:23:45 +0000956
957 // This directory has a module map.
958 DirectoryHasModuleMap[Dir] = true;
959
960 // Check whether there is a private module map that we need to load as well.
961 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
962 ModuleMapFileName.end());
963 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
964 if (const FileEntry *PrivateModuleMapFile
965 = FileMgr.getFile(ModuleMapFileName)) {
966 if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
967 // No suitable module map.
968 DirectoryHasModuleMap[Dir] = false;
969 return LMM_InvalidModuleMap;
970 }
971 }
972
973 return LMM_NewlyLoaded;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000974 }
975
976 // No suitable module map.
977 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor26697972011-11-12 00:22:19 +0000978 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000979}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000980