blob: 97bff4f27739bff13ef8250544e882ce76f3e10d [file] [log] [blame]
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59a9ebd2006-10-18 05:34:33 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner59a9ebd2006-10-18 05:34:33 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Lex/HeaderMap.h"
18#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000019#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000020#include "clang/Lex/Lexer.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000021#include "llvm/ADT/SmallString.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000022#include "llvm/Support/Capacity.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/Path.h"
Daniel Jasperba7f2f72013-09-24 09:14:14 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000026#include <cstdio>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000027#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000028#include <limits.h>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000029#endif
Chris Lattner59a9ebd2006-10-18 05:34:33 +000030using namespace clang;
31
Douglas Gregor99734e72009-04-25 23:30:02 +000032const IdentifierInfo *
33HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
34 if (ControllingMacro)
35 return ControllingMacro;
36
37 if (!ControllingMacroID || !External)
38 return 0;
39
40 ControllingMacro = External->GetIdentifier(ControllingMacroID);
41 return ControllingMacro;
42}
43
Douglas Gregor09b69892011-02-10 17:09:37 +000044ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
45
Dmitri Gribenkof8579502013-01-12 19:30:44 +000046HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000047 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000048 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000049 const TargetInfo *Target)
Will Wilsonba2f1462013-12-27 20:02:27 +000050 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
51 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
Nico Weber3b1d1212011-05-24 04:31:14 +000052 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000053 SystemDirIdx = 0;
54 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000055
Douglas Gregor99734e72009-04-25 23:30:02 +000056 ExternalLookup = 0;
Douglas Gregor09b69892011-02-10 17:09:37 +000057 ExternalSource = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000058 NumIncluded = 0;
59 NumMultiIncludeFileOptzn = 0;
60 NumFrameworkLookups = NumSubFrameworkLookups = 0;
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +000061
62 EnabledModules = LangOpts.Modules;
Chris Lattner641a0be2006-10-20 06:23:14 +000063}
64
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000065HeaderSearch::~HeaderSearch() {
66 // Delete headermaps.
67 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
68 delete HeaderMaps[i].second;
69}
Mike Stump11289f42009-09-09 15:08:12 +000070
Chris Lattner59a9ebd2006-10-18 05:34:33 +000071void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000072 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
73 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000074 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
75 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
76 NumOnceOnlyFiles += FileInfo[i].isImport;
77 if (MaxNumIncludes < FileInfo[i].NumIncludes)
78 MaxNumIncludes = FileInfo[i].NumIncludes;
79 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
80 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000081 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
82 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
83 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000084
Chris Lattner23b7eb62007-06-15 23:05:46 +000085 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
86 fprintf(stderr, " %d #includes skipped due to"
87 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000088
Chris Lattner23b7eb62007-06-15 23:05:46 +000089 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
90 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000091}
92
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000093/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +000094/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +000095const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000096 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +000097 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000098 if (!HeaderMaps.empty()) {
99 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000100 // Pointer equality comparison of FileEntries works because they are
101 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000102 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000103 return HeaderMaps[i].second;
104 }
Mike Stump11289f42009-09-09 15:08:12 +0000105
Chris Lattner5159f612010-11-23 08:35:12 +0000106 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000107 HeaderMaps.push_back(std::make_pair(FE, HM));
108 return HM;
109 }
Mike Stump11289f42009-09-09 15:08:12 +0000110
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000111 return 0;
112}
113
Douglas Gregor279a6c32012-01-29 17:08:11 +0000114std::string HeaderSearch::getModuleFileName(Module *Module) {
Douglas Gregor1e44e022011-09-12 20:41:59 +0000115 // If we don't have a module cache path, we can't do anything.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000116 if (ModuleCachePath.empty())
117 return std::string();
118
119
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000120 SmallString<256> Result(ModuleCachePath);
Douglas Gregor279a6c32012-01-29 17:08:11 +0000121 llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
122 return Result.str().str();
123}
124
125std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
126 // If we don't have a module cache path, we can't do anything.
127 if (ModuleCachePath.empty())
128 return std::string();
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000129
Douglas Gregor279a6c32012-01-29 17:08:11 +0000130
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000131 SmallString<256> Result(ModuleCachePath);
Douglas Gregor279a6c32012-01-29 17:08:11 +0000132 llvm::sys::path::append(Result, ModuleName + ".pcm");
133 return Result.str().str();
134}
135
136Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000137 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000138 Module *Module = ModMap.findModule(ModuleName);
139 if (Module || !AllowSearch)
140 return Module;
141
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000142 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000143 // maps, searching for a module map that describes this module.
144 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
145 if (SearchDirs[Idx].isFramework()) {
146 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000147 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000148 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
149 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
150 if (const DirectoryEntry *FrameworkDir
151 = FileMgr.getDirectory(FrameworkDirName)) {
152 bool IsSystem
153 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
154 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000155 if (Module)
156 break;
157 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000158 }
159
160 // FIXME: Figure out how header maps and module maps will work together.
161
162 // Only deal with normal search directories.
163 if (!SearchDirs[Idx].isNormalDir())
164 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000165
166 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000167 // Search for a module map file in this directory.
Douglas Gregor963c5532013-06-21 16:28:10 +0000168 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem)
169 == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000170 // We just loaded a module map file; check whether the module is
171 // available now.
172 Module = ModMap.findModule(ModuleName);
173 if (Module)
174 break;
175 }
176
177 // Search for a module map in a subdirectory with the same name as the
178 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000179 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000180 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
181 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Douglas Gregor963c5532013-06-21 16:28:10 +0000182 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000183 // If we just loaded a module map file, look for the module again.
184 Module = ModMap.findModule(ModuleName);
185 if (Module)
186 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000187 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000188
189 // If we've already performed the exhaustive search for module maps in this
190 // search directory, don't do it again.
191 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
192 continue;
193
194 // Load all module maps in the immediate subdirectories of this search
195 // directory.
196 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
197
198 // Look again for the module.
199 Module = ModMap.findModule(ModuleName);
200 if (Module)
201 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000202 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000203
Douglas Gregor279a6c32012-01-29 17:08:11 +0000204 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000205}
206
Chris Lattnerf62f7582007-12-17 07:52:39 +0000207//===----------------------------------------------------------------------===//
208// File lookup within a DirectoryLookup scope
209//===----------------------------------------------------------------------===//
210
Chris Lattner8d720d02007-12-17 17:57:27 +0000211/// getName - Return the directory or filename corresponding to this lookup
212/// object.
213const char *DirectoryLookup::getName() const {
214 if (isNormalDir())
215 return getDir()->getName();
216 if (isFramework())
217 return getFrameworkDir()->getName();
218 assert(isHeaderMap() && "Unknown DirectoryLookup");
219 return getHeaderMap()->getFileName();
220}
221
Richard Smith8c71eba2014-03-05 20:51:45 +0000222static const FileEntry *
223getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
224 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
225 ModuleMap::KnownHeader *SuggestedModule) {
226 // If we have a module map that might map this header, load it and
227 // check whether we'll have a suggestion for a module.
228 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
229 if (SuggestedModule) {
230 const FileEntry *File = HS.getFileMgr().getFile(FileName,
231 /*OpenFile=*/false);
232 if (File) {
233 // If there is a module that corresponds to this header, suggest it.
234 *SuggestedModule = HS.findModuleForHeader(File);
235
236 // FIXME: This appears to be a no-op. We loaded the module map for this
237 // directory at the start of this function.
238 if (!SuggestedModule->getModule() &&
239 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
240 *SuggestedModule = HS.findModuleForHeader(File);
241 }
242
243 return File;
244 }
245
246 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
247}
Chris Lattner8d720d02007-12-17 17:57:27 +0000248
Chris Lattnerf62f7582007-12-17 07:52:39 +0000249/// LookupFile - Lookup the specified file in this search path, returning it
250/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000251const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000252 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000253 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000254 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000255 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000256 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000257 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000258 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000259 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000260 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000261 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000262
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000263 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000264 if (isNormalDir()) {
265 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000266 TmpDir = getDir()->getName();
267 llvm::sys::path::append(TmpDir, Filename);
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000268 if (SearchPath != NULL) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000269 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000270 SearchPath->clear();
271 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
272 }
273 if (RelativePath != NULL) {
274 RelativePath->clear();
275 RelativePath->append(Filename.begin(), Filename.end());
276 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000277
278 return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
279 isSystemHeaderDirectory(),
280 SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000281 }
Mike Stump11289f42009-09-09 15:08:12 +0000282
Chris Lattner712e3872007-12-17 08:13:48 +0000283 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000284 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000285 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattner44bd21b2007-12-17 08:17:39 +0000287 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000288 const HeaderMap *HM = getHeaderMap();
289 SmallString<1024> Path;
290 StringRef Dest = HM->lookupFilename(Filename, Path);
291 if (Dest.empty())
292 return 0;
293
294 const FileEntry *Result;
295
296 // Check if the headermap maps the filename to a framework include
297 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
298 // framework include.
299 if (llvm::sys::path::is_relative(Dest)) {
300 MappedName.clear();
301 MappedName.append(Dest.begin(), Dest.end());
302 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000303 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000304 Result = HM->LookupFile(Filename, HS.getFileMgr());
305
306 } else {
307 Result = HS.getFileMgr().getFile(Dest);
308 }
309
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000310 if (Result) {
311 if (SearchPath != NULL) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000312 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000313 SearchPath->clear();
314 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
315 }
316 if (RelativePath != NULL) {
317 RelativePath->clear();
318 RelativePath->append(Filename.begin(), Filename.end());
319 }
320 }
321 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000322}
323
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000324/// \brief Given a framework directory, find the top-most framework directory.
325///
326/// \param FileMgr The file manager to use for directory lookups.
327/// \param DirName The name of the framework directory.
328/// \param SubmodulePath Will be populated with the submodule path from the
329/// returned top-level module to the originally named framework.
330static const DirectoryEntry *
331getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
332 SmallVectorImpl<std::string> &SubmodulePath) {
333 assert(llvm::sys::path::extension(DirName) == ".framework" &&
334 "Not a framework directory");
335
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000336 // Note: as an egregious but useful hack we use the real path here, because
337 // frameworks moving between top-level frameworks to embedded frameworks tend
338 // to be symlinked, and we base the logical structure of modules on the
339 // physical layout. In particular, we need to deal with crazy includes like
340 //
341 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
342 //
343 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
344 // which one should access with, e.g.,
345 //
346 // #include <Bar/Wibble.h>
347 //
348 // Similar issues occur when a top-level framework has moved into an
349 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000350 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000351 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000352 do {
353 // Get the parent directory name.
354 DirName = llvm::sys::path::parent_path(DirName);
355 if (DirName.empty())
356 break;
357
358 // Determine whether this directory exists.
359 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
360 if (!Dir)
361 break;
362
363 // If this is a framework directory, then we're a subframework of this
364 // framework.
365 if (llvm::sys::path::extension(DirName) == ".framework") {
366 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
367 TopFrameworkDir = Dir;
368 }
369 } while (true);
370
371 return TopFrameworkDir;
372}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000373
Chris Lattner712e3872007-12-17 08:13:48 +0000374/// DoFrameworkLookup - Do a lookup of the specified file in the current
375/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000376const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000377 StringRef Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000378 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000379 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000380 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000381 ModuleMap::KnownHeader *SuggestedModule,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000382 bool &InUserSpecifiedSystemFramework) const
Douglas Gregor97eec242011-09-15 22:00:41 +0000383{
Chris Lattner712e3872007-12-17 08:13:48 +0000384 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000386 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000387 size_t SlashPos = Filename.find('/');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000388 if (SlashPos == StringRef::npos) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000389
Chris Lattner712e3872007-12-17 08:13:48 +0000390 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000391 // HeaderSearch. Possible answers are yes/no and unknown.
392 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000393 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattner712e3872007-12-17 08:13:48 +0000395 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000396 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Chris Lattner5ed76da2006-10-22 07:24:13 +0000397 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattner712e3872007-12-17 08:13:48 +0000399 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000401 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000402 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000403 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000404 if (FrameworkName.empty() || FrameworkName.back() != '/')
405 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000406
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000407 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000408 StringRef ModuleName(Filename.begin(), SlashPos);
409 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000411 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
412 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000413
Daniel Dunbar17138612012-04-05 17:09:40 +0000414 // If the cache entry was unresolved, populate it now.
415 if (CacheEntry.Directory == 0) {
Chris Lattner712e3872007-12-17 08:13:48 +0000416 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattner5ed76da2006-10-22 07:24:13 +0000418 // If the framework dir doesn't exist, we fail.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000419 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
420 if (Dir == 0) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattner5ed76da2006-10-22 07:24:13 +0000422 // Otherwise, if it does, remember that this is the right direntry for this
423 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000424 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000425
426 // If this is a user search directory, check if the framework has been
427 // user-specified as a system framework.
428 if (getDirCharacteristic() == SrcMgr::C_User) {
429 SmallString<1024> SystemFrameworkMarker(FrameworkName);
430 SystemFrameworkMarker += ".system_framework";
431 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
432 CacheEntry.IsUserSpecifiedSystemFramework = true;
433 }
434 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000435 }
Mike Stump11289f42009-09-09 15:08:12 +0000436
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000437 // Set the 'user-specified system framework' flag.
438 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
439
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000440 if (RelativePath != NULL) {
441 RelativePath->clear();
442 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
443 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000444
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000445 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000446 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000447
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000448 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000449
450 if (SearchPath != NULL) {
451 SearchPath->clear();
452 // Without trailing '/'.
453 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
454 }
455
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000456 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000457 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
458 /*openFile=*/!SuggestedModule);
459 if (!FE) {
460 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
461 const char *Private = "Private";
462 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
463 Private+strlen(Private));
464 if (SearchPath != NULL)
465 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
466 Private+strlen(Private));
467
468 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000471 // If we found the header and are allowed to suggest a module, do so now.
472 if (FE && SuggestedModule) {
473 // Find the framework in which this header occurs.
474 StringRef FrameworkPath = FE->getName();
475 bool FoundFramework = false;
476 do {
477 // Get the parent directory name.
478 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
479 if (FrameworkPath.empty())
480 break;
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000481
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000482 // Determine whether this directory exists.
483 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
484 if (!Dir)
485 break;
486
487 // If this is a framework directory, then we're a subframework of this
488 // framework.
489 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
490 FoundFramework = true;
491 break;
492 }
493 } while (true);
494
495 if (FoundFramework) {
496 // Find the top-level framework based on this framework.
497 SmallVector<std::string, 4> SubmodulePath;
498 const DirectoryEntry *TopFrameworkDir
499 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
500
501 // Determine the name of the top-level framework.
502 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
503
504 // Load this framework module. If that succeeds, find the suggested module
505 // for this header, if any.
506 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
507 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
508 *SuggestedModule = HS.findModuleForHeader(FE);
509 }
510 } else {
511 *SuggestedModule = HS.findModuleForHeader(FE);
512 }
513 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000514 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000515}
516
Douglas Gregor89929282012-01-30 06:01:29 +0000517void HeaderSearch::setTarget(const TargetInfo &Target) {
518 ModMap.setTarget(Target);
519}
520
Chris Lattnerf62f7582007-12-17 07:52:39 +0000521
Chris Lattner712e3872007-12-17 08:13:48 +0000522//===----------------------------------------------------------------------===//
523// Header File Location.
524//===----------------------------------------------------------------------===//
525
Reid Klecknera97d4c02014-02-18 23:49:24 +0000526/// \brief Return true with a diagnostic if the file that MSVC would have found
527/// fails to match the one that Clang would have found with MSVC header search
528/// disabled.
529static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
530 const FileEntry *MSFE, const FileEntry *FE,
531 SourceLocation IncludeLoc) {
532 if (MSFE && FE != MSFE) {
533 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
534 return true;
535 }
536 return false;
537}
Chris Lattner712e3872007-12-17 08:13:48 +0000538
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000539static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
540 assert(!Str.empty());
541 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
542 std::copy(Str.begin(), Str.end(), CopyStr);
543 CopyStr[Str.size()] = '\0';
544 return CopyStr;
545}
546
James Dennettc07ab2c2012-06-20 00:56:32 +0000547/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000548/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000549/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
550/// non-empty, indicates where the \#including file(s) are, in case a relative
551/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000552const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000553 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
554 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
555 ArrayRef<const FileEntry *> Includers, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000556 SmallVectorImpl<char> *RelativePath,
Will Wilson0fafd342013-12-27 19:46:16 +0000557 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
Daniel Jasper97da9172013-10-22 08:09:47 +0000558 if (!HSOpts->ModuleMapFiles.empty()) {
559 // Preload all explicitly specified module map files. This enables modules
560 // map files lying in a directory structure separate from the header files
561 // that they describe. These cannot be loaded lazily upon encountering a
Will Wilson9ef61a72013-12-19 16:24:17 +0000562 // header file, as there is no other known mapping from a header file to its
Daniel Jasper97da9172013-10-22 08:09:47 +0000563 // module map file.
564 for (llvm::SetVector<std::string>::iterator
565 I = HSOpts->ModuleMapFiles.begin(),
566 E = HSOpts->ModuleMapFiles.end();
567 I != E; ++I) {
568 const FileEntry *File = FileMgr.getFile(*I);
569 if (!File)
570 continue;
571 loadModuleMapFile(File, /*IsSystem=*/false);
572 }
573 HSOpts->ModuleMapFiles.clear();
574 }
575
Douglas Gregor97eec242011-09-15 22:00:41 +0000576 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000577 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000578
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000579 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000580 if (llvm::sys::path::is_absolute(Filename)) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000581 CurDir = 0;
582
583 // If this was an #include_next "/absolute/file", fail.
584 if (FromDir) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000585
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000586 if (SearchPath != NULL)
587 SearchPath->clear();
588 if (RelativePath != NULL) {
589 RelativePath->clear();
590 RelativePath->append(Filename.begin(), Filename.end());
591 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000592 // Otherwise, just return the file.
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000593 return FileMgr.getFile(Filename, /*openFile=*/true);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000594 }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Reid Klecknera97d4c02014-02-18 23:49:24 +0000596 // This is the header that MSVC's header search would have found.
597 const FileEntry *MSFE = 0;
Richard Smith8c71eba2014-03-05 20:51:45 +0000598 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000599
Douglas Gregor9f93e382011-07-28 04:45:53 +0000600 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000601 // directory. This cannot be based on CurDir, because each includer could be
602 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
603 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000604 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000605 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000606 SmallString<1024> TmpDir;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000607 for (ArrayRef<const FileEntry *>::iterator I = Includers.begin(),
608 E = Includers.end();
Will Wilson0fafd342013-12-27 19:46:16 +0000609 I != E; ++I) {
610 const FileEntry *Includer = *I;
611 // Concatenate the requested file onto the directory.
612 // FIXME: Portability. Filename concatenation should be in sys::Path.
613 TmpDir = Includer->getDir()->getName();
614 TmpDir.push_back('/');
615 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000616
Richard Smith6f548ec2014-03-06 18:08:08 +0000617 // FIXME: We don't cache the result of getFileInfo across the call to
618 // getFileAndSuggestModule, because it's a reference to an element of
619 // a container that could be reallocated across this call.
620 bool IncluderIsSystemHeader =
621 getFileInfo(Includer).DirInfo != SrcMgr::C_User;
Will Wilson0fafd342013-12-27 19:46:16 +0000622 if (const FileEntry *FE =
Richard Smith8c71eba2014-03-05 20:51:45 +0000623 getFileAndSuggestModule(*this, TmpDir.str(), Includer->getDir(),
Richard Smith6f548ec2014-03-06 18:08:08 +0000624 IncluderIsSystemHeader,
Richard Smith8c71eba2014-03-05 20:51:45 +0000625 SuggestedModule)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000626 // Leave CurDir unset.
627 // This file is a system header or C++ unfriendly if the old file is.
628 //
629 // Note that we only use one of FromHFI/ToHFI at once, due to potential
630 // reallocation of the underlying vector potentially making the first
631 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000632 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000633 unsigned DirInfo = FromHFI.DirInfo;
634 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
635 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000636
Will Wilson0fafd342013-12-27 19:46:16 +0000637 HeaderFileInfo &ToHFI = getFileInfo(FE);
638 ToHFI.DirInfo = DirInfo;
639 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
640 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000641
Will Wilson0fafd342013-12-27 19:46:16 +0000642 if (SearchPath != NULL) {
643 StringRef SearchPathRef(Includer->getDir()->getName());
644 SearchPath->clear();
645 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
646 }
647 if (RelativePath != NULL) {
648 RelativePath->clear();
649 RelativePath->append(Filename.begin(), Filename.end());
650 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000651 if (I == Includers.begin())
652 return FE;
653
654 // Otherwise, we found the path via MSVC header search rules. If
655 // -Wmsvc-include is enabled, we have to keep searching to see if we
656 // would've found this header in -I or -isystem directories.
657 if (Diags.getDiagnosticLevel(diag::ext_pp_include_search_ms,
658 IncludeLoc) ==
659 DiagnosticsEngine::Ignored) {
660 return FE;
661 } else {
662 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000663 if (SuggestedModule) {
664 MSSuggestedModule = *SuggestedModule;
665 *SuggestedModule = ModuleMap::KnownHeader();
666 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000667 break;
668 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000669 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000670 }
671 }
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000673 CurDir = 0;
674
675 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000676 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000678 // If this is a #include_next request, start searching after the directory the
679 // file was found in.
680 if (FromDir)
681 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000682
Chris Lattnerd4275422007-07-22 07:28:00 +0000683 // Cache all of the lookups performed by this method. Many headers are
684 // multiply included, and the "pragma once" optimization prevents them from
685 // being relex/pp'd, but they would still have to search through a
686 // (potentially huge) series of SearchDirs to find it.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000687 LookupFileCacheInfo &CacheLookup =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000688 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattnerd4275422007-07-22 07:28:00 +0000689
690 // If the entry has been previously looked up, the first value will be
691 // non-zero. If the value is equal to i (the start point of our search), then
692 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000693 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000694 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000695 i = CacheLookup.HitIdx;
696 if (CacheLookup.MappedName)
697 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000698 } else {
699 // Otherwise, this is the first query, or the previous query didn't match
700 // our search start. We will fill in our found location below, so prime the
701 // start point value.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000702 CacheLookup.StartIdx = i+1;
Chris Lattnerd4275422007-07-22 07:28:00 +0000703 }
Mike Stump11289f42009-09-09 15:08:12 +0000704
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000705 SmallString<64> MappedName;
706
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000707 // Check each directory in sequence to see if it contains this file.
708 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000709 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000710 bool HasBeenMapped = false;
Mike Stump11289f42009-09-09 15:08:12 +0000711 const FileEntry *FE =
Douglas Gregor97eec242011-09-15 22:00:41 +0000712 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000713 SuggestedModule, InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000714 HasBeenMapped, MappedName);
715 if (HasBeenMapped) {
716 CacheLookup.MappedName =
717 copyString(Filename, LookupFileCache.getAllocator());
718 }
Chris Lattner712e3872007-12-17 08:13:48 +0000719 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattner712e3872007-12-17 08:13:48 +0000721 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000722
Chris Lattner712e3872007-12-17 08:13:48 +0000723 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000724 HeaderFileInfo &HFI = getFileInfo(FE);
725 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000726
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000727 // If the directory characteristic is User but this framework was
728 // user-specified to be treated as a system framework, promote the
729 // characteristic.
730 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
731 HFI.DirInfo = SrcMgr::C_System;
732
Richard Smith8acadcb2012-06-13 20:27:03 +0000733 // If the filename matches a known system header prefix, override
734 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000735 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
736 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
737 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000738 : SrcMgr::C_User;
739 break;
740 }
741 }
742
Douglas Gregor9f93e382011-07-28 04:45:53 +0000743 // If this file is found in a header map and uses the framework style of
744 // includes, then this header is part of a framework we're building.
745 if (CurDir->isIndexHeaderMap()) {
746 size_t SlashPos = Filename.find('/');
747 if (SlashPos != StringRef::npos) {
748 HFI.IndexHeaderMapHeader = 1;
749 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
750 SlashPos));
751 }
752 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000753
Richard Smith8c71eba2014-03-05 20:51:45 +0000754 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
755 if (SuggestedModule)
756 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000757 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000758 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000759
Chris Lattner712e3872007-12-17 08:13:48 +0000760 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000761 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000762 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000763 }
Mike Stump11289f42009-09-09 15:08:12 +0000764
Douglas Gregord8575e12011-07-30 06:28:34 +0000765 // If we are including a file with a quoted include "foo.h" from inside
766 // a header in a framework that is currently being built, and we couldn't
767 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
768 // "Foo" is the name of the framework in which the including header was found.
Will Wilson0fafd342013-12-27 19:46:16 +0000769 if (!Includers.empty() && !isAngled &&
770 Filename.find('/') == StringRef::npos) {
771 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front());
Douglas Gregord8575e12011-07-30 06:28:34 +0000772 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000773 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000774 ScratchFilename += IncludingHFI.Framework;
775 ScratchFilename += '/';
776 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000777
Reid Klecknera97d4c02014-02-18 23:49:24 +0000778 const FileEntry *FE = LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000779 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
780 Includers.front(), SearchPath, RelativePath, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000781
Richard Smith8c71eba2014-03-05 20:51:45 +0000782 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
783 if (SuggestedModule)
784 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000785 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000786 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000787
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000788 LookupFileCacheInfo &CacheLookup
Douglas Gregord8575e12011-07-30 06:28:34 +0000789 = LookupFileCache.GetOrCreateValue(Filename).getValue();
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000790 CacheLookup.HitIdx
791 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000792 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000793 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000794 }
795 }
796
Richard Smith8c71eba2014-03-05 20:51:45 +0000797 if (checkMSVCHeaderSearch(Diags, MSFE, 0, IncludeLoc)) {
798 if (SuggestedModule)
799 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000800 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000801 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000802
Chris Lattnerd4275422007-07-22 07:28:00 +0000803 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000804 CacheLookup.HitIdx = SearchDirs.size();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000805 return 0;
806}
807
Chris Lattner63dd32b2006-10-20 04:42:40 +0000808/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000809/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000810/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
811/// is a subframework within Carbon.framework. If so, return the FileEntry
812/// for the designated file, otherwise return null.
813const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000814LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000815 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000816 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000817 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000818 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000819 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattner63dd32b2006-10-20 04:42:40 +0000821 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000822 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000823 size_t SlashPos = Filename.find('/');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000824 if (SlashPos == StringRef::npos) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000825
Chris Lattner63dd32b2006-10-20 04:42:40 +0000826 // Look up the base framework name of the ContextFileEnt.
Chris Lattner48043482006-10-27 05:12:36 +0000827 const char *ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chris Lattner63dd32b2006-10-20 04:42:40 +0000829 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000830 const unsigned DotFrameworkLen = 10;
831 const char *FrameworkPos = strstr(ContextName, ".framework");
832 if (FrameworkPos == 0 ||
833 (FrameworkPos[DotFrameworkLen] != '/' &&
834 FrameworkPos[DotFrameworkLen] != '\\'))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000835 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000836
Daniel Dunbar17138612012-04-05 17:09:40 +0000837 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000838
Chris Lattner63dd32b2006-10-20 04:42:40 +0000839 // Append Frameworks/HIToolbox.framework/
840 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000841 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000842 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000843
Daniel Dunbar17138612012-04-05 17:09:40 +0000844 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
Chris Lattner8afa6de2010-11-21 09:55:08 +0000845 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000846
Chris Lattner5ed76da2006-10-22 07:24:13 +0000847 // Some other location?
Daniel Dunbar17138612012-04-05 17:09:40 +0000848 if (CacheLookup.getValue().Directory &&
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000849 CacheLookup.getKeyLength() == FrameworkName.size() &&
850 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
851 CacheLookup.getKeyLength()) != 0)
Chris Lattner5ed76da2006-10-22 07:24:13 +0000852 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000853
Chris Lattner5ed76da2006-10-22 07:24:13 +0000854 // Cache subframework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000855 if (CacheLookup.getValue().Directory == 0) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000856 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000857
Chris Lattner5ed76da2006-10-22 07:24:13 +0000858 // If the framework dir doesn't exist, we fail.
Chris Lattner5159f612010-11-23 08:35:12 +0000859 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Chris Lattner5ed76da2006-10-22 07:24:13 +0000860 if (Dir == 0) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000861
Chris Lattner5ed76da2006-10-22 07:24:13 +0000862 // Otherwise, if it does, remember that this is the right direntry for this
863 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000864 CacheLookup.getValue().Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000865 }
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattner577377e2006-10-20 04:55:45 +0000867 const FileEntry *FE = 0;
868
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000869 if (RelativePath != NULL) {
870 RelativePath->clear();
871 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
872 }
873
Chris Lattner63dd32b2006-10-20 04:42:40 +0000874 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000875 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000876 HeadersFilename += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000877 if (SearchPath != NULL) {
878 SearchPath->clear();
879 // Without trailing '/'.
880 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
881 }
882
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000883 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000884 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000885
Chris Lattner63dd32b2006-10-20 04:42:40 +0000886 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000887 HeadersFilename = FrameworkName;
888 HeadersFilename += "PrivateHeaders/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000889 if (SearchPath != NULL) {
890 SearchPath->clear();
891 // Without trailing '/'.
892 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
893 }
894
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000895 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000896 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000897 return 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000898 }
Mike Stump11289f42009-09-09 15:08:12 +0000899
Chris Lattner577377e2006-10-20 04:55:45 +0000900 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000901 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000902 // Note that the temporary 'DirInfo' is required here, as either call to
903 // getFileInfo could resize the vector and we don't want to rely on order
904 // of evaluation.
905 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
906 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000907
908 // If we're supposed to suggest a module, look for one now.
909 if (SuggestedModule) {
910 // Find the top-level framework based on this framework.
911 FrameworkName.pop_back(); // remove the trailing '/'
912 SmallVector<std::string, 4> SubmodulePath;
913 const DirectoryEntry *TopFrameworkDir
914 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
915
916 // Determine the name of the top-level framework.
917 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
918
919 // Load this framework module. If that succeeds, find the suggested module
920 // for this header, if any.
921 bool IsSystem = false;
922 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
923 *SuggestedModule = findModuleForHeader(FE);
924 }
925 }
926
Chris Lattner577377e2006-10-20 04:55:45 +0000927 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000928}
929
Chandler Carruthb0ffe502011-12-09 01:33:57 +0000930/// \brief Helper static function to normalize a path for injection into
931/// a synthetic header.
932/*static*/ std::string
933HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
934 // Implicit include paths should be resolved relative to the current
935 // working directory first, and then use the regular header search
936 // mechanism. The proper way to handle this is to have the
937 // predefines buffer located at the current working directory, but
938 // it has no file entry. For now, workaround this by using an
939 // absolute path if we find the file here, and otherwise letting
940 // header search handle it.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000941 SmallString<128> Path(File);
Chandler Carruthb0ffe502011-12-09 01:33:57 +0000942 llvm::sys::fs::make_absolute(Path);
943 bool exists;
944 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
945 Path = File;
946 else if (exists)
947 FileMgr.getFile(File);
948
949 return Lexer::Stringify(Path.str());
950}
951
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000952//===----------------------------------------------------------------------===//
953// File Info Management.
954//===----------------------------------------------------------------------===//
955
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000956/// \brief Merge the header file info provided by \p OtherHFI into the current
957/// header file info (\p HFI)
958static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
959 const HeaderFileInfo &OtherHFI) {
960 HFI.isImport |= OtherHFI.isImport;
961 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000962 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000963 HFI.NumIncludes += OtherHFI.NumIncludes;
964
965 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
966 HFI.ControllingMacro = OtherHFI.ControllingMacro;
967 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
968 }
969
970 if (OtherHFI.External) {
971 HFI.DirInfo = OtherHFI.DirInfo;
972 HFI.External = OtherHFI.External;
973 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
974 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000975
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000976 if (HFI.Framework.empty())
977 HFI.Framework = OtherHFI.Framework;
978
979 HFI.Resolved = true;
980}
981
Steve Naroff3fa455a2009-04-24 20:03:17 +0000982/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000983/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000984HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000985 if (FE->getUID() >= FileInfo.size())
986 FileInfo.resize(FE->getUID()+1);
Douglas Gregor09b69892011-02-10 17:09:37 +0000987
988 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000989 if (ExternalSource && !HFI.Resolved)
990 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregor09b69892011-02-10 17:09:37 +0000991 return HFI;
Mike Stump11289f42009-09-09 15:08:12 +0000992}
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000993
Douglas Gregor37aa4932011-05-04 00:14:37 +0000994bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
995 // Check if we've ever seen this file as a header.
996 if (File->getUID() >= FileInfo.size())
997 return false;
998
999 // Resolve header file info from the external source, if needed.
1000 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001001 if (ExternalSource && !HFI.Resolved)
1002 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregor37aa4932011-05-04 00:14:37 +00001003
Argyrios Kyrtzidis0d355df2012-12-10 20:08:37 +00001004 return HFI.isPragmaOnce || HFI.isImport ||
1005 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001006}
1007
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001008void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001009 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001010 bool isCompilingModuleHeader) {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001011 if (FE->getUID() >= FileInfo.size())
1012 FileInfo.resize(FE->getUID()+1);
1013
1014 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1015 HFI.isModuleHeader = true;
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001016 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001017 HFI.setHeaderRole(Role);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001018}
1019
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001020bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1021 ++NumIncluded; // Count # of attempted #includes.
1022
1023 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001024 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001025
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001026 // If this is a #import directive, check that we have not already imported
1027 // this header.
1028 if (isImport) {
1029 // If this has already been imported, don't import it again.
1030 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001032 // Has this already been #import'ed or #include'd?
1033 if (FileInfo.NumIncludes) return false;
1034 } else {
1035 // Otherwise, if this is a #include of a file that was previously #import'd
1036 // or if this is the second #include of a #pragma once file, ignore it.
1037 if (FileInfo.isImport)
1038 return false;
1039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001041 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1042 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001043 if (const IdentifierInfo *ControllingMacro
Douglas Gregor99734e72009-04-25 23:30:02 +00001044 = FileInfo.getControllingMacro(ExternalLookup))
1045 if (ControllingMacro->hasMacroDefinition()) {
1046 ++NumMultiIncludeFileOptzn;
1047 return false;
1048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001050 // Increment the number of times this file has been included.
1051 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001053 return true;
1054}
1055
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001056size_t HeaderSearch::getTotalMemory() const {
1057 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001058 + llvm::capacity_in_bytes(FileInfo)
1059 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001060 + LookupFileCache.getAllocator().getTotalMemory()
1061 + FrameworkMap.getAllocator().getTotalMemory();
1062}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001063
1064StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1065 return FrameworkNames.GetOrCreateValue(Framework).getKey();
1066}
Douglas Gregor718292f2011-11-11 19:10:28 +00001067
1068bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001069 const DirectoryEntry *Root,
1070 bool IsSystem) {
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001071 if (!enabledModules())
1072 return false;
1073
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001074 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001075
1076 StringRef DirName = FileName;
1077 do {
1078 // Get the parent directory name.
1079 DirName = llvm::sys::path::parent_path(DirName);
1080 if (DirName.empty())
1081 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001082
Douglas Gregor718292f2011-11-11 19:10:28 +00001083 // Determine whether this directory exists.
1084 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1085 if (!Dir)
1086 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001087
1088 // Try to load the "module.map" file in this directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001089 switch (loadModuleMapFile(Dir, IsSystem)) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001090 case LMM_NewlyLoaded:
1091 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001092 // Success. All of the directories we stepped through inherit this module
1093 // map file.
1094 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1095 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1096 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001097
1098 case LMM_NoDirectory:
1099 case LMM_InvalidModuleMap:
1100 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001101 }
1102
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001103 // If we hit the top of our search, we're done.
1104 if (Dir == Root)
1105 return false;
1106
Douglas Gregor718292f2011-11-11 19:10:28 +00001107 // Keep track of all of the directories we checked, so we can mark them as
1108 // having module maps if we eventually do find a module map.
1109 FixUpDirectories.push_back(Dir);
1110 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001111}
1112
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001113ModuleMap::KnownHeader
1114HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001115 if (ExternalSource) {
1116 // Make sure the external source has handled header info about this file,
1117 // which includes whether the file is part of a module.
1118 (void)getFileInfo(File);
1119 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001120 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001121}
1122
Douglas Gregor963c5532013-06-21 16:28:10 +00001123bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001124 const DirectoryEntry *Dir = File->getDir();
1125
1126 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1127 = DirectoryHasModuleMap.find(Dir);
1128 if (KnownDir != DirectoryHasModuleMap.end())
1129 return !KnownDir->second;
1130
Douglas Gregor963c5532013-06-21 16:28:10 +00001131 bool Result = ModMap.parseModuleMapFile(File, IsSystem);
Douglas Gregor80306772011-12-07 21:25:07 +00001132 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
1133 // If the file we loaded was a module.map, look for the corresponding
1134 // module_private.map.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001135 SmallString<128> PrivateFilename(Dir->getName());
Douglas Gregor80306772011-12-07 21:25:07 +00001136 llvm::sys::path::append(PrivateFilename, "module_private.map");
1137 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
Douglas Gregor963c5532013-06-21 16:28:10 +00001138 Result = ModMap.parseModuleMapFile(PrivateFile, IsSystem);
Douglas Gregor80306772011-12-07 21:25:07 +00001139 }
1140
1141 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001142 return Result;
1143}
1144
Douglas Gregor279a6c32012-01-29 17:08:11 +00001145Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1146 const DirectoryEntry *Dir,
1147 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001148 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001149 return Module;
1150
1151 // Try to load a module map file.
Douglas Gregor963c5532013-06-21 16:28:10 +00001152 switch (loadModuleMapFile(Dir, IsSystem)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001153 case LMM_InvalidModuleMap:
1154 break;
1155
1156 case LMM_AlreadyLoaded:
1157 case LMM_NoDirectory:
1158 return 0;
1159
1160 case LMM_NewlyLoaded:
1161 return ModMap.findModule(Name);
1162 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001163
Douglas Gregor4ddf2222013-01-10 01:43:00 +00001164 // Figure out the top-level framework directory and the submodule path from
1165 // that top-level framework to the requested framework.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001166 SmallVector<std::string, 2> SubmodulePath;
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001167 SubmodulePath.push_back(Name);
Douglas Gregor4ddf2222013-01-10 01:43:00 +00001168 const DirectoryEntry *TopFrameworkDir
1169 = ::getTopFrameworkDir(FileMgr, Dir->getName(), SubmodulePath);
Douglas Gregor9194a912012-11-06 19:39:40 +00001170
Douglas Gregor9194a912012-11-06 19:39:40 +00001171
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001172 // Try to infer a module map from the top-level framework directory.
1173 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora686e1b2012-01-27 19:52:33 +00001174 TopFrameworkDir,
1175 IsSystem,
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001176 /*Parent=*/0);
Douglas Gregor4ddf2222013-01-10 01:43:00 +00001177 if (!Result)
1178 return 0;
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001179
1180 // Follow the submodule path to find the requested (sub)framework module
1181 // within the top-level framework module.
1182 SubmodulePath.pop_back();
1183 while (!SubmodulePath.empty() && Result) {
1184 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
1185 SubmodulePath.pop_back();
1186 }
1187 return Result;
Douglas Gregor56c64012011-11-17 01:41:17 +00001188}
1189
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001190
Douglas Gregor80b69042011-11-12 00:22:19 +00001191HeaderSearch::LoadModuleMapResult
Douglas Gregor963c5532013-06-21 16:28:10 +00001192HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001193 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Douglas Gregor963c5532013-06-21 16:28:10 +00001194 return loadModuleMapFile(Dir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001195
Douglas Gregor80b69042011-11-12 00:22:19 +00001196 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001197}
1198
Douglas Gregor80b69042011-11-12 00:22:19 +00001199HeaderSearch::LoadModuleMapResult
Douglas Gregor963c5532013-06-21 16:28:10 +00001200HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001201 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1202 = DirectoryHasModuleMap.find(Dir);
1203 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor80b69042011-11-12 00:22:19 +00001204 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001205
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001206 SmallString<128> ModuleMapFileName;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001207 ModuleMapFileName += Dir->getName();
Douglas Gregore7ab3662011-12-07 02:23:45 +00001208 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001209 llvm::sys::path::append(ModuleMapFileName, "module.map");
1210 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
1211 // We have found a module map file. Try to parse it.
Douglas Gregor963c5532013-06-21 16:28:10 +00001212 if (ModMap.parseModuleMapFile(ModuleMapFile, IsSystem)) {
Douglas Gregore7ab3662011-12-07 02:23:45 +00001213 // No suitable module map.
1214 DirectoryHasModuleMap[Dir] = false;
1215 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001216 }
Douglas Gregore7ab3662011-12-07 02:23:45 +00001217
1218 // This directory has a module map.
1219 DirectoryHasModuleMap[Dir] = true;
1220
1221 // Check whether there is a private module map that we need to load as well.
1222 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
1223 ModuleMapFileName.end());
1224 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
1225 if (const FileEntry *PrivateModuleMapFile
1226 = FileMgr.getFile(ModuleMapFileName)) {
Douglas Gregor963c5532013-06-21 16:28:10 +00001227 if (ModMap.parseModuleMapFile(PrivateModuleMapFile, IsSystem)) {
Douglas Gregore7ab3662011-12-07 02:23:45 +00001228 // No suitable module map.
1229 DirectoryHasModuleMap[Dir] = false;
1230 return LMM_InvalidModuleMap;
1231 }
1232 }
1233
1234 return LMM_NewlyLoaded;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001235 }
1236
1237 // No suitable module map.
1238 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor80b69042011-11-12 00:22:19 +00001239 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001240}
Douglas Gregor718292f2011-11-11 19:10:28 +00001241
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001242void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001243 Modules.clear();
1244
1245 // Load module maps for each of the header search directories.
1246 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor963c5532013-06-21 16:28:10 +00001247 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor07f43572012-01-29 18:15:03 +00001248 if (SearchDirs[Idx].isFramework()) {
1249 llvm::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001250 SmallString<128> DirNative;
Douglas Gregor07f43572012-01-29 18:15:03 +00001251 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1252 DirNative);
1253
1254 // Search each of the ".framework" directories to load them as modules.
Douglas Gregor07f43572012-01-29 18:15:03 +00001255 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1256 Dir != DirEnd && !EC; Dir.increment(EC)) {
1257 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1258 continue;
1259
1260 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1261 if (!FrameworkDir)
1262 continue;
1263
1264 // Load this framework module.
1265 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1266 IsSystem);
1267 }
1268 continue;
1269 }
1270
1271 // FIXME: Deal with header maps.
1272 if (SearchDirs[Idx].isHeaderMap())
1273 continue;
1274
1275 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001276 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem);
Douglas Gregor07f43572012-01-29 18:15:03 +00001277
1278 // Try to load module map files for immediate subdirectories of this search
1279 // directory.
Douglas Gregor0339a642013-03-21 01:08:50 +00001280 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001281 }
1282
1283 // Populate the list of modules.
1284 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1285 MEnd = ModMap.module_end();
1286 M != MEnd; ++M) {
1287 Modules.push_back(M->getValue());
1288 }
1289}
Douglas Gregor0339a642013-03-21 01:08:50 +00001290
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001291void HeaderSearch::loadTopLevelSystemModules() {
1292 // Load module maps for each of the header search directories.
1293 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001294 // We only care about normal header directories.
1295 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001296 continue;
1297 }
1298
1299 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001300 loadModuleMapFile(SearchDirs[Idx].getDir(),
1301 SearchDirs[Idx].isSystemHeaderDirectory());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001302 }
1303}
1304
Douglas Gregor0339a642013-03-21 01:08:50 +00001305void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1306 if (SearchDir.haveSearchedAllModuleMaps())
1307 return;
1308
1309 llvm::error_code EC;
1310 SmallString<128> DirNative;
1311 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1312 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1313 Dir != DirEnd && !EC; Dir.increment(EC)) {
Douglas Gregor963c5532013-06-21 16:28:10 +00001314 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory());
Douglas Gregor0339a642013-03-21 01:08:50 +00001315 }
1316
1317 SearchDir.setSearchedAllModuleMaps(true);
1318}