blob: 3b6c5ccde4ac6312ad16ecdd0115072c286895d5 [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"
Douglas Gregora30cfe52011-11-11 19:10:28 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Lex/HeaderMap.h"
19#include "clang/Lex/HeaderSearchOptions.h"
20#include "clang/Lex/Lexer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/ADT/SmallString.h"
Ted Kremenekeabea452011-07-27 18:41:18 +000022#include "llvm/Support/Capacity.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/Path.h"
Chris Lattner3daed522009-03-02 22:20:04 +000025#include <cstdio>
Douglas Gregor3cc62772013-01-22 23:49:45 +000026#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoadeb7822013-01-26 16:29:36 +000027#include <limits.h>
Douglas Gregor3cc62772013-01-22 23:49:45 +000028#endif
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Douglas Gregor8c5a7602009-04-25 23:30:02 +000031const IdentifierInfo *
32HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
33 if (ControllingMacro)
34 return ControllingMacro;
35
36 if (!ControllingMacroID || !External)
37 return 0;
38
39 ControllingMacro = External->GetIdentifier(ControllingMacroID);
40 return ControllingMacro;
41}
42
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000043ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
44
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000045HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Douglas Gregorc042edd2012-10-24 16:19:39 +000046 FileManager &FM, DiagnosticsEngine &Diags,
Douglas Gregordc58aa72012-01-30 06:01:29 +000047 const LangOptions &LangOpts,
48 const TargetInfo *Target)
Douglas Gregorc042edd2012-10-24 16:19:39 +000049 : HSOpts(HSOpts), FileMgr(FM), FrameworkMap(64),
Douglas Gregordc58aa72012-01-30 06:01:29 +000050 ModMap(FileMgr, *Diags.getClient(), LangOpts, Target)
Douglas Gregor8e238062011-11-11 00:35:06 +000051{
Nico Weber74a5fd82011-05-24 04:31:14 +000052 AngledDirIdx = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000053 SystemDirIdx = 0;
54 NoCurDirSearch = false;
Mike Stump1eb44332009-09-09 15:08:12 +000055
Douglas Gregor8c5a7602009-04-25 23:30:02 +000056 ExternalLookup = 0;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000057 ExternalSource = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000058 NumIncluded = 0;
59 NumMultiIncludeFileOptzn = 0;
60 NumFrameworkLookups = NumSubFrameworkLookups = 0;
61}
62
Chris Lattner822da612007-12-17 06:36:45 +000063HeaderSearch::~HeaderSearch() {
64 // Delete headermaps.
65 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
66 delete HeaderMaps[i].second;
67}
Mike Stump1eb44332009-09-09 15:08:12 +000068
Reid Spencer5f016e22007-07-11 17:01:13 +000069void HeaderSearch::PrintStats() {
70 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
71 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
72 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
73 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
74 NumOnceOnlyFiles += FileInfo[i].isImport;
75 if (MaxNumIncludes < FileInfo[i].NumIncludes)
76 MaxNumIncludes = FileInfo[i].NumIncludes;
77 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
78 }
79 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
80 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
81 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump1eb44332009-09-09 15:08:12 +000082
Reid Spencer5f016e22007-07-11 17:01:13 +000083 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
84 fprintf(stderr, " %d #includes skipped due to"
85 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump1eb44332009-09-09 15:08:12 +000086
Reid Spencer5f016e22007-07-11 17:01:13 +000087 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
88 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
89}
90
Chris Lattner822da612007-12-17 06:36:45 +000091/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000092/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000093const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000094 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000095 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000096 if (!HeaderMaps.empty()) {
97 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000098 // Pointer equality comparison of FileEntries works because they are
99 // already uniqued by inode.
Mike Stump1eb44332009-09-09 15:08:12 +0000100 if (HeaderMaps[i].first == FE)
Chris Lattner822da612007-12-17 06:36:45 +0000101 return HeaderMaps[i].second;
102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Chris Lattner39b49bc2010-11-23 08:35:12 +0000104 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattner822da612007-12-17 06:36:45 +0000105 HeaderMaps.push_back(std::make_pair(FE, HM));
106 return HM;
107 }
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattner822da612007-12-17 06:36:45 +0000109 return 0;
110}
111
Douglas Gregore434ec72012-01-29 17:08:11 +0000112std::string HeaderSearch::getModuleFileName(Module *Module) {
Douglas Gregor9a6da692011-09-12 20:41:59 +0000113 // If we don't have a module cache path, we can't do anything.
Douglas Gregore434ec72012-01-29 17:08:11 +0000114 if (ModuleCachePath.empty())
115 return std::string();
116
117
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000118 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000119 llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
120 return Result.str().str();
121}
122
123std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
124 // If we don't have a module cache path, we can't do anything.
125 if (ModuleCachePath.empty())
126 return std::string();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000127
Douglas Gregore434ec72012-01-29 17:08:11 +0000128
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000129 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000130 llvm::sys::path::append(Result, ModuleName + ".pcm");
131 return Result.str().str();
132}
133
134Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000135 // Look in the module map to determine if there is a module by this name.
Douglas Gregore434ec72012-01-29 17:08:11 +0000136 Module *Module = ModMap.findModule(ModuleName);
137 if (Module || !AllowSearch)
138 return Module;
139
Douglas Gregor7005b902013-01-10 01:43:00 +0000140 // Look through the various header search paths to load any available module
Douglas Gregore434ec72012-01-29 17:08:11 +0000141 // maps, searching for a module map that describes this module.
142 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
143 if (SearchDirs[Idx].isFramework()) {
144 // Search for or infer a module map for a framework.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000145 SmallString<128> FrameworkDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000146 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
147 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
148 if (const DirectoryEntry *FrameworkDir
149 = FileMgr.getDirectory(FrameworkDirName)) {
150 bool IsSystem
151 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
152 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregorcf70d782011-11-12 00:05:07 +0000153 if (Module)
154 break;
155 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000156 }
157
158 // FIXME: Figure out how header maps and module maps will work together.
159
160 // Only deal with normal search directories.
161 if (!SearchDirs[Idx].isNormalDir())
162 continue;
163
164 // Search for a module map file in this directory.
165 if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) {
166 // We just loaded a module map file; check whether the module is
167 // available now.
168 Module = ModMap.findModule(ModuleName);
169 if (Module)
170 break;
171 }
172
173 // Search for a module map in a subdirectory with the same name as the
174 // module.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000175 SmallString<128> NestedModuleMapDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000176 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
177 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
178 if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) {
179 // If we just loaded a module map file, look for the module again.
180 Module = ModMap.findModule(ModuleName);
181 if (Module)
182 break;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000183 }
184 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000185
186 return Module;
Douglas Gregor9a6da692011-09-12 20:41:59 +0000187}
188
Chris Lattnerdf772332007-12-17 07:52:39 +0000189//===----------------------------------------------------------------------===//
190// File lookup within a DirectoryLookup scope
191//===----------------------------------------------------------------------===//
192
Chris Lattner3af66a92007-12-17 17:57:27 +0000193/// getName - Return the directory or filename corresponding to this lookup
194/// object.
195const char *DirectoryLookup::getName() const {
196 if (isNormalDir())
197 return getDir()->getName();
198 if (isFramework())
199 return getFrameworkDir()->getName();
200 assert(isHeaderMap() && "Unknown DirectoryLookup");
201 return getHeaderMap()->getFileName();
202}
203
204
Chris Lattnerdf772332007-12-17 07:52:39 +0000205/// LookupFile - Lookup the specified file in this search path, returning it
206/// if it exists or returning null if not.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000207const FileEntry *DirectoryLookup::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000208 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000209 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000210 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000211 SmallVectorImpl<char> *RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000212 Module **SuggestedModule,
213 bool &InUserSpecifiedSystemFramework) const {
214 InUserSpecifiedSystemFramework = false;
215
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000216 SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000217 if (isNormalDir()) {
218 // Concatenate the requested file onto the directory.
Eli Friedmana6e023c2011-07-08 20:17:28 +0000219 TmpDir = getDir()->getName();
220 llvm::sys::path::append(TmpDir, Filename);
Manuel Klimek74124942011-04-26 21:50:03 +0000221 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000222 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000223 SearchPath->clear();
224 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
225 }
226 if (RelativePath != NULL) {
227 RelativePath->clear();
228 RelativePath->append(Filename.begin(), Filename.end());
229 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000230
231 // If we have a module map that might map this header, load it and
232 // check whether we'll have a suggestion for a module.
233 if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
234 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
235 /*openFile=*/false);
236 if (!File)
237 return File;
238
239 // If there is a module that corresponds to this header,
240 // suggest it.
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000241 *SuggestedModule = HS.findModuleForHeader(File);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000242 return File;
243 }
244
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000245 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattnerafded5b2007-12-17 08:13:48 +0000248 if (isFramework())
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000249 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000250 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000252 assert(isHeaderMap() && "Unknown directory lookup");
Manuel Klimek74124942011-04-26 21:50:03 +0000253 const FileEntry * const Result = getHeaderMap()->LookupFile(
254 Filename, HS.getFileMgr());
255 if (Result) {
256 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000257 StringRef SearchPathRef(getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000258 SearchPath->clear();
259 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
260 }
261 if (RelativePath != NULL) {
262 RelativePath->clear();
263 RelativePath->append(Filename.begin(), Filename.end());
264 }
265 }
266 return Result;
Chris Lattnerdf772332007-12-17 07:52:39 +0000267}
268
Douglas Gregor713b7c02013-01-26 00:55:12 +0000269/// FIXME: HACK HACK HACK!
270static llvm::DenseMap<const DirectoryEntry *, const DirectoryEntry *>
271 TopFrameworkDirs;
272
Douglas Gregor7005b902013-01-10 01:43:00 +0000273/// \brief Given a framework directory, find the top-most framework directory.
274///
275/// \param FileMgr The file manager to use for directory lookups.
276/// \param DirName The name of the framework directory.
277/// \param SubmodulePath Will be populated with the submodule path from the
278/// returned top-level module to the originally named framework.
279static const DirectoryEntry *
280getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
281 SmallVectorImpl<std::string> &SubmodulePath) {
282 assert(llvm::sys::path::extension(DirName) == ".framework" &&
283 "Not a framework directory");
284
Douglas Gregor7005b902013-01-10 01:43:00 +0000285 // Note: as an egregious but useful hack we use the real path here, because
286 // frameworks moving between top-level frameworks to embedded frameworks tend
287 // to be symlinked, and we base the logical structure of modules on the
288 // physical layout. In particular, we need to deal with crazy includes like
289 //
290 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
291 //
292 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
293 // which one should access with, e.g.,
294 //
295 // #include <Bar/Wibble.h>
296 //
297 // Similar issues occur when a top-level framework has moved into an
298 // embedded framework.
Douglas Gregor7005b902013-01-10 01:43:00 +0000299 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregor713b7c02013-01-26 00:55:12 +0000300 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor7005b902013-01-10 01:43:00 +0000301 do {
302 // Get the parent directory name.
303 DirName = llvm::sys::path::parent_path(DirName);
304 if (DirName.empty())
305 break;
306
307 // Determine whether this directory exists.
308 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
309 if (!Dir)
310 break;
311
312 // If this is a framework directory, then we're a subframework of this
313 // framework.
314 if (llvm::sys::path::extension(DirName) == ".framework") {
315 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
316 TopFrameworkDir = Dir;
317 }
318 } while (true);
319
320 return TopFrameworkDir;
321}
Chris Lattnerdf772332007-12-17 07:52:39 +0000322
Chris Lattnerafded5b2007-12-17 08:13:48 +0000323/// DoFrameworkLookup - Do a lookup of the specified file in the current
324/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000325const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000326 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000327 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000328 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000329 SmallVectorImpl<char> *RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000330 Module **SuggestedModule,
331 bool &InUserSpecifiedSystemFramework) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000332{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000333 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000336 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000337 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattnerafded5b2007-12-17 08:13:48 +0000339 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000340 // HeaderSearch. Possible answers are yes/no and unknown.
341 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnera1394812010-01-10 01:35:12 +0000342 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Chris Lattnerafded5b2007-12-17 08:13:48 +0000344 // If it is known and in some other directory, fail.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000345 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattnerafded5b2007-12-17 08:13:48 +0000348 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000351 SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000352 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 if (FrameworkName.empty() || FrameworkName.back() != '/')
354 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000357 StringRef ModuleName(Filename.begin(), SlashPos);
358 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
361 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000363 // If the cache entry was unresolved, populate it now.
364 if (CacheEntry.Directory == 0) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000365 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // If the framework dir doesn't exist, we fail.
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000368 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
369 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // Otherwise, if it does, remember that this is the right direntry for this
372 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000373 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000374
375 // If this is a user search directory, check if the framework has been
376 // user-specified as a system framework.
377 if (getDirCharacteristic() == SrcMgr::C_User) {
378 SmallString<1024> SystemFrameworkMarker(FrameworkName);
379 SystemFrameworkMarker += ".system_framework";
380 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
381 CacheEntry.IsUserSpecifiedSystemFramework = true;
382 }
383 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 }
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000386 // Set the 'user-specified system framework' flag.
387 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
388
Manuel Klimek74124942011-04-26 21:50:03 +0000389 if (RelativePath != NULL) {
390 RelativePath->clear();
391 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
392 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000393
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
395 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000398
399 if (SearchPath != NULL) {
400 SearchPath->clear();
401 // Without trailing '/'.
402 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
403 }
404
Chris Lattnera1394812010-01-10 01:35:12 +0000405 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor7005b902013-01-10 01:43:00 +0000406 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
407 /*openFile=*/!SuggestedModule);
408 if (!FE) {
409 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
410 const char *Private = "Private";
411 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
412 Private+strlen(Private));
413 if (SearchPath != NULL)
414 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
415 Private+strlen(Private));
416
417 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Douglas Gregor7005b902013-01-10 01:43:00 +0000420 // If we found the header and are allowed to suggest a module, do so now.
421 if (FE && SuggestedModule) {
422 // Find the framework in which this header occurs.
423 StringRef FrameworkPath = FE->getName();
424 bool FoundFramework = false;
425 do {
426 // Get the parent directory name.
427 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
428 if (FrameworkPath.empty())
429 break;
Manuel Klimek74124942011-04-26 21:50:03 +0000430
Douglas Gregor7005b902013-01-10 01:43:00 +0000431 // Determine whether this directory exists.
432 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
433 if (!Dir)
434 break;
435
436 // If this is a framework directory, then we're a subframework of this
437 // framework.
438 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
439 FoundFramework = true;
440 break;
441 }
442 } while (true);
443
444 if (FoundFramework) {
445 // Find the top-level framework based on this framework.
446 SmallVector<std::string, 4> SubmodulePath;
447 const DirectoryEntry *TopFrameworkDir
448 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
449
450 // Determine the name of the top-level framework.
451 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
452
453 // Load this framework module. If that succeeds, find the suggested module
454 // for this header, if any.
455 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
456 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
457 *SuggestedModule = HS.findModuleForHeader(FE);
458 }
459 } else {
460 *SuggestedModule = HS.findModuleForHeader(FE);
461 }
462 }
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000463 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000464}
465
Douglas Gregordc58aa72012-01-30 06:01:29 +0000466void HeaderSearch::setTarget(const TargetInfo &Target) {
467 ModMap.setTarget(Target);
468}
469
Chris Lattnerdf772332007-12-17 07:52:39 +0000470
Chris Lattnerafded5b2007-12-17 08:13:48 +0000471//===----------------------------------------------------------------------===//
472// Header File Location.
473//===----------------------------------------------------------------------===//
474
475
James Dennett853519c2012-06-20 00:56:32 +0000476/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Reid Spencer5f016e22007-07-11 17:01:13 +0000477/// return null on failure. isAngled indicates whether the file reference is
James Dennett853519c2012-06-20 00:56:32 +0000478/// for system \#include's or not (i.e. using <> instead of ""). CurFileEnt, if
479/// non-null, indicates where the \#including file is, in case a relative search
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000480/// is needed.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000481const FileEntry *HeaderSearch::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000482 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000483 bool isAngled,
484 const DirectoryLookup *FromDir,
485 const DirectoryLookup *&CurDir,
486 const FileEntry *CurFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000487 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000488 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000489 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000490 bool SkipCache)
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000491{
492 if (SuggestedModule)
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000493 *SuggestedModule = 0;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000496 if (llvm::sys::path::is_absolute(Filename)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 CurDir = 0;
498
499 // If this was an #include_next "/absolute/file", fail.
500 if (FromDir) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Manuel Klimek74124942011-04-26 21:50:03 +0000502 if (SearchPath != NULL)
503 SearchPath->clear();
504 if (RelativePath != NULL) {
505 RelativePath->clear();
506 RelativePath->append(Filename.begin(), Filename.end());
507 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000509 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000512 // Unless disabled, check to see if the file is in the #includer's
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000513 // directory. This has to be based on CurFileEnt, not CurDir, because
514 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
Chris Lattnerdf772332007-12-17 07:52:39 +0000515 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
516 // This search is not done for <> headers.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000517 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000518 SmallString<1024> TmpDir;
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000519 // Concatenate the requested file onto the directory.
520 // FIXME: Portability. Filename concatenation should be in sys::Path.
521 TmpDir += CurFileEnt->getDir()->getName();
522 TmpDir.push_back('/');
523 TmpDir.append(Filename.begin(), Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000524 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 // Leave CurDir unset.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000526 // This file is a system header or C++ unfriendly if the old file is.
527 //
Douglas Gregor21efbb62012-08-13 15:47:39 +0000528 // Note that we only use one of FromHFI/ToHFI at once, due to potential
529 // reallocation of the underlying vector potentially making the first
530 // reference binding dangling.
531 HeaderFileInfo &FromHFI = getFileInfo(CurFileEnt);
532 unsigned DirInfo = FromHFI.DirInfo;
533 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
534 StringRef Framework = FromHFI.Framework;
535
536 HeaderFileInfo &ToHFI = getFileInfo(FE);
537 ToHFI.DirInfo = DirInfo;
538 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
539 ToHFI.Framework = Framework;
540
Manuel Klimek74124942011-04-26 21:50:03 +0000541 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000542 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000543 SearchPath->clear();
544 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
545 }
546 if (RelativePath != NULL) {
547 RelativePath->clear();
548 RelativePath->append(Filename.begin(), Filename.end());
549 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 return FE;
551 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 CurDir = 0;
555
556 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000557 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 // If this is a #include_next request, start searching after the directory the
560 // file was found in.
561 if (FromDir)
562 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattner9960ae82007-07-22 07:28:00 +0000564 // Cache all of the lookups performed by this method. Many headers are
565 // multiply included, and the "pragma once" optimization prevents them from
566 // being relex/pp'd, but they would still have to search through a
567 // (potentially huge) series of SearchDirs to find it.
568 std::pair<unsigned, unsigned> &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000569 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000570
571 // If the entry has been previously looked up, the first value will be
572 // non-zero. If the value is equal to i (the start point of our search), then
573 // this is a matching hit.
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000574 if (!SkipCache && CacheLookup.first == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000575 // Skip querying potentially lots of directories for this lookup.
576 i = CacheLookup.second;
577 } else {
578 // Otherwise, this is the first query, or the previous query didn't match
579 // our search start. We will fill in our found location below, so prime the
580 // start point value.
581 CacheLookup.first = i+1;
582 }
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 // Check each directory in sequence to see if it contains this file.
585 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000586 bool InUserSpecifiedSystemFramework = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000587 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000588 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000589 SuggestedModule, InUserSpecifiedSystemFramework);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000590 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattnerafded5b2007-12-17 08:13:48 +0000592 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattnerafded5b2007-12-17 08:13:48 +0000594 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000595 HeaderFileInfo &HFI = getFileInfo(FE);
596 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000598 // If the directory characteristic is User but this framework was
599 // user-specified to be treated as a system framework, promote the
600 // characteristic.
601 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
602 HFI.DirInfo = SrcMgr::C_System;
603
Richard Smithf122a132012-06-13 20:27:03 +0000604 // If the filename matches a known system header prefix, override
605 // whether the file is a system header.
Richard Trieu4ef2f6a2012-06-13 20:52:36 +0000606 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
607 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
608 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smithf122a132012-06-13 20:27:03 +0000609 : SrcMgr::C_User;
610 break;
611 }
612 }
613
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000614 // If this file is found in a header map and uses the framework style of
615 // includes, then this header is part of a framework we're building.
616 if (CurDir->isIndexHeaderMap()) {
617 size_t SlashPos = Filename.find('/');
618 if (SlashPos != StringRef::npos) {
619 HFI.IndexHeaderMapHeader = 1;
620 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
621 SlashPos));
622 }
623 }
624
Chris Lattnerafded5b2007-12-17 08:13:48 +0000625 // Remember this location for the next lookup we do.
626 CacheLookup.second = i;
627 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 }
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000630 // If we are including a file with a quoted include "foo.h" from inside
631 // a header in a framework that is currently being built, and we couldn't
632 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
633 // "Foo" is the name of the framework in which the including header was found.
634 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
635 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
636 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000637 SmallString<128> ScratchFilename;
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000638 ScratchFilename += IncludingHFI.Framework;
639 ScratchFilename += '/';
640 ScratchFilename += Filename;
641
642 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
643 FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000644 SearchPath, RelativePath,
645 SuggestedModule);
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000646 std::pair<unsigned, unsigned> &CacheLookup
647 = LookupFileCache.GetOrCreateValue(Filename).getValue();
648 CacheLookup.second
649 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
650 return Result;
651 }
652 }
653
Chris Lattner9960ae82007-07-22 07:28:00 +0000654 // Otherwise, didn't find it. Remember we didn't find this.
655 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 return 0;
657}
658
659/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennett853519c2012-06-20 00:56:32 +0000660/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Reid Spencer5f016e22007-07-11 17:01:13 +0000661/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
662/// is a subframework within Carbon.framework. If so, return the FileEntry
663/// for the designated file, otherwise return null.
664const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000665LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000666 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000667 SmallVectorImpl<char> *SearchPath,
Douglas Gregor1b58c742013-02-08 00:10:48 +0000668 SmallVectorImpl<char> *RelativePath,
669 Module **SuggestedModule) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000670 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000673 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000674 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000675 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 // Look up the base framework name of the ContextFileEnt.
678 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Reid Spencer5f016e22007-07-11 17:01:13 +0000680 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000681 const unsigned DotFrameworkLen = 10;
682 const char *FrameworkPos = strstr(ContextName, ".framework");
683 if (FrameworkPos == 0 ||
684 (FrameworkPos[DotFrameworkLen] != '/' &&
685 FrameworkPos[DotFrameworkLen] != '\\'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000688 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000689
690 // Append Frameworks/HIToolbox.framework/
691 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000692 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000693 FrameworkName += ".framework/";
694
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000695 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000696 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 // Some other location?
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000699 if (CacheLookup.getValue().Directory &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 CacheLookup.getKeyLength() == FrameworkName.size() &&
701 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
702 CacheLookup.getKeyLength()) != 0)
703 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 // Cache subframework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000706 if (CacheLookup.getValue().Directory == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000710 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 // Otherwise, if it does, remember that this is the right direntry for this
714 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000715 CacheLookup.getValue().Directory = Dir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 const FileEntry *FE = 0;
719
Manuel Klimek74124942011-04-26 21:50:03 +0000720 if (RelativePath != NULL) {
721 RelativePath->clear();
722 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
723 }
724
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000726 SmallString<1024> HeadersFilename(FrameworkName);
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 HeadersFilename += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000728 if (SearchPath != NULL) {
729 SearchPath->clear();
730 // Without trailing '/'.
731 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
732 }
733
Chris Lattnera1394812010-01-10 01:35:12 +0000734 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000735 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
738 HeadersFilename = FrameworkName;
739 HeadersFilename += "PrivateHeaders/";
Manuel Klimek74124942011-04-26 21:50:03 +0000740 if (SearchPath != NULL) {
741 SearchPath->clear();
742 // Without trailing '/'.
743 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
744 }
745
Chris Lattnera1394812010-01-10 01:35:12 +0000746 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000747 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 return 0;
749 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000752 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000753 // Note that the temporary 'DirInfo' is required here, as either call to
754 // getFileInfo could resize the vector and we don't want to rely on order
755 // of evaluation.
756 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
757 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregor1b58c742013-02-08 00:10:48 +0000758
759 // If we're supposed to suggest a module, look for one now.
760 if (SuggestedModule) {
761 // Find the top-level framework based on this framework.
762 FrameworkName.pop_back(); // remove the trailing '/'
763 SmallVector<std::string, 4> SubmodulePath;
764 const DirectoryEntry *TopFrameworkDir
765 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
766
767 // Determine the name of the top-level framework.
768 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
769
770 // Load this framework module. If that succeeds, find the suggested module
771 // for this header, if any.
772 bool IsSystem = false;
773 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
774 *SuggestedModule = findModuleForHeader(FE);
775 }
776 }
777
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 return FE;
779}
780
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000781/// \brief Helper static function to normalize a path for injection into
782/// a synthetic header.
783/*static*/ std::string
784HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
785 // Implicit include paths should be resolved relative to the current
786 // working directory first, and then use the regular header search
787 // mechanism. The proper way to handle this is to have the
788 // predefines buffer located at the current working directory, but
789 // it has no file entry. For now, workaround this by using an
790 // absolute path if we find the file here, and otherwise letting
791 // header search handle it.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000792 SmallString<128> Path(File);
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000793 llvm::sys::fs::make_absolute(Path);
794 bool exists;
795 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
796 Path = File;
797 else if (exists)
798 FileMgr.getFile(File);
799
800 return Lexer::Stringify(Path.str());
801}
802
Reid Spencer5f016e22007-07-11 17:01:13 +0000803//===----------------------------------------------------------------------===//
804// File Info Management.
805//===----------------------------------------------------------------------===//
806
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000807/// \brief Merge the header file info provided by \p OtherHFI into the current
808/// header file info (\p HFI)
809static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
810 const HeaderFileInfo &OtherHFI) {
811 HFI.isImport |= OtherHFI.isImport;
812 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
813 HFI.NumIncludes += OtherHFI.NumIncludes;
814
815 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
816 HFI.ControllingMacro = OtherHFI.ControllingMacro;
817 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
818 }
819
820 if (OtherHFI.External) {
821 HFI.DirInfo = OtherHFI.DirInfo;
822 HFI.External = OtherHFI.External;
823 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
824 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000825
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000826 if (HFI.Framework.empty())
827 HFI.Framework = OtherHFI.Framework;
828
829 HFI.Resolved = true;
830}
831
Steve Naroff83d63c72009-04-24 20:03:17 +0000832/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000833/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000834HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 if (FE->getUID() >= FileInfo.size())
836 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000837
838 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000839 if (ExternalSource && !HFI.Resolved)
840 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000841 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +0000842}
Reid Spencer5f016e22007-07-11 17:01:13 +0000843
Douglas Gregordd3e5542011-05-04 00:14:37 +0000844bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
845 // Check if we've ever seen this file as a header.
846 if (File->getUID() >= FileInfo.size())
847 return false;
848
849 // Resolve header file info from the external source, if needed.
850 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000851 if (ExternalSource && !HFI.Resolved)
852 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +0000853
Argyrios Kyrtzidis44dfff62012-12-10 20:08:37 +0000854 return HFI.isPragmaOnce || HFI.isImport ||
855 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregordd3e5542011-05-04 00:14:37 +0000856}
857
Steve Naroff83d63c72009-04-24 20:03:17 +0000858void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
859 if (UID >= FileInfo.size())
860 FileInfo.resize(UID+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000861 HFI.Resolved = true;
Steve Naroff83d63c72009-04-24 20:03:17 +0000862 FileInfo[UID] = HFI;
863}
864
Reid Spencer5f016e22007-07-11 17:01:13 +0000865bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
866 ++NumIncluded; // Count # of attempted #includes.
867
868 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +0000869 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Reid Spencer5f016e22007-07-11 17:01:13 +0000871 // If this is a #import directive, check that we have not already imported
872 // this header.
873 if (isImport) {
874 // If this has already been imported, don't import it again.
875 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // Has this already been #import'ed or #include'd?
878 if (FileInfo.NumIncludes) return false;
879 } else {
880 // Otherwise, if this is a #include of a file that was previously #import'd
881 // or if this is the second #include of a #pragma once file, ignore it.
882 if (FileInfo.isImport)
883 return false;
884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
887 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +0000888 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000889 = FileInfo.getControllingMacro(ExternalLookup))
890 if (ControllingMacro->hasMacroDefinition()) {
891 ++NumMultiIncludeFileOptzn;
892 return false;
893 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 // Increment the number of times this file has been included.
896 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 return true;
899}
900
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000901size_t HeaderSearch::getTotalMemory() const {
902 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +0000903 + llvm::capacity_in_bytes(FileInfo)
904 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000905 + LookupFileCache.getAllocator().getTotalMemory()
906 + FrameworkMap.getAllocator().getTotalMemory();
907}
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000908
909StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
910 return FrameworkNames.GetOrCreateValue(Framework).getKey();
911}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000912
913bool HeaderSearch::hasModuleMap(StringRef FileName,
914 const DirectoryEntry *Root) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000915 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000916
917 StringRef DirName = FileName;
918 do {
919 // Get the parent directory name.
920 DirName = llvm::sys::path::parent_path(DirName);
921 if (DirName.empty())
922 return false;
923
924 // Determine whether this directory exists.
925 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
926 if (!Dir)
927 return false;
928
Douglas Gregorcf70d782011-11-12 00:05:07 +0000929 // Try to load the module map file in this directory.
Douglas Gregor26697972011-11-12 00:22:19 +0000930 switch (loadModuleMapFile(Dir)) {
931 case LMM_NewlyLoaded:
932 case LMM_AlreadyLoaded:
Douglas Gregorcf70d782011-11-12 00:05:07 +0000933 // Success. All of the directories we stepped through inherit this module
934 // map file.
Douglas Gregora30cfe52011-11-11 19:10:28 +0000935 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
936 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
937
938 return true;
Douglas Gregor26697972011-11-12 00:22:19 +0000939
940 case LMM_NoDirectory:
941 case LMM_InvalidModuleMap:
942 break;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000943 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000944
Douglas Gregorcf70d782011-11-12 00:05:07 +0000945 // If we hit the top of our search, we're done.
946 if (Dir == Root)
947 return false;
948
Douglas Gregora30cfe52011-11-11 19:10:28 +0000949 // Keep track of all of the directories we checked, so we can mark them as
950 // having module maps if we eventually do find a module map.
951 FixUpDirectories.push_back(Dir);
952 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000953}
954
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000955Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000956 if (Module *Mod = ModMap.findModuleForHeader(File))
957 return Mod;
Douglas Gregor65f3b5e2011-11-11 22:18:48 +0000958
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000959 return 0;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000960}
961
Douglas Gregordb1cde72011-11-16 00:09:06 +0000962bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
963 const DirectoryEntry *Dir = File->getDir();
964
965 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
966 = DirectoryHasModuleMap.find(Dir);
967 if (KnownDir != DirectoryHasModuleMap.end())
968 return !KnownDir->second;
969
970 bool Result = ModMap.parseModuleMapFile(File);
Douglas Gregor4813442c2011-12-07 21:25:07 +0000971 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
972 // If the file we loaded was a module.map, look for the corresponding
973 // module_private.map.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000974 SmallString<128> PrivateFilename(Dir->getName());
Douglas Gregor4813442c2011-12-07 21:25:07 +0000975 llvm::sys::path::append(PrivateFilename, "module_private.map");
976 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
977 Result = ModMap.parseModuleMapFile(PrivateFile);
978 }
979
980 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000981 return Result;
982}
983
Douglas Gregore434ec72012-01-29 17:08:11 +0000984Module *HeaderSearch::loadFrameworkModule(StringRef Name,
985 const DirectoryEntry *Dir,
986 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000987 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000988 return Module;
989
990 // Try to load a module map file.
991 switch (loadModuleMapFile(Dir)) {
992 case LMM_InvalidModuleMap:
993 break;
994
995 case LMM_AlreadyLoaded:
996 case LMM_NoDirectory:
997 return 0;
998
999 case LMM_NewlyLoaded:
1000 return ModMap.findModule(Name);
1001 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +00001002
Douglas Gregor7005b902013-01-10 01:43:00 +00001003 // Figure out the top-level framework directory and the submodule path from
1004 // that top-level framework to the requested framework.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001005 SmallVector<std::string, 2> SubmodulePath;
Douglas Gregora8c6fea2012-01-13 22:31:52 +00001006 SubmodulePath.push_back(Name);
Douglas Gregor7005b902013-01-10 01:43:00 +00001007 const DirectoryEntry *TopFrameworkDir
1008 = ::getTopFrameworkDir(FileMgr, Dir->getName(), SubmodulePath);
Douglas Gregor82e52372012-11-06 19:39:40 +00001009
Douglas Gregor82e52372012-11-06 19:39:40 +00001010
Douglas Gregora8c6fea2012-01-13 22:31:52 +00001011 // Try to infer a module map from the top-level framework directory.
1012 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +00001013 TopFrameworkDir,
1014 IsSystem,
Douglas Gregora8c6fea2012-01-13 22:31:52 +00001015 /*Parent=*/0);
Douglas Gregor7005b902013-01-10 01:43:00 +00001016 if (!Result)
1017 return 0;
Douglas Gregora8c6fea2012-01-13 22:31:52 +00001018
1019 // Follow the submodule path to find the requested (sub)framework module
1020 // within the top-level framework module.
1021 SubmodulePath.pop_back();
1022 while (!SubmodulePath.empty() && Result) {
1023 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
1024 SubmodulePath.pop_back();
1025 }
1026 return Result;
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001027}
1028
Douglas Gregordb1cde72011-11-16 00:09:06 +00001029
Douglas Gregor26697972011-11-12 00:22:19 +00001030HeaderSearch::LoadModuleMapResult
1031HeaderSearch::loadModuleMapFile(StringRef DirName) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001032 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1033 return loadModuleMapFile(Dir);
1034
Douglas Gregor26697972011-11-12 00:22:19 +00001035 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001036}
1037
Douglas Gregor26697972011-11-12 00:22:19 +00001038HeaderSearch::LoadModuleMapResult
1039HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001040 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1041 = DirectoryHasModuleMap.find(Dir);
1042 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +00001043 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001044
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001045 SmallString<128> ModuleMapFileName;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001046 ModuleMapFileName += Dir->getName();
Douglas Gregor587986e2011-12-07 02:23:45 +00001047 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregorcf70d782011-11-12 00:05:07 +00001048 llvm::sys::path::append(ModuleMapFileName, "module.map");
1049 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
1050 // We have found a module map file. Try to parse it.
Douglas Gregor587986e2011-12-07 02:23:45 +00001051 if (ModMap.parseModuleMapFile(ModuleMapFile)) {
1052 // No suitable module map.
1053 DirectoryHasModuleMap[Dir] = false;
1054 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001055 }
Douglas Gregor587986e2011-12-07 02:23:45 +00001056
1057 // This directory has a module map.
1058 DirectoryHasModuleMap[Dir] = true;
1059
1060 // Check whether there is a private module map that we need to load as well.
1061 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
1062 ModuleMapFileName.end());
1063 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
1064 if (const FileEntry *PrivateModuleMapFile
1065 = FileMgr.getFile(ModuleMapFileName)) {
1066 if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
1067 // No suitable module map.
1068 DirectoryHasModuleMap[Dir] = false;
1069 return LMM_InvalidModuleMap;
1070 }
1071 }
1072
1073 return LMM_NewlyLoaded;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001074 }
1075
1076 // No suitable module map.
1077 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor26697972011-11-12 00:22:19 +00001078 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001079}
Douglas Gregora30cfe52011-11-11 19:10:28 +00001080
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001081void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001082 Modules.clear();
1083
1084 // Load module maps for each of the header search directories.
1085 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1086 if (SearchDirs[Idx].isFramework()) {
1087 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001088 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001089 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1090 DirNative);
1091
1092 // Search each of the ".framework" directories to load them as modules.
1093 bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
1094 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1095 Dir != DirEnd && !EC; Dir.increment(EC)) {
1096 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1097 continue;
1098
1099 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1100 if (!FrameworkDir)
1101 continue;
1102
1103 // Load this framework module.
1104 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1105 IsSystem);
1106 }
1107 continue;
1108 }
1109
1110 // FIXME: Deal with header maps.
1111 if (SearchDirs[Idx].isHeaderMap())
1112 continue;
1113
1114 // Try to load a module map file for the search directory.
1115 loadModuleMapFile(SearchDirs[Idx].getDir());
1116
1117 // Try to load module map files for immediate subdirectories of this search
1118 // directory.
1119 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001120 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001121 llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
1122 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1123 Dir != DirEnd && !EC; Dir.increment(EC)) {
1124 loadModuleMapFile(Dir->path());
1125 }
1126 }
1127
1128 // Populate the list of modules.
1129 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1130 MEnd = ModMap.module_end();
1131 M != MEnd; ++M) {
1132 Modules.push_back(M->getValue());
1133 }
1134}