blob: 131f6aa09cf824f747c927d0d76645bfec782dcc [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"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000021#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000023#include "llvm/ADT/SmallString.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000024#include "llvm/Support/Capacity.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/Support/FileSystem.h"
26#include "llvm/Support/Path.h"
Daniel Jasperba7f2f72013-09-24 09:14:14 +000027#include "llvm/Support/raw_ostream.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000028#include <cstdio>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000029#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000030#include <limits.h>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000031#endif
Chris Lattner59a9ebd2006-10-18 05:34:33 +000032using namespace clang;
33
Douglas Gregor99734e72009-04-25 23:30:02 +000034const IdentifierInfo *
35HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
36 if (ControllingMacro)
37 return ControllingMacro;
38
39 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000040 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000041
42 ControllingMacro = External->GetIdentifier(ControllingMacroID);
43 return ControllingMacro;
44}
45
Douglas Gregor09b69892011-02-10 17:09:37 +000046ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
47
Dmitri Gribenkof8579502013-01-12 19:30:44 +000048HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000049 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000050 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000051 const TargetInfo *Target)
Will Wilsonba2f1462013-12-27 20:02:27 +000052 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
Daniel Jasper21a0f552014-11-25 09:45:48 +000053 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this),
54 LangOpts(LangOpts) {
Nico Weber3b1d1212011-05-24 04:31:14 +000055 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000056 SystemDirIdx = 0;
57 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000058
Craig Topperd2d442c2014-05-17 23:10:59 +000059 ExternalLookup = nullptr;
60 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000061 NumIncluded = 0;
62 NumMultiIncludeFileOptzn = 0;
63 NumFrameworkLookups = NumSubFrameworkLookups = 0;
64}
65
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000066HeaderSearch::~HeaderSearch() {
67 // Delete headermaps.
68 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
69 delete HeaderMaps[i].second;
70}
Mike Stump11289f42009-09-09 15:08:12 +000071
Chris Lattner59a9ebd2006-10-18 05:34:33 +000072void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000073 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
74 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000075 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
76 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
77 NumOnceOnlyFiles += FileInfo[i].isImport;
78 if (MaxNumIncludes < FileInfo[i].NumIncludes)
79 MaxNumIncludes = FileInfo[i].NumIncludes;
80 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
81 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000082 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
83 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
84 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattner23b7eb62007-06-15 23:05:46 +000086 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
87 fprintf(stderr, " %d #includes skipped due to"
88 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000089
Chris Lattner23b7eb62007-06-15 23:05:46 +000090 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
91 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000092}
93
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000094/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +000095/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +000096const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000097 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +000098 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000099 if (!HeaderMaps.empty()) {
100 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000101 // Pointer equality comparison of FileEntries works because they are
102 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000103 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000104 return HeaderMaps[i].second;
105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattner5159f612010-11-23 08:35:12 +0000107 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000108 HeaderMaps.push_back(std::make_pair(FE, HM));
109 return HM;
110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Craig Topperd2d442c2014-05-17 23:10:59 +0000112 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000113}
114
Douglas Gregor279a6c32012-01-29 17:08:11 +0000115std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000116 const FileEntry *ModuleMap =
117 getModuleMap().getModuleMapFileForUniquing(Module);
118 return getModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000119}
120
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000121std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
122 StringRef ModuleMapPath) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000123 // If we don't have a module cache path, we can't do anything.
124 if (ModuleCachePath.empty())
125 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000126
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000127 SmallString<256> Result(ModuleCachePath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000128 llvm::sys::fs::make_absolute(Result);
129
130 if (HSOpts->DisableModuleHash) {
131 llvm::sys::path::append(Result, ModuleName + ".pcm");
132 } else {
133 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
134 // be globally unique to this particular module. To avoid false-negatives
135 // on case-insensitive filesystems, we use lower-case, which is safe because
136 // to cause a collision the modules must have the same name, which is an
137 // error if they are imported in the same translation.
138 SmallString<256> AbsModuleMapPath(ModuleMapPath);
139 llvm::sys::fs::make_absolute(AbsModuleMapPath);
140 llvm::APInt Code(64, llvm::hash_value(AbsModuleMapPath.str().lower()));
141 SmallString<128> HashStr;
142 Code.toStringUnsigned(HashStr, /*Radix*/36);
143 llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
144 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000145 return Result.str().str();
146}
147
148Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000149 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000150 Module *Module = ModMap.findModule(ModuleName);
Daniel Jasper21a0f552014-11-25 09:45:48 +0000151 if (Module || !AllowSearch || !LangOpts.ModulesImplicitMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000152 return Module;
153
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000154 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000155 // maps, searching for a module map that describes this module.
156 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
157 if (SearchDirs[Idx].isFramework()) {
158 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000159 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000160 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
161 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
162 if (const DirectoryEntry *FrameworkDir
163 = FileMgr.getDirectory(FrameworkDirName)) {
164 bool IsSystem
165 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
166 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000167 if (Module)
168 break;
169 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000170 }
171
172 // FIXME: Figure out how header maps and module maps will work together.
173
174 // Only deal with normal search directories.
175 if (!SearchDirs[Idx].isNormalDir())
176 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000177
178 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000179 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000180 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
181 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000182 // We just loaded a module map file; check whether the module is
183 // available now.
184 Module = ModMap.findModule(ModuleName);
185 if (Module)
186 break;
187 }
188
189 // Search for a module map in a subdirectory with the same name as the
190 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000191 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000192 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
193 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000194 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
195 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000196 // If we just loaded a module map file, look for the module again.
197 Module = ModMap.findModule(ModuleName);
198 if (Module)
199 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000200 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000201
202 // If we've already performed the exhaustive search for module maps in this
203 // search directory, don't do it again.
204 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
205 continue;
206
207 // Load all module maps in the immediate subdirectories of this search
208 // directory.
209 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
210
211 // Look again for the module.
212 Module = ModMap.findModule(ModuleName);
213 if (Module)
214 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000215 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000216
Douglas Gregor279a6c32012-01-29 17:08:11 +0000217 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000218}
219
Chris Lattnerf62f7582007-12-17 07:52:39 +0000220//===----------------------------------------------------------------------===//
221// File lookup within a DirectoryLookup scope
222//===----------------------------------------------------------------------===//
223
Chris Lattner8d720d02007-12-17 17:57:27 +0000224/// getName - Return the directory or filename corresponding to this lookup
225/// object.
226const char *DirectoryLookup::getName() const {
227 if (isNormalDir())
228 return getDir()->getName();
229 if (isFramework())
230 return getFrameworkDir()->getName();
231 assert(isHeaderMap() && "Unknown DirectoryLookup");
232 return getHeaderMap()->getFileName();
233}
234
Richard Smith8c71eba2014-03-05 20:51:45 +0000235static const FileEntry *
236getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
237 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
238 ModuleMap::KnownHeader *SuggestedModule) {
239 // If we have a module map that might map this header, load it and
240 // check whether we'll have a suggestion for a module.
241 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
242 if (SuggestedModule) {
243 const FileEntry *File = HS.getFileMgr().getFile(FileName,
244 /*OpenFile=*/false);
245 if (File) {
246 // If there is a module that corresponds to this header, suggest it.
247 *SuggestedModule = HS.findModuleForHeader(File);
248
249 // FIXME: This appears to be a no-op. We loaded the module map for this
250 // directory at the start of this function.
251 if (!SuggestedModule->getModule() &&
252 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
253 *SuggestedModule = HS.findModuleForHeader(File);
254 }
255
256 return File;
257 }
258
259 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
260}
Chris Lattner8d720d02007-12-17 17:57:27 +0000261
Chris Lattnerf62f7582007-12-17 07:52:39 +0000262/// LookupFile - Lookup the specified file in this search path, returning it
263/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000264const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000265 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000266 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000267 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000268 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000269 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000270 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000271 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000272 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000273 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000274 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000275
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000276 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000277 if (isNormalDir()) {
278 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000279 TmpDir = getDir()->getName();
280 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000281 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000283 SearchPath->clear();
284 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
285 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000286 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000287 RelativePath->clear();
288 RelativePath->append(Filename.begin(), Filename.end());
289 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000290
291 return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
292 isSystemHeaderDirectory(),
293 SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000294 }
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner712e3872007-12-17 08:13:48 +0000296 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000297 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000298 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000299
Chris Lattner44bd21b2007-12-17 08:17:39 +0000300 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000301 const HeaderMap *HM = getHeaderMap();
302 SmallString<1024> Path;
303 StringRef Dest = HM->lookupFilename(Filename, Path);
304 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000305 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000306
307 const FileEntry *Result;
308
309 // Check if the headermap maps the filename to a framework include
310 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
311 // framework include.
312 if (llvm::sys::path::is_relative(Dest)) {
313 MappedName.clear();
314 MappedName.append(Dest.begin(), Dest.end());
315 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000316 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000317 Result = HM->LookupFile(Filename, HS.getFileMgr());
318
319 } else {
320 Result = HS.getFileMgr().getFile(Dest);
321 }
322
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000323 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000324 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000326 SearchPath->clear();
327 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
328 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000329 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000330 RelativePath->clear();
331 RelativePath->append(Filename.begin(), Filename.end());
332 }
333 }
334 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000335}
336
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000337/// \brief Given a framework directory, find the top-most framework directory.
338///
339/// \param FileMgr The file manager to use for directory lookups.
340/// \param DirName The name of the framework directory.
341/// \param SubmodulePath Will be populated with the submodule path from the
342/// returned top-level module to the originally named framework.
343static const DirectoryEntry *
344getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
345 SmallVectorImpl<std::string> &SubmodulePath) {
346 assert(llvm::sys::path::extension(DirName) == ".framework" &&
347 "Not a framework directory");
348
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000349 // Note: as an egregious but useful hack we use the real path here, because
350 // frameworks moving between top-level frameworks to embedded frameworks tend
351 // to be symlinked, and we base the logical structure of modules on the
352 // physical layout. In particular, we need to deal with crazy includes like
353 //
354 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
355 //
356 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
357 // which one should access with, e.g.,
358 //
359 // #include <Bar/Wibble.h>
360 //
361 // Similar issues occur when a top-level framework has moved into an
362 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000363 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000364 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000365 do {
366 // Get the parent directory name.
367 DirName = llvm::sys::path::parent_path(DirName);
368 if (DirName.empty())
369 break;
370
371 // Determine whether this directory exists.
372 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
373 if (!Dir)
374 break;
375
376 // If this is a framework directory, then we're a subframework of this
377 // framework.
378 if (llvm::sys::path::extension(DirName) == ".framework") {
379 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
380 TopFrameworkDir = Dir;
381 }
382 } while (true);
383
384 return TopFrameworkDir;
385}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000386
Chris Lattner712e3872007-12-17 08:13:48 +0000387/// DoFrameworkLookup - Do a lookup of the specified file in the current
388/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000389const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000390 StringRef Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000391 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000392 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000393 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000394 ModuleMap::KnownHeader *SuggestedModule,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000395 bool &InUserSpecifiedSystemFramework) const
Douglas Gregor97eec242011-09-15 22:00:41 +0000396{
Chris Lattner712e3872007-12-17 08:13:48 +0000397 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000399 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000400 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000401 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattner712e3872007-12-17 08:13:48 +0000403 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000404 // HeaderSearch. Possible answers are yes/no and unknown.
405 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000406 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattner712e3872007-12-17 08:13:48 +0000408 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000409 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000410 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Chris Lattner712e3872007-12-17 08:13:48 +0000412 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000414 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000415 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000416 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000417 if (FrameworkName.empty() || FrameworkName.back() != '/')
418 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000420 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000421 StringRef ModuleName(Filename.begin(), SlashPos);
422 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000424 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
425 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000426
Daniel Dunbar17138612012-04-05 17:09:40 +0000427 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000428 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000429 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattner5ed76da2006-10-22 07:24:13 +0000431 // If the framework dir doesn't exist, we fail.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000432 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000433 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattner5ed76da2006-10-22 07:24:13 +0000435 // Otherwise, if it does, remember that this is the right direntry for this
436 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000437 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000438
439 // If this is a user search directory, check if the framework has been
440 // user-specified as a system framework.
441 if (getDirCharacteristic() == SrcMgr::C_User) {
442 SmallString<1024> SystemFrameworkMarker(FrameworkName);
443 SystemFrameworkMarker += ".system_framework";
444 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
445 CacheEntry.IsUserSpecifiedSystemFramework = true;
446 }
447 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000448 }
Mike Stump11289f42009-09-09 15:08:12 +0000449
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000450 // Set the 'user-specified system framework' flag.
451 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
452
Craig Topperd2d442c2014-05-17 23:10:59 +0000453 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000454 RelativePath->clear();
455 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
456 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000457
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000458 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000459 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000460
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000461 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000462
Craig Topperd2d442c2014-05-17 23:10:59 +0000463 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000464 SearchPath->clear();
465 // Without trailing '/'.
466 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
467 }
468
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000469 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000470 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
471 /*openFile=*/!SuggestedModule);
472 if (!FE) {
473 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
474 const char *Private = "Private";
475 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
476 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000477 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000478 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
479 Private+strlen(Private));
480
481 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000482 }
Mike Stump11289f42009-09-09 15:08:12 +0000483
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000484 // If we found the header and are allowed to suggest a module, do so now.
485 if (FE && SuggestedModule) {
486 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000487 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000488 bool FoundFramework = false;
489 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000490 // Determine whether this directory exists.
491 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
492 if (!Dir)
493 break;
494
495 // If this is a framework directory, then we're a subframework of this
496 // framework.
497 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
498 FoundFramework = true;
499 break;
500 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000501
502 // Get the parent directory name.
503 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
504 if (FrameworkPath.empty())
505 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000506 } while (true);
507
508 if (FoundFramework) {
509 // Find the top-level framework based on this framework.
510 SmallVector<std::string, 4> SubmodulePath;
511 const DirectoryEntry *TopFrameworkDir
512 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
513
514 // Determine the name of the top-level framework.
515 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
516
517 // Load this framework module. If that succeeds, find the suggested module
518 // for this header, if any.
519 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
520 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
521 *SuggestedModule = HS.findModuleForHeader(FE);
522 }
523 } else {
524 *SuggestedModule = HS.findModuleForHeader(FE);
525 }
526 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000527 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000528}
529
Douglas Gregor89929282012-01-30 06:01:29 +0000530void HeaderSearch::setTarget(const TargetInfo &Target) {
531 ModMap.setTarget(Target);
532}
533
Chris Lattnerf62f7582007-12-17 07:52:39 +0000534
Chris Lattner712e3872007-12-17 08:13:48 +0000535//===----------------------------------------------------------------------===//
536// Header File Location.
537//===----------------------------------------------------------------------===//
538
Reid Klecknera97d4c02014-02-18 23:49:24 +0000539/// \brief Return true with a diagnostic if the file that MSVC would have found
540/// fails to match the one that Clang would have found with MSVC header search
541/// disabled.
542static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
543 const FileEntry *MSFE, const FileEntry *FE,
544 SourceLocation IncludeLoc) {
545 if (MSFE && FE != MSFE) {
546 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
547 return true;
548 }
549 return false;
550}
Chris Lattner712e3872007-12-17 08:13:48 +0000551
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000552static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
553 assert(!Str.empty());
554 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
555 std::copy(Str.begin(), Str.end(), CopyStr);
556 CopyStr[Str.size()] = '\0';
557 return CopyStr;
558}
559
James Dennettc07ab2c2012-06-20 00:56:32 +0000560/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000561/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000562/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
563/// non-empty, indicates where the \#including file(s) are, in case a relative
564/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000565const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000566 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
567 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000568 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
569 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Will Wilson0fafd342013-12-27 19:46:16 +0000570 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
Daniel Jasper97da9172013-10-22 08:09:47 +0000571 if (!HSOpts->ModuleMapFiles.empty()) {
572 // Preload all explicitly specified module map files. This enables modules
573 // map files lying in a directory structure separate from the header files
574 // that they describe. These cannot be loaded lazily upon encountering a
Will Wilson9ef61a72013-12-19 16:24:17 +0000575 // header file, as there is no other known mapping from a header file to its
Daniel Jasper97da9172013-10-22 08:09:47 +0000576 // module map file.
Richard Smithd963ca62014-10-17 01:26:52 +0000577 for (const auto &Filename : HSOpts->ModuleMapFiles)
578 if (const FileEntry *File = FileMgr.getFile(Filename))
579 loadModuleMapFile(File, /*IsSystem=*/false);
Daniel Jasper97da9172013-10-22 08:09:47 +0000580 HSOpts->ModuleMapFiles.clear();
581 }
582
Douglas Gregor97eec242011-09-15 22:00:41 +0000583 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000584 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000585
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000586 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000587 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000588 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000589
590 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000591 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000592
Craig Topperd2d442c2014-05-17 23:10:59 +0000593 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000594 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000595 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000596 RelativePath->clear();
597 RelativePath->append(Filename.begin(), Filename.end());
598 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000599 // Otherwise, just return the file.
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000600 return FileMgr.getFile(Filename, /*openFile=*/true);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000601 }
Mike Stump11289f42009-09-09 15:08:12 +0000602
Reid Klecknera97d4c02014-02-18 23:49:24 +0000603 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000604 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000605 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000606
Douglas Gregor9f93e382011-07-28 04:45:53 +0000607 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000608 // directory. This cannot be based on CurDir, because each includer could be
609 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
610 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000611 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000612 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000613 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000614 bool First = true;
615 for (const auto &IncluderAndDir : Includers) {
616 const FileEntry *Includer = IncluderAndDir.first;
617
Will Wilson0fafd342013-12-27 19:46:16 +0000618 // Concatenate the requested file onto the directory.
619 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000620 TmpDir = IncluderAndDir.second->getName();
Will Wilson0fafd342013-12-27 19:46:16 +0000621 TmpDir.push_back('/');
622 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000623
Richard Smith6f548ec2014-03-06 18:08:08 +0000624 // FIXME: We don't cache the result of getFileInfo across the call to
625 // getFileAndSuggestModule, because it's a reference to an element of
626 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000627 //
628 // FIXME: If we have no includer, that means we're processing a #include
629 // from a module build. We should treat this as a system header if we're
630 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000631 bool IncluderIsSystemHeader =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000632 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000633 if (const FileEntry *FE = getFileAndSuggestModule(
634 *this, TmpDir.str(), IncluderAndDir.second,
635 IncluderIsSystemHeader, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000636 if (!Includer) {
637 assert(First && "only first includer can have no file");
638 return FE;
639 }
640
Will Wilson0fafd342013-12-27 19:46:16 +0000641 // Leave CurDir unset.
642 // This file is a system header or C++ unfriendly if the old file is.
643 //
644 // Note that we only use one of FromHFI/ToHFI at once, due to potential
645 // reallocation of the underlying vector potentially making the first
646 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000647 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000648 unsigned DirInfo = FromHFI.DirInfo;
649 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
650 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000651
Will Wilson0fafd342013-12-27 19:46:16 +0000652 HeaderFileInfo &ToHFI = getFileInfo(FE);
653 ToHFI.DirInfo = DirInfo;
654 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
655 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000656
Craig Topperd2d442c2014-05-17 23:10:59 +0000657 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000658 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000659 SearchPath->clear();
660 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
661 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000662 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000663 RelativePath->clear();
664 RelativePath->append(Filename.begin(), Filename.end());
665 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000666 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000667 return FE;
668
669 // Otherwise, we found the path via MSVC header search rules. If
670 // -Wmsvc-include is enabled, we have to keep searching to see if we
671 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000672 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000673 return FE;
674 } else {
675 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000676 if (SuggestedModule) {
677 MSSuggestedModule = *SuggestedModule;
678 *SuggestedModule = ModuleMap::KnownHeader();
679 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000680 break;
681 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000682 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000683 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000684 }
685 }
Mike Stump11289f42009-09-09 15:08:12 +0000686
Craig Topperd2d442c2014-05-17 23:10:59 +0000687 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000688
689 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000690 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000692 // If this is a #include_next request, start searching after the directory the
693 // file was found in.
694 if (FromDir)
695 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattnerd4275422007-07-22 07:28:00 +0000697 // Cache all of the lookups performed by this method. Many headers are
698 // multiply included, and the "pragma once" optimization prevents them from
699 // being relex/pp'd, but they would still have to search through a
700 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000701 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000702
703 // If the entry has been previously looked up, the first value will be
704 // non-zero. If the value is equal to i (the start point of our search), then
705 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000706 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000707 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000708 i = CacheLookup.HitIdx;
709 if (CacheLookup.MappedName)
710 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000711 } else {
712 // Otherwise, this is the first query, or the previous query didn't match
713 // our search start. We will fill in our found location below, so prime the
714 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000715 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000716 }
Mike Stump11289f42009-09-09 15:08:12 +0000717
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000718 SmallString<64> MappedName;
719
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000720 // Check each directory in sequence to see if it contains this file.
721 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000722 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000723 bool HasBeenMapped = false;
Mike Stump11289f42009-09-09 15:08:12 +0000724 const FileEntry *FE =
Douglas Gregor97eec242011-09-15 22:00:41 +0000725 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000726 SuggestedModule, InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000727 HasBeenMapped, MappedName);
728 if (HasBeenMapped) {
729 CacheLookup.MappedName =
730 copyString(Filename, LookupFileCache.getAllocator());
731 }
Chris Lattner712e3872007-12-17 08:13:48 +0000732 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000733
Chris Lattner712e3872007-12-17 08:13:48 +0000734 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner712e3872007-12-17 08:13:48 +0000736 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000737 HeaderFileInfo &HFI = getFileInfo(FE);
738 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000739
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000740 // If the directory characteristic is User but this framework was
741 // user-specified to be treated as a system framework, promote the
742 // characteristic.
743 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
744 HFI.DirInfo = SrcMgr::C_System;
745
Richard Smith8acadcb2012-06-13 20:27:03 +0000746 // If the filename matches a known system header prefix, override
747 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000748 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
749 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
750 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000751 : SrcMgr::C_User;
752 break;
753 }
754 }
755
Douglas Gregor9f93e382011-07-28 04:45:53 +0000756 // If this file is found in a header map and uses the framework style of
757 // includes, then this header is part of a framework we're building.
758 if (CurDir->isIndexHeaderMap()) {
759 size_t SlashPos = Filename.find('/');
760 if (SlashPos != StringRef::npos) {
761 HFI.IndexHeaderMapHeader = 1;
762 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
763 SlashPos));
764 }
765 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000766
Richard Smith8c71eba2014-03-05 20:51:45 +0000767 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
768 if (SuggestedModule)
769 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000770 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000771 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000772
Chris Lattner712e3872007-12-17 08:13:48 +0000773 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000774 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000775 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000776 }
Mike Stump11289f42009-09-09 15:08:12 +0000777
Douglas Gregord8575e12011-07-30 06:28:34 +0000778 // If we are including a file with a quoted include "foo.h" from inside
779 // a header in a framework that is currently being built, and we couldn't
780 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
781 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000782 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000783 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000784 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000785 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000786 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000787 ScratchFilename += IncludingHFI.Framework;
788 ScratchFilename += '/';
789 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000790
Reid Klecknera97d4c02014-02-18 23:49:24 +0000791 const FileEntry *FE = LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000792 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
793 Includers.front(), SearchPath, RelativePath, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000794
Richard Smith8c71eba2014-03-05 20:51:45 +0000795 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
796 if (SuggestedModule)
797 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000798 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000799 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000800
David Blaikie3c8c46e2014-11-19 05:48:40 +0000801 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000802 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000803 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000804 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000805 }
806 }
807
Craig Topperd2d442c2014-05-17 23:10:59 +0000808 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000809 if (SuggestedModule)
810 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000811 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000812 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000813
Chris Lattnerd4275422007-07-22 07:28:00 +0000814 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000815 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000816 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000817}
818
Chris Lattner63dd32b2006-10-20 04:42:40 +0000819/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000820/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000821/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
822/// is a subframework within Carbon.framework. If so, return the FileEntry
823/// for the designated file, otherwise return null.
824const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000825LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000826 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000827 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000828 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000829 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000830 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000831
Chris Lattner63dd32b2006-10-20 04:42:40 +0000832 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000833 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000834 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000835 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner63dd32b2006-10-20 04:42:40 +0000837 // Look up the base framework name of the ContextFileEnt.
Chris Lattner48043482006-10-27 05:12:36 +0000838 const char *ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattner63dd32b2006-10-20 04:42:40 +0000840 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000841 const unsigned DotFrameworkLen = 10;
842 const char *FrameworkPos = strstr(ContextName, ".framework");
Craig Topperd2d442c2014-05-17 23:10:59 +0000843 if (FrameworkPos == nullptr ||
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000844 (FrameworkPos[DotFrameworkLen] != '/' &&
845 FrameworkPos[DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000846 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000847
Daniel Dunbar17138612012-04-05 17:09:40 +0000848 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000849
Chris Lattner63dd32b2006-10-20 04:42:40 +0000850 // Append Frameworks/HIToolbox.framework/
851 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000852 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000853 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000854
David Blaikie13156b62014-11-19 03:06:06 +0000855 auto &CacheLookup =
856 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
857 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000858
Chris Lattner5ed76da2006-10-22 07:24:13 +0000859 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000860 if (CacheLookup.second.Directory &&
861 CacheLookup.first().size() == FrameworkName.size() &&
862 memcmp(CacheLookup.first().data(), &FrameworkName[0],
863 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000864 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000865
Chris Lattner5ed76da2006-10-22 07:24:13 +0000866 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000867 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000868 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattner5ed76da2006-10-22 07:24:13 +0000870 // If the framework dir doesn't exist, we fail.
Chris Lattner5159f612010-11-23 08:35:12 +0000871 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000872 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Chris Lattner5ed76da2006-10-22 07:24:13 +0000874 // Otherwise, if it does, remember that this is the right direntry for this
875 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000876 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000877 }
Mike Stump11289f42009-09-09 15:08:12 +0000878
Craig Topperd2d442c2014-05-17 23:10:59 +0000879 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000880
Craig Topperd2d442c2014-05-17 23:10:59 +0000881 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000882 RelativePath->clear();
883 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
884 }
885
Chris Lattner63dd32b2006-10-20 04:42:40 +0000886 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000887 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000888 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000889 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000890 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))) {
Mike Stump11289f42009-09-09 15:08:12 +0000897
Chris Lattner63dd32b2006-10-20 04:42:40 +0000898 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000899 HeadersFilename = FrameworkName;
900 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000901 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000902 SearchPath->clear();
903 // Without trailing '/'.
904 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
905 }
906
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000907 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000908 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000909 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000910 }
Mike Stump11289f42009-09-09 15:08:12 +0000911
Chris Lattner577377e2006-10-20 04:55:45 +0000912 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000913 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000914 // Note that the temporary 'DirInfo' is required here, as either call to
915 // getFileInfo could resize the vector and we don't want to rely on order
916 // of evaluation.
917 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
918 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000919
920 // If we're supposed to suggest a module, look for one now.
921 if (SuggestedModule) {
922 // Find the top-level framework based on this framework.
923 FrameworkName.pop_back(); // remove the trailing '/'
924 SmallVector<std::string, 4> SubmodulePath;
925 const DirectoryEntry *TopFrameworkDir
926 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
927
928 // Determine the name of the top-level framework.
929 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
930
931 // Load this framework module. If that succeeds, find the suggested module
932 // for this header, if any.
933 bool IsSystem = false;
934 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
935 *SuggestedModule = findModuleForHeader(FE);
936 }
937 }
938
Chris Lattner577377e2006-10-20 04:55:45 +0000939 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000940}
941
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000942//===----------------------------------------------------------------------===//
943// File Info Management.
944//===----------------------------------------------------------------------===//
945
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000946/// \brief Merge the header file info provided by \p OtherHFI into the current
947/// header file info (\p HFI)
948static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
949 const HeaderFileInfo &OtherHFI) {
950 HFI.isImport |= OtherHFI.isImport;
951 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000952 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000953 HFI.NumIncludes += OtherHFI.NumIncludes;
954
955 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
956 HFI.ControllingMacro = OtherHFI.ControllingMacro;
957 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
958 }
959
960 if (OtherHFI.External) {
961 HFI.DirInfo = OtherHFI.DirInfo;
962 HFI.External = OtherHFI.External;
963 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
964 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000965
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000966 if (HFI.Framework.empty())
967 HFI.Framework = OtherHFI.Framework;
968
969 HFI.Resolved = true;
970}
971
Steve Naroff3fa455a2009-04-24 20:03:17 +0000972/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000973/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000974HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000975 if (FE->getUID() >= FileInfo.size())
976 FileInfo.resize(FE->getUID()+1);
Douglas Gregor09b69892011-02-10 17:09:37 +0000977
978 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000979 if (ExternalSource && !HFI.Resolved)
980 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Ben Langmuird285c502014-03-13 16:46:36 +0000981 HFI.IsValid = 1;
Douglas Gregor09b69892011-02-10 17:09:37 +0000982 return HFI;
Mike Stump11289f42009-09-09 15:08:12 +0000983}
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000984
Ben Langmuird285c502014-03-13 16:46:36 +0000985bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
986 if (FE->getUID() >= FileInfo.size())
987 return false;
988 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
989 if (HFI.IsValid) {
990 Result = HFI;
991 return true;
992 }
993 return false;
994}
995
Douglas Gregor37aa4932011-05-04 00:14:37 +0000996bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
997 // Check if we've ever seen this file as a header.
998 if (File->getUID() >= FileInfo.size())
999 return false;
1000
1001 // Resolve header file info from the external source, if needed.
1002 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001003 if (ExternalSource && !HFI.Resolved)
1004 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregor37aa4932011-05-04 00:14:37 +00001005
Argyrios Kyrtzidis0d355df2012-12-10 20:08:37 +00001006 return HFI.isPragmaOnce || HFI.isImport ||
1007 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001008}
1009
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001010void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001011 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001012 bool isCompilingModuleHeader) {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001013 if (FE->getUID() >= FileInfo.size())
1014 FileInfo.resize(FE->getUID()+1);
1015
1016 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1017 HFI.isModuleHeader = true;
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001018 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001019 HFI.setHeaderRole(Role);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001020}
1021
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001022bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1023 ++NumIncluded; // Count # of attempted #includes.
1024
1025 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001026 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001027
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001028 // If this is a #import directive, check that we have not already imported
1029 // this header.
1030 if (isImport) {
1031 // If this has already been imported, don't import it again.
1032 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001034 // Has this already been #import'ed or #include'd?
1035 if (FileInfo.NumIncludes) return false;
1036 } else {
1037 // Otherwise, if this is a #include of a file that was previously #import'd
1038 // or if this is the second #include of a #pragma once file, ignore it.
1039 if (FileInfo.isImport)
1040 return false;
1041 }
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001043 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1044 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001045 if (const IdentifierInfo *ControllingMacro
Douglas Gregor99734e72009-04-25 23:30:02 +00001046 = FileInfo.getControllingMacro(ExternalLookup))
1047 if (ControllingMacro->hasMacroDefinition()) {
1048 ++NumMultiIncludeFileOptzn;
1049 return false;
1050 }
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001052 // Increment the number of times this file has been included.
1053 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001054
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001055 return true;
1056}
1057
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001058size_t HeaderSearch::getTotalMemory() const {
1059 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001060 + llvm::capacity_in_bytes(FileInfo)
1061 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001062 + LookupFileCache.getAllocator().getTotalMemory()
1063 + FrameworkMap.getAllocator().getTotalMemory();
1064}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001065
1066StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001067 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001068}
Douglas Gregor718292f2011-11-11 19:10:28 +00001069
1070bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001071 const DirectoryEntry *Root,
1072 bool IsSystem) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001073 if (!enabledModules() || !LangOpts.ModulesImplicitMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001074 return false;
1075
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001076 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001077
1078 StringRef DirName = FileName;
1079 do {
1080 // Get the parent directory name.
1081 DirName = llvm::sys::path::parent_path(DirName);
1082 if (DirName.empty())
1083 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001084
Douglas Gregor718292f2011-11-11 19:10:28 +00001085 // Determine whether this directory exists.
1086 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1087 if (!Dir)
1088 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001089
Ben Langmuir984e1df2014-03-19 20:23:34 +00001090 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001091 switch (loadModuleMapFile(Dir, IsSystem,
1092 llvm::sys::path::extension(Dir->getName()) ==
1093 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001094 case LMM_NewlyLoaded:
1095 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001096 // Success. All of the directories we stepped through inherit this module
1097 // map file.
1098 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1099 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1100 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001101
1102 case LMM_NoDirectory:
1103 case LMM_InvalidModuleMap:
1104 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001105 }
1106
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001107 // If we hit the top of our search, we're done.
1108 if (Dir == Root)
1109 return false;
1110
Douglas Gregor718292f2011-11-11 19:10:28 +00001111 // Keep track of all of the directories we checked, so we can mark them as
1112 // having module maps if we eventually do find a module map.
1113 FixUpDirectories.push_back(Dir);
1114 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001115}
1116
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001117ModuleMap::KnownHeader
1118HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001119 if (ExternalSource) {
1120 // Make sure the external source has handled header info about this file,
1121 // which includes whether the file is part of a module.
1122 (void)getFileInfo(File);
1123 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001124 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001125}
1126
Ben Langmuir984e1df2014-03-19 20:23:34 +00001127static const FileEntry *getPrivateModuleMap(StringRef ModuleMapPath,
1128 const DirectoryEntry *Directory,
1129 FileManager &FileMgr) {
1130 StringRef Filename = llvm::sys::path::filename(ModuleMapPath);
1131 SmallString<128> PrivateFilename(Directory->getName());
1132 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001133 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001134 else if (Filename == "module.modulemap")
1135 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1136 else
1137 return nullptr;
1138 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001139}
1140
Ben Langmuir984e1df2014-03-19 20:23:34 +00001141bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1142 switch (loadModuleMapFileImpl(File, IsSystem)) {
1143 case LMM_AlreadyLoaded:
1144 case LMM_NewlyLoaded:
1145 return false;
1146 case LMM_NoDirectory:
1147 case LMM_InvalidModuleMap:
1148 return true;
1149 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001150 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001151}
1152
1153HeaderSearch::LoadModuleMapResult
1154HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem) {
1155 assert(File && "expected FileEntry");
1156
Richard Smith9887d792014-10-17 01:42:53 +00001157 // Check whether we've already loaded this module map, and mark it as being
1158 // loaded in case we recursively try to load it from itself.
1159 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1160 if (!AddResult.second)
1161 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001162
1163 if (ModMap.parseModuleMapFile(File, IsSystem)) {
Richard Smith9887d792014-10-17 01:42:53 +00001164 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001165 return LMM_InvalidModuleMap;
1166 }
1167
1168 // Try to load a corresponding private module map.
1169 if (const FileEntry *PMMFile =
Richard Smith9887d792014-10-17 01:42:53 +00001170 getPrivateModuleMap(File->getName(), File->getDir(), FileMgr)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001171 if (ModMap.parseModuleMapFile(PMMFile, IsSystem)) {
Richard Smith9887d792014-10-17 01:42:53 +00001172 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001173 return LMM_InvalidModuleMap;
1174 }
1175 }
1176
1177 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001178 return LMM_NewlyLoaded;
1179}
1180
1181const FileEntry *
1182HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001183 if (!LangOpts.ModulesImplicitMaps)
1184 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001185 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1186 // module.map at the framework root is also accepted.
1187 SmallString<128> ModuleMapFileName(Dir->getName());
1188 if (IsFramework)
1189 llvm::sys::path::append(ModuleMapFileName, "Modules");
1190 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1191 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1192 return F;
1193
1194 // Continue to allow module.map
1195 ModuleMapFileName = Dir->getName();
1196 llvm::sys::path::append(ModuleMapFileName, "module.map");
1197 return FileMgr.getFile(ModuleMapFileName);
1198}
1199
1200Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001201 const DirectoryEntry *Dir,
1202 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001203 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001204 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001205
Douglas Gregor56c64012011-11-17 01:41:17 +00001206 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001207 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001208 case LMM_InvalidModuleMap:
1209 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001210
Douglas Gregor56c64012011-11-17 01:41:17 +00001211 case LMM_AlreadyLoaded:
1212 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001213 return nullptr;
1214
Douglas Gregor56c64012011-11-17 01:41:17 +00001215 case LMM_NewlyLoaded:
1216 return ModMap.findModule(Name);
1217 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001218
Douglas Gregor9194a912012-11-06 19:39:40 +00001219
Ben Langmuirc3ea5652014-03-20 18:27:26 +00001220 // Try to infer a module map from the framework directory.
Daniel Jasper21a0f552014-11-25 09:45:48 +00001221 if (LangOpts.ModulesImplicitMaps)
1222 return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
1223
1224 return nullptr;
Douglas Gregor56c64012011-11-17 01:41:17 +00001225}
1226
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001227
Douglas Gregor80b69042011-11-12 00:22:19 +00001228HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001229HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1230 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001231 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001232 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001233
Douglas Gregor80b69042011-11-12 00:22:19 +00001234 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001235}
1236
Douglas Gregor80b69042011-11-12 00:22:19 +00001237HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001238HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1239 bool IsFramework) {
1240 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001241 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001242 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001243
Ben Langmuir984e1df2014-03-19 20:23:34 +00001244 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1245 LoadModuleMapResult Result = loadModuleMapFileImpl(ModuleMapFile, IsSystem);
1246 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1247 // E.g. Foo.framework/Modules/module.modulemap
1248 // ^Dir ^ModuleMapFile
1249 if (Result == LMM_NewlyLoaded)
1250 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001251 else if (Result == LMM_InvalidModuleMap)
1252 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001253 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001254 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001255 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001256}
Douglas Gregor718292f2011-11-11 19:10:28 +00001257
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001258void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001259 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001260
1261 if (LangOpts.ModulesImplicitMaps) {
1262 // Load module maps for each of the header search directories.
1263 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1264 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1265 if (SearchDirs[Idx].isFramework()) {
1266 std::error_code EC;
1267 SmallString<128> DirNative;
1268 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1269 DirNative);
1270
1271 // Search each of the ".framework" directories to load them as modules.
1272 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1273 Dir != DirEnd && !EC; Dir.increment(EC)) {
1274 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1275 continue;
1276
1277 const DirectoryEntry *FrameworkDir =
1278 FileMgr.getDirectory(Dir->path());
1279 if (!FrameworkDir)
1280 continue;
1281
1282 // Load this framework module.
1283 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1284 IsSystem);
1285 }
1286 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001287 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001288
1289 // FIXME: Deal with header maps.
1290 if (SearchDirs[Idx].isHeaderMap())
1291 continue;
1292
1293 // Try to load a module map file for the search directory.
1294 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1295 /*IsFramework*/ false);
1296
1297 // Try to load module map files for immediate subdirectories of this
1298 // search directory.
1299 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001300 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001301 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001302
Douglas Gregor07f43572012-01-29 18:15:03 +00001303 // Populate the list of modules.
1304 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1305 MEnd = ModMap.module_end();
1306 M != MEnd; ++M) {
1307 Modules.push_back(M->getValue());
1308 }
1309}
Douglas Gregor0339a642013-03-21 01:08:50 +00001310
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001311void HeaderSearch::loadTopLevelSystemModules() {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001312 if (!LangOpts.ModulesImplicitMaps)
1313 return;
1314
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001315 // Load module maps for each of the header search directories.
1316 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001317 // We only care about normal header directories.
1318 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001319 continue;
1320 }
1321
1322 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001323 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001324 SearchDirs[Idx].isSystemHeaderDirectory(),
1325 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001326 }
1327}
1328
Douglas Gregor0339a642013-03-21 01:08:50 +00001329void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001330 assert(LangOpts.ModulesImplicitMaps &&
1331 "Should not be loading subdirectory module maps");
1332
Douglas Gregor0339a642013-03-21 01:08:50 +00001333 if (SearchDir.haveSearchedAllModuleMaps())
1334 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001335
1336 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001337 SmallString<128> DirNative;
1338 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1339 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1340 Dir != DirEnd && !EC; Dir.increment(EC)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001341 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1342 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001343 }
1344
1345 SearchDir.setSearchedAllModuleMaps(true);
1346}