blob: f76d851ac6c9575575e6d0c3cdd22054a8a1d3a5 [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);
Ben Langmuir18dd78a2015-02-12 21:51:31 +0000118 return getModuleFileName(Module->Name, ModuleMap->getName(),
119 Module->IsSystem);
Douglas Gregor279a6c32012-01-29 17:08:11 +0000120}
121
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000122std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
Ben Langmuir18dd78a2015-02-12 21:51:31 +0000123 StringRef ModuleMapPath,
124 bool IsSystem) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000125 // If we don't have a module cache path, we can't do anything.
126 if (ModuleCachePath.empty())
127 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000128
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000129 SmallString<256> Result(ModuleCachePath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000130 llvm::sys::fs::make_absolute(Result);
131
132 if (HSOpts->DisableModuleHash) {
133 llvm::sys::path::append(Result, ModuleName + ".pcm");
134 } else {
135 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000136 // ideally be globally unique to this particular module. Name collisions
137 // in the hash are safe (because any translation unit can only import one
138 // module with each name), but result in a loss of caching.
139 //
140 // To avoid false-negatives, we form as canonical a path as we can, and map
141 // to lower-case in case we're on a case-insensitive file system.
142 auto *Dir =
143 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
144 if (!Dir)
145 return std::string();
146 auto DirName = FileMgr.getCanonicalName(Dir);
147 auto FileName = llvm::sys::path::filename(ModuleMapPath);
148
149 llvm::hash_code Hash =
150 llvm::hash_combine(DirName.lower(), FileName.lower());
151
Ben Langmuir18dd78a2015-02-12 21:51:31 +0000152 // Hash the IsSystem bit, since changing search paths can change whether a
153 // module is considered 'system' or not.
154 Hash = llvm::hash_combine(Hash, IsSystem);
155
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000156 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000157 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000158 llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
159 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000160 return Result.str().str();
161}
162
163Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000164 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000165 Module *Module = ModMap.findModule(ModuleName);
Daniel Jasper21a0f552014-11-25 09:45:48 +0000166 if (Module || !AllowSearch || !LangOpts.ModulesImplicitMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000167 return Module;
168
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000169 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000170 // maps, searching for a module map that describes this module.
171 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
172 if (SearchDirs[Idx].isFramework()) {
173 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000174 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000175 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
176 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
177 if (const DirectoryEntry *FrameworkDir
178 = FileMgr.getDirectory(FrameworkDirName)) {
179 bool IsSystem
180 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
181 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000182 if (Module)
183 break;
184 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000185 }
186
187 // FIXME: Figure out how header maps and module maps will work together.
188
189 // Only deal with normal search directories.
190 if (!SearchDirs[Idx].isNormalDir())
191 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000192
193 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000194 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000195 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
196 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000197 // We just loaded a module map file; check whether the module is
198 // available now.
199 Module = ModMap.findModule(ModuleName);
200 if (Module)
201 break;
202 }
203
204 // Search for a module map in a subdirectory with the same name as the
205 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000206 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000207 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
208 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000209 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
210 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000211 // If we just loaded a module map file, look for the module again.
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
217 // If we've already performed the exhaustive search for module maps in this
218 // search directory, don't do it again.
219 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
220 continue;
221
222 // Load all module maps in the immediate subdirectories of this search
223 // directory.
224 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
225
226 // Look again for the module.
227 Module = ModMap.findModule(ModuleName);
228 if (Module)
229 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000230 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000231
Douglas Gregor279a6c32012-01-29 17:08:11 +0000232 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000233}
234
Chris Lattnerf62f7582007-12-17 07:52:39 +0000235//===----------------------------------------------------------------------===//
236// File lookup within a DirectoryLookup scope
237//===----------------------------------------------------------------------===//
238
Chris Lattner8d720d02007-12-17 17:57:27 +0000239/// getName - Return the directory or filename corresponding to this lookup
240/// object.
241const char *DirectoryLookup::getName() const {
242 if (isNormalDir())
243 return getDir()->getName();
244 if (isFramework())
245 return getFrameworkDir()->getName();
246 assert(isHeaderMap() && "Unknown DirectoryLookup");
247 return getHeaderMap()->getFileName();
248}
249
Richard Smith8c71eba2014-03-05 20:51:45 +0000250static const FileEntry *
251getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
252 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
253 ModuleMap::KnownHeader *SuggestedModule) {
254 // If we have a module map that might map this header, load it and
255 // check whether we'll have a suggestion for a module.
256 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
257 if (SuggestedModule) {
258 const FileEntry *File = HS.getFileMgr().getFile(FileName,
259 /*OpenFile=*/false);
260 if (File) {
261 // If there is a module that corresponds to this header, suggest it.
262 *SuggestedModule = HS.findModuleForHeader(File);
263
264 // FIXME: This appears to be a no-op. We loaded the module map for this
265 // directory at the start of this function.
266 if (!SuggestedModule->getModule() &&
267 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
268 *SuggestedModule = HS.findModuleForHeader(File);
269 }
270
271 return File;
272 }
273
274 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
275}
Chris Lattner8d720d02007-12-17 17:57:27 +0000276
Chris Lattnerf62f7582007-12-17 07:52:39 +0000277/// LookupFile - Lookup the specified file in this search path, returning it
278/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000279const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000280 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000281 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000283 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000284 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000285 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000286 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000287 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000288 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000289 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000290
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000291 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000292 if (isNormalDir()) {
293 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000294 TmpDir = getDir()->getName();
295 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000296 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000297 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000298 SearchPath->clear();
299 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
300 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000301 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000302 RelativePath->clear();
303 RelativePath->append(Filename.begin(), Filename.end());
304 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000305
306 return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
307 isSystemHeaderDirectory(),
308 SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000309 }
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattner712e3872007-12-17 08:13:48 +0000311 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000312 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000313 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000314
Chris Lattner44bd21b2007-12-17 08:17:39 +0000315 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000316 const HeaderMap *HM = getHeaderMap();
317 SmallString<1024> Path;
318 StringRef Dest = HM->lookupFilename(Filename, Path);
319 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000320 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000321
322 const FileEntry *Result;
323
324 // Check if the headermap maps the filename to a framework include
325 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
326 // framework include.
327 if (llvm::sys::path::is_relative(Dest)) {
328 MappedName.clear();
329 MappedName.append(Dest.begin(), Dest.end());
330 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000331 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000332 Result = HM->LookupFile(Filename, HS.getFileMgr());
333
334 } else {
335 Result = HS.getFileMgr().getFile(Dest);
336 }
337
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000338 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000339 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000341 SearchPath->clear();
342 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
343 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000344 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000345 RelativePath->clear();
346 RelativePath->append(Filename.begin(), Filename.end());
347 }
348 }
349 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000350}
351
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000352/// \brief Given a framework directory, find the top-most framework directory.
353///
354/// \param FileMgr The file manager to use for directory lookups.
355/// \param DirName The name of the framework directory.
356/// \param SubmodulePath Will be populated with the submodule path from the
357/// returned top-level module to the originally named framework.
358static const DirectoryEntry *
359getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
360 SmallVectorImpl<std::string> &SubmodulePath) {
361 assert(llvm::sys::path::extension(DirName) == ".framework" &&
362 "Not a framework directory");
363
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000364 // Note: as an egregious but useful hack we use the real path here, because
365 // frameworks moving between top-level frameworks to embedded frameworks tend
366 // to be symlinked, and we base the logical structure of modules on the
367 // physical layout. In particular, we need to deal with crazy includes like
368 //
369 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
370 //
371 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
372 // which one should access with, e.g.,
373 //
374 // #include <Bar/Wibble.h>
375 //
376 // Similar issues occur when a top-level framework has moved into an
377 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000378 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000379 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000380 do {
381 // Get the parent directory name.
382 DirName = llvm::sys::path::parent_path(DirName);
383 if (DirName.empty())
384 break;
385
386 // Determine whether this directory exists.
387 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
388 if (!Dir)
389 break;
390
391 // If this is a framework directory, then we're a subframework of this
392 // framework.
393 if (llvm::sys::path::extension(DirName) == ".framework") {
394 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
395 TopFrameworkDir = Dir;
396 }
397 } while (true);
398
399 return TopFrameworkDir;
400}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000401
Chris Lattner712e3872007-12-17 08:13:48 +0000402/// DoFrameworkLookup - Do a lookup of the specified file in the current
403/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000404const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000405 StringRef Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000406 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000407 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000408 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000409 ModuleMap::KnownHeader *SuggestedModule,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000410 bool &InUserSpecifiedSystemFramework) const
Douglas Gregor97eec242011-09-15 22:00:41 +0000411{
Chris Lattner712e3872007-12-17 08:13:48 +0000412 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000414 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000415 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000416 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattner712e3872007-12-17 08:13:48 +0000418 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000419 // HeaderSearch. Possible answers are yes/no and unknown.
420 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000421 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattner712e3872007-12-17 08:13:48 +0000423 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000424 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000425 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattner712e3872007-12-17 08:13:48 +0000427 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000429 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000430 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000431 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000432 if (FrameworkName.empty() || FrameworkName.back() != '/')
433 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000435 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000436 StringRef ModuleName(Filename.begin(), SlashPos);
437 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000439 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
440 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000441
Daniel Dunbar17138612012-04-05 17:09:40 +0000442 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000443 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000444 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000445
Chris Lattner5ed76da2006-10-22 07:24:13 +0000446 // If the framework dir doesn't exist, we fail.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000447 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000448 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000449
Chris Lattner5ed76da2006-10-22 07:24:13 +0000450 // Otherwise, if it does, remember that this is the right direntry for this
451 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000452 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000453
454 // If this is a user search directory, check if the framework has been
455 // user-specified as a system framework.
456 if (getDirCharacteristic() == SrcMgr::C_User) {
457 SmallString<1024> SystemFrameworkMarker(FrameworkName);
458 SystemFrameworkMarker += ".system_framework";
459 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
460 CacheEntry.IsUserSpecifiedSystemFramework = true;
461 }
462 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000465 // Set the 'user-specified system framework' flag.
466 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
467
Craig Topperd2d442c2014-05-17 23:10:59 +0000468 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000469 RelativePath->clear();
470 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
471 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000472
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000473 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000474 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000476 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000477
Craig Topperd2d442c2014-05-17 23:10:59 +0000478 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000479 SearchPath->clear();
480 // Without trailing '/'.
481 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
482 }
483
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000484 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000485 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
486 /*openFile=*/!SuggestedModule);
487 if (!FE) {
488 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
489 const char *Private = "Private";
490 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
491 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000492 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000493 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
494 Private+strlen(Private));
495
496 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000499 // If we found the header and are allowed to suggest a module, do so now.
500 if (FE && SuggestedModule) {
501 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000502 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000503 bool FoundFramework = false;
504 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000505 // Determine whether this directory exists.
506 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
507 if (!Dir)
508 break;
509
510 // If this is a framework directory, then we're a subframework of this
511 // framework.
512 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
513 FoundFramework = true;
514 break;
515 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000516
517 // Get the parent directory name.
518 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
519 if (FrameworkPath.empty())
520 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000521 } while (true);
522
523 if (FoundFramework) {
524 // Find the top-level framework based on this framework.
525 SmallVector<std::string, 4> SubmodulePath;
526 const DirectoryEntry *TopFrameworkDir
527 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
528
529 // Determine the name of the top-level framework.
530 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
531
532 // Load this framework module. If that succeeds, find the suggested module
533 // for this header, if any.
534 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
535 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
536 *SuggestedModule = HS.findModuleForHeader(FE);
537 }
538 } else {
539 *SuggestedModule = HS.findModuleForHeader(FE);
540 }
541 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000542 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000543}
544
Douglas Gregor89929282012-01-30 06:01:29 +0000545void HeaderSearch::setTarget(const TargetInfo &Target) {
546 ModMap.setTarget(Target);
547}
548
Chris Lattnerf62f7582007-12-17 07:52:39 +0000549
Chris Lattner712e3872007-12-17 08:13:48 +0000550//===----------------------------------------------------------------------===//
551// Header File Location.
552//===----------------------------------------------------------------------===//
553
Reid Klecknera97d4c02014-02-18 23:49:24 +0000554/// \brief Return true with a diagnostic if the file that MSVC would have found
555/// fails to match the one that Clang would have found with MSVC header search
556/// disabled.
557static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
558 const FileEntry *MSFE, const FileEntry *FE,
559 SourceLocation IncludeLoc) {
560 if (MSFE && FE != MSFE) {
561 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
562 return true;
563 }
564 return false;
565}
Chris Lattner712e3872007-12-17 08:13:48 +0000566
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000567static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
568 assert(!Str.empty());
569 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
570 std::copy(Str.begin(), Str.end(), CopyStr);
571 CopyStr[Str.size()] = '\0';
572 return CopyStr;
573}
574
James Dennettc07ab2c2012-06-20 00:56:32 +0000575/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000576/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000577/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
578/// non-empty, indicates where the \#including file(s) are, in case a relative
579/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000580const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000581 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
582 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000583 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
584 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Will Wilson0fafd342013-12-27 19:46:16 +0000585 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
Douglas Gregor97eec242011-09-15 22:00:41 +0000586 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000587 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000588
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000589 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000590 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000591 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000592
593 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000594 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000595
Craig Topperd2d442c2014-05-17 23:10:59 +0000596 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000597 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000598 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000599 RelativePath->clear();
600 RelativePath->append(Filename.begin(), Filename.end());
601 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000602 // Otherwise, just return the file.
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000603 return FileMgr.getFile(Filename, /*openFile=*/true);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000604 }
Mike Stump11289f42009-09-09 15:08:12 +0000605
Reid Klecknera97d4c02014-02-18 23:49:24 +0000606 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000607 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000608 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000609
Douglas Gregor9f93e382011-07-28 04:45:53 +0000610 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000611 // directory. This cannot be based on CurDir, because each includer could be
612 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
613 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000614 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000615 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000616 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000617 bool First = true;
618 for (const auto &IncluderAndDir : Includers) {
619 const FileEntry *Includer = IncluderAndDir.first;
620
Will Wilson0fafd342013-12-27 19:46:16 +0000621 // Concatenate the requested file onto the directory.
622 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000623 TmpDir = IncluderAndDir.second->getName();
Will Wilson0fafd342013-12-27 19:46:16 +0000624 TmpDir.push_back('/');
625 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000626
Richard Smith6f548ec2014-03-06 18:08:08 +0000627 // FIXME: We don't cache the result of getFileInfo across the call to
628 // getFileAndSuggestModule, because it's a reference to an element of
629 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000630 //
631 // FIXME: If we have no includer, that means we're processing a #include
632 // from a module build. We should treat this as a system header if we're
633 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000634 bool IncluderIsSystemHeader =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000635 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000636 if (const FileEntry *FE = getFileAndSuggestModule(
637 *this, TmpDir.str(), IncluderAndDir.second,
638 IncluderIsSystemHeader, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000639 if (!Includer) {
640 assert(First && "only first includer can have no file");
641 return FE;
642 }
643
Will Wilson0fafd342013-12-27 19:46:16 +0000644 // Leave CurDir unset.
645 // This file is a system header or C++ unfriendly if the old file is.
646 //
647 // Note that we only use one of FromHFI/ToHFI at once, due to potential
648 // reallocation of the underlying vector potentially making the first
649 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000650 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000651 unsigned DirInfo = FromHFI.DirInfo;
652 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
653 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000654
Will Wilson0fafd342013-12-27 19:46:16 +0000655 HeaderFileInfo &ToHFI = getFileInfo(FE);
656 ToHFI.DirInfo = DirInfo;
657 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
658 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000659
Craig Topperd2d442c2014-05-17 23:10:59 +0000660 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000661 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000662 SearchPath->clear();
663 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
664 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000665 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000666 RelativePath->clear();
667 RelativePath->append(Filename.begin(), Filename.end());
668 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000669 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000670 return FE;
671
672 // Otherwise, we found the path via MSVC header search rules. If
673 // -Wmsvc-include is enabled, we have to keep searching to see if we
674 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000675 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000676 return FE;
677 } else {
678 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000679 if (SuggestedModule) {
680 MSSuggestedModule = *SuggestedModule;
681 *SuggestedModule = ModuleMap::KnownHeader();
682 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000683 break;
684 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000685 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000686 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000687 }
688 }
Mike Stump11289f42009-09-09 15:08:12 +0000689
Craig Topperd2d442c2014-05-17 23:10:59 +0000690 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000691
692 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000693 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000695 // If this is a #include_next request, start searching after the directory the
696 // file was found in.
697 if (FromDir)
698 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattnerd4275422007-07-22 07:28:00 +0000700 // Cache all of the lookups performed by this method. Many headers are
701 // multiply included, and the "pragma once" optimization prevents them from
702 // being relex/pp'd, but they would still have to search through a
703 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000704 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000705
706 // If the entry has been previously looked up, the first value will be
707 // non-zero. If the value is equal to i (the start point of our search), then
708 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000709 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000710 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000711 i = CacheLookup.HitIdx;
712 if (CacheLookup.MappedName)
713 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000714 } else {
715 // Otherwise, this is the first query, or the previous query didn't match
716 // our search start. We will fill in our found location below, so prime the
717 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000718 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000719 }
Mike Stump11289f42009-09-09 15:08:12 +0000720
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000721 SmallString<64> MappedName;
722
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000723 // Check each directory in sequence to see if it contains this file.
724 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000725 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000726 bool HasBeenMapped = false;
Mike Stump11289f42009-09-09 15:08:12 +0000727 const FileEntry *FE =
Douglas Gregor97eec242011-09-15 22:00:41 +0000728 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000729 SuggestedModule, InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000730 HasBeenMapped, MappedName);
731 if (HasBeenMapped) {
732 CacheLookup.MappedName =
733 copyString(Filename, LookupFileCache.getAllocator());
734 }
Chris Lattner712e3872007-12-17 08:13:48 +0000735 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chris Lattner712e3872007-12-17 08:13:48 +0000737 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000738
Chris Lattner712e3872007-12-17 08:13:48 +0000739 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000740 HeaderFileInfo &HFI = getFileInfo(FE);
741 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000742
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000743 // If the directory characteristic is User but this framework was
744 // user-specified to be treated as a system framework, promote the
745 // characteristic.
746 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
747 HFI.DirInfo = SrcMgr::C_System;
748
Richard Smith8acadcb2012-06-13 20:27:03 +0000749 // If the filename matches a known system header prefix, override
750 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000751 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
752 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
753 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000754 : SrcMgr::C_User;
755 break;
756 }
757 }
758
Douglas Gregor9f93e382011-07-28 04:45:53 +0000759 // If this file is found in a header map and uses the framework style of
760 // includes, then this header is part of a framework we're building.
761 if (CurDir->isIndexHeaderMap()) {
762 size_t SlashPos = Filename.find('/');
763 if (SlashPos != StringRef::npos) {
764 HFI.IndexHeaderMapHeader = 1;
765 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
766 SlashPos));
767 }
768 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000769
Richard Smith8c71eba2014-03-05 20:51:45 +0000770 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
771 if (SuggestedModule)
772 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000773 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000774 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000775
Chris Lattner712e3872007-12-17 08:13:48 +0000776 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000777 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000778 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
Douglas Gregord8575e12011-07-30 06:28:34 +0000781 // If we are including a file with a quoted include "foo.h" from inside
782 // a header in a framework that is currently being built, and we couldn't
783 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
784 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000785 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000786 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000787 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000788 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000789 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000790 ScratchFilename += IncludingHFI.Framework;
791 ScratchFilename += '/';
792 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000793
Reid Klecknera97d4c02014-02-18 23:49:24 +0000794 const FileEntry *FE = LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000795 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
796 Includers.front(), SearchPath, RelativePath, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000797
Richard Smith8c71eba2014-03-05 20:51:45 +0000798 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
799 if (SuggestedModule)
800 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000801 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000802 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000803
David Blaikie3c8c46e2014-11-19 05:48:40 +0000804 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000805 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000806 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000807 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000808 }
809 }
810
Craig Topperd2d442c2014-05-17 23:10:59 +0000811 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000812 if (SuggestedModule)
813 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000814 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000815 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000816
Chris Lattnerd4275422007-07-22 07:28:00 +0000817 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000818 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000819 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000820}
821
Chris Lattner63dd32b2006-10-20 04:42:40 +0000822/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000823/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000824/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
825/// is a subframework within Carbon.framework. If so, return the FileEntry
826/// for the designated file, otherwise return null.
827const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000828LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000829 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000830 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000831 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000832 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000833 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000834
Chris Lattner63dd32b2006-10-20 04:42:40 +0000835 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000836 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000837 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000838 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattner63dd32b2006-10-20 04:42:40 +0000840 // Look up the base framework name of the ContextFileEnt.
Chris Lattner48043482006-10-27 05:12:36 +0000841 const char *ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chris Lattner63dd32b2006-10-20 04:42:40 +0000843 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000844 const unsigned DotFrameworkLen = 10;
845 const char *FrameworkPos = strstr(ContextName, ".framework");
Craig Topperd2d442c2014-05-17 23:10:59 +0000846 if (FrameworkPos == nullptr ||
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000847 (FrameworkPos[DotFrameworkLen] != '/' &&
848 FrameworkPos[DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000849 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000850
Daniel Dunbar17138612012-04-05 17:09:40 +0000851 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000852
Chris Lattner63dd32b2006-10-20 04:42:40 +0000853 // Append Frameworks/HIToolbox.framework/
854 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000855 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000856 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000857
David Blaikie13156b62014-11-19 03:06:06 +0000858 auto &CacheLookup =
859 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
860 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000861
Chris Lattner5ed76da2006-10-22 07:24:13 +0000862 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000863 if (CacheLookup.second.Directory &&
864 CacheLookup.first().size() == FrameworkName.size() &&
865 memcmp(CacheLookup.first().data(), &FrameworkName[0],
866 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000867 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Chris Lattner5ed76da2006-10-22 07:24:13 +0000869 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000870 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000871 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattner5ed76da2006-10-22 07:24:13 +0000873 // If the framework dir doesn't exist, we fail.
Chris Lattner5159f612010-11-23 08:35:12 +0000874 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000875 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000876
Chris Lattner5ed76da2006-10-22 07:24:13 +0000877 // Otherwise, if it does, remember that this is the right direntry for this
878 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000879 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000880 }
Mike Stump11289f42009-09-09 15:08:12 +0000881
Craig Topperd2d442c2014-05-17 23:10:59 +0000882 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000883
Craig Topperd2d442c2014-05-17 23:10:59 +0000884 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000885 RelativePath->clear();
886 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
887 }
888
Chris Lattner63dd32b2006-10-20 04:42:40 +0000889 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000890 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000891 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000892 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000893 SearchPath->clear();
894 // Without trailing '/'.
895 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
896 }
897
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000898 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000899 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattner63dd32b2006-10-20 04:42:40 +0000901 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000902 HeadersFilename = FrameworkName;
903 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000904 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000905 SearchPath->clear();
906 // Without trailing '/'.
907 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
908 }
909
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000910 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000911 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000912 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000913 }
Mike Stump11289f42009-09-09 15:08:12 +0000914
Chris Lattner577377e2006-10-20 04:55:45 +0000915 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000916 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000917 // Note that the temporary 'DirInfo' is required here, as either call to
918 // getFileInfo could resize the vector and we don't want to rely on order
919 // of evaluation.
920 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
921 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000922
923 // If we're supposed to suggest a module, look for one now.
924 if (SuggestedModule) {
925 // Find the top-level framework based on this framework.
926 FrameworkName.pop_back(); // remove the trailing '/'
927 SmallVector<std::string, 4> SubmodulePath;
928 const DirectoryEntry *TopFrameworkDir
929 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
930
931 // Determine the name of the top-level framework.
932 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
933
934 // Load this framework module. If that succeeds, find the suggested module
935 // for this header, if any.
936 bool IsSystem = false;
937 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
938 *SuggestedModule = findModuleForHeader(FE);
939 }
940 }
941
Chris Lattner577377e2006-10-20 04:55:45 +0000942 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000943}
944
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000945//===----------------------------------------------------------------------===//
946// File Info Management.
947//===----------------------------------------------------------------------===//
948
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000949/// \brief Merge the header file info provided by \p OtherHFI into the current
950/// header file info (\p HFI)
951static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
952 const HeaderFileInfo &OtherHFI) {
953 HFI.isImport |= OtherHFI.isImport;
954 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000955 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000956 HFI.NumIncludes += OtherHFI.NumIncludes;
957
958 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
959 HFI.ControllingMacro = OtherHFI.ControllingMacro;
960 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
961 }
962
963 if (OtherHFI.External) {
964 HFI.DirInfo = OtherHFI.DirInfo;
965 HFI.External = OtherHFI.External;
966 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
967 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000968
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000969 if (HFI.Framework.empty())
970 HFI.Framework = OtherHFI.Framework;
971
972 HFI.Resolved = true;
973}
974
Steve Naroff3fa455a2009-04-24 20:03:17 +0000975/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000976/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000977HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000978 if (FE->getUID() >= FileInfo.size())
979 FileInfo.resize(FE->getUID()+1);
Douglas Gregor09b69892011-02-10 17:09:37 +0000980
981 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000982 if (ExternalSource && !HFI.Resolved)
983 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Ben Langmuird285c502014-03-13 16:46:36 +0000984 HFI.IsValid = 1;
Douglas Gregor09b69892011-02-10 17:09:37 +0000985 return HFI;
Mike Stump11289f42009-09-09 15:08:12 +0000986}
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000987
Ben Langmuird285c502014-03-13 16:46:36 +0000988bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
989 if (FE->getUID() >= FileInfo.size())
990 return false;
991 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
992 if (HFI.IsValid) {
993 Result = HFI;
994 return true;
995 }
996 return false;
997}
998
Douglas Gregor37aa4932011-05-04 00:14:37 +0000999bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1000 // Check if we've ever seen this file as a header.
1001 if (File->getUID() >= FileInfo.size())
1002 return false;
1003
1004 // Resolve header file info from the external source, if needed.
1005 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001006 if (ExternalSource && !HFI.Resolved)
1007 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregor37aa4932011-05-04 00:14:37 +00001008
Argyrios Kyrtzidis0d355df2012-12-10 20:08:37 +00001009 return HFI.isPragmaOnce || HFI.isImport ||
1010 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001011}
1012
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001013void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001014 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001015 bool isCompilingModuleHeader) {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001016 if (FE->getUID() >= FileInfo.size())
1017 FileInfo.resize(FE->getUID()+1);
1018
1019 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1020 HFI.isModuleHeader = true;
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001021 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001022 HFI.setHeaderRole(Role);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001023}
1024
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001025bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1026 ++NumIncluded; // Count # of attempted #includes.
1027
1028 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001029 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001030
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001031 // If this is a #import directive, check that we have not already imported
1032 // this header.
1033 if (isImport) {
1034 // If this has already been imported, don't import it again.
1035 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001036
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001037 // Has this already been #import'ed or #include'd?
1038 if (FileInfo.NumIncludes) return false;
1039 } else {
1040 // Otherwise, if this is a #include of a file that was previously #import'd
1041 // or if this is the second #include of a #pragma once file, ignore it.
1042 if (FileInfo.isImport)
1043 return false;
1044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001046 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1047 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001048 if (const IdentifierInfo *ControllingMacro
Douglas Gregor99734e72009-04-25 23:30:02 +00001049 = FileInfo.getControllingMacro(ExternalLookup))
1050 if (ControllingMacro->hasMacroDefinition()) {
1051 ++NumMultiIncludeFileOptzn;
1052 return false;
1053 }
Mike Stump11289f42009-09-09 15:08:12 +00001054
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001055 // Increment the number of times this file has been included.
1056 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001057
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001058 return true;
1059}
1060
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001061size_t HeaderSearch::getTotalMemory() const {
1062 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001063 + llvm::capacity_in_bytes(FileInfo)
1064 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001065 + LookupFileCache.getAllocator().getTotalMemory()
1066 + FrameworkMap.getAllocator().getTotalMemory();
1067}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001068
1069StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001070 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001071}
Douglas Gregor718292f2011-11-11 19:10:28 +00001072
1073bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001074 const DirectoryEntry *Root,
1075 bool IsSystem) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001076 if (!enabledModules() || !LangOpts.ModulesImplicitMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001077 return false;
1078
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001079 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001080
1081 StringRef DirName = FileName;
1082 do {
1083 // Get the parent directory name.
1084 DirName = llvm::sys::path::parent_path(DirName);
1085 if (DirName.empty())
1086 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001087
Douglas Gregor718292f2011-11-11 19:10:28 +00001088 // Determine whether this directory exists.
1089 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1090 if (!Dir)
1091 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001092
Ben Langmuir984e1df2014-03-19 20:23:34 +00001093 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001094 switch (loadModuleMapFile(Dir, IsSystem,
1095 llvm::sys::path::extension(Dir->getName()) ==
1096 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001097 case LMM_NewlyLoaded:
1098 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001099 // Success. All of the directories we stepped through inherit this module
1100 // map file.
1101 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1102 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1103 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001104
1105 case LMM_NoDirectory:
1106 case LMM_InvalidModuleMap:
1107 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001108 }
1109
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001110 // If we hit the top of our search, we're done.
1111 if (Dir == Root)
1112 return false;
1113
Douglas Gregor718292f2011-11-11 19:10:28 +00001114 // Keep track of all of the directories we checked, so we can mark them as
1115 // having module maps if we eventually do find a module map.
1116 FixUpDirectories.push_back(Dir);
1117 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001118}
1119
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001120ModuleMap::KnownHeader
1121HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001122 if (ExternalSource) {
1123 // Make sure the external source has handled header info about this file,
1124 // which includes whether the file is part of a module.
1125 (void)getFileInfo(File);
1126 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001127 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001128}
1129
Richard Smith9acb99e32014-12-10 03:09:48 +00001130static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001131 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001132 StringRef Filename = llvm::sys::path::filename(File->getName());
1133 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001134 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001135 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001136 else if (Filename == "module.modulemap")
1137 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1138 else
1139 return nullptr;
1140 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001141}
1142
Ben Langmuir984e1df2014-03-19 20:23:34 +00001143bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001144 // Find the directory for the module. For frameworks, that may require going
1145 // up from the 'Modules' directory.
1146 const DirectoryEntry *Dir = nullptr;
1147 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1148 Dir = FileMgr.getDirectory(".");
1149 else {
1150 Dir = File->getDir();
1151 StringRef DirName(Dir->getName());
1152 if (llvm::sys::path::filename(DirName) == "Modules") {
1153 DirName = llvm::sys::path::parent_path(DirName);
1154 if (DirName.endswith(".framework"))
1155 Dir = FileMgr.getDirectory(DirName);
1156 // FIXME: This assert can fail if there's a race between the above check
1157 // and the removal of the directory.
1158 assert(Dir && "parent must exist");
1159 }
1160 }
1161
1162 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001163 case LMM_AlreadyLoaded:
1164 case LMM_NewlyLoaded:
1165 return false;
1166 case LMM_NoDirectory:
1167 case LMM_InvalidModuleMap:
1168 return true;
1169 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001170 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001171}
1172
1173HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001174HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1175 const DirectoryEntry *Dir) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001176 assert(File && "expected FileEntry");
1177
Richard Smith9887d792014-10-17 01:42:53 +00001178 // Check whether we've already loaded this module map, and mark it as being
1179 // loaded in case we recursively try to load it from itself.
1180 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1181 if (!AddResult.second)
1182 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001183
Richard Smith9acb99e32014-12-10 03:09:48 +00001184 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001185 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001186 return LMM_InvalidModuleMap;
1187 }
1188
1189 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001190 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1191 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001192 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001193 return LMM_InvalidModuleMap;
1194 }
1195 }
1196
1197 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001198 return LMM_NewlyLoaded;
1199}
1200
1201const FileEntry *
1202HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001203 if (!LangOpts.ModulesImplicitMaps)
1204 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001205 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1206 // module.map at the framework root is also accepted.
1207 SmallString<128> ModuleMapFileName(Dir->getName());
1208 if (IsFramework)
1209 llvm::sys::path::append(ModuleMapFileName, "Modules");
1210 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1211 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1212 return F;
1213
1214 // Continue to allow module.map
1215 ModuleMapFileName = Dir->getName();
1216 llvm::sys::path::append(ModuleMapFileName, "module.map");
1217 return FileMgr.getFile(ModuleMapFileName);
1218}
1219
1220Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001221 const DirectoryEntry *Dir,
1222 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001223 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001224 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001225
Douglas Gregor56c64012011-11-17 01:41:17 +00001226 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001227 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001228 case LMM_InvalidModuleMap:
1229 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001230
Douglas Gregor56c64012011-11-17 01:41:17 +00001231 case LMM_AlreadyLoaded:
1232 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001233 return nullptr;
1234
Douglas Gregor56c64012011-11-17 01:41:17 +00001235 case LMM_NewlyLoaded:
1236 return ModMap.findModule(Name);
1237 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001238
Douglas Gregor9194a912012-11-06 19:39:40 +00001239
Ben Langmuirc3ea5652014-03-20 18:27:26 +00001240 // Try to infer a module map from the framework directory.
Daniel Jasper21a0f552014-11-25 09:45:48 +00001241 if (LangOpts.ModulesImplicitMaps)
1242 return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
1243
1244 return nullptr;
Douglas Gregor56c64012011-11-17 01:41:17 +00001245}
1246
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001247
Douglas Gregor80b69042011-11-12 00:22:19 +00001248HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001249HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1250 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001251 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001252 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001253
Douglas Gregor80b69042011-11-12 00:22:19 +00001254 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001255}
1256
Douglas Gregor80b69042011-11-12 00:22:19 +00001257HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001258HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1259 bool IsFramework) {
1260 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001261 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001262 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001263
Ben Langmuir984e1df2014-03-19 20:23:34 +00001264 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001265 LoadModuleMapResult Result =
1266 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001267 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1268 // E.g. Foo.framework/Modules/module.modulemap
1269 // ^Dir ^ModuleMapFile
1270 if (Result == LMM_NewlyLoaded)
1271 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001272 else if (Result == LMM_InvalidModuleMap)
1273 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001274 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001275 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001276 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001277}
Douglas Gregor718292f2011-11-11 19:10:28 +00001278
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001279void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001280 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001281
1282 if (LangOpts.ModulesImplicitMaps) {
1283 // Load module maps for each of the header search directories.
1284 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1285 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1286 if (SearchDirs[Idx].isFramework()) {
1287 std::error_code EC;
1288 SmallString<128> DirNative;
1289 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1290 DirNative);
1291
1292 // Search each of the ".framework" directories to load them as modules.
1293 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1294 Dir != DirEnd && !EC; Dir.increment(EC)) {
1295 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1296 continue;
1297
1298 const DirectoryEntry *FrameworkDir =
1299 FileMgr.getDirectory(Dir->path());
1300 if (!FrameworkDir)
1301 continue;
1302
1303 // Load this framework module.
1304 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1305 IsSystem);
1306 }
1307 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001308 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001309
1310 // FIXME: Deal with header maps.
1311 if (SearchDirs[Idx].isHeaderMap())
1312 continue;
1313
1314 // Try to load a module map file for the search directory.
1315 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1316 /*IsFramework*/ false);
1317
1318 // Try to load module map files for immediate subdirectories of this
1319 // search directory.
1320 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001321 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001322 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001323
Douglas Gregor07f43572012-01-29 18:15:03 +00001324 // Populate the list of modules.
1325 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1326 MEnd = ModMap.module_end();
1327 M != MEnd; ++M) {
1328 Modules.push_back(M->getValue());
1329 }
1330}
Douglas Gregor0339a642013-03-21 01:08:50 +00001331
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001332void HeaderSearch::loadTopLevelSystemModules() {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001333 if (!LangOpts.ModulesImplicitMaps)
1334 return;
1335
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001336 // Load module maps for each of the header search directories.
1337 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001338 // We only care about normal header directories.
1339 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001340 continue;
1341 }
1342
1343 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001344 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001345 SearchDirs[Idx].isSystemHeaderDirectory(),
1346 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001347 }
1348}
1349
Douglas Gregor0339a642013-03-21 01:08:50 +00001350void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001351 assert(LangOpts.ModulesImplicitMaps &&
1352 "Should not be loading subdirectory module maps");
1353
Douglas Gregor0339a642013-03-21 01:08:50 +00001354 if (SearchDir.haveSearchedAllModuleMaps())
1355 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001356
1357 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001358 SmallString<128> DirNative;
1359 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1360 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1361 Dir != DirEnd && !EC; Dir.increment(EC)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001362 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1363 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001364 }
1365
1366 SearchDir.setSearchedAllModuleMaps(true);
1367}