blob: c12d7314ee23d360b45fed191aba3dadc190de47 [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()),
53 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
Nico Weber3b1d1212011-05-24 04:31:14 +000054 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000055 SystemDirIdx = 0;
56 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000057
Craig Topperd2d442c2014-05-17 23:10:59 +000058 ExternalLookup = nullptr;
59 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000060 NumIncluded = 0;
61 NumMultiIncludeFileOptzn = 0;
62 NumFrameworkLookups = NumSubFrameworkLookups = 0;
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +000063
64 EnabledModules = LangOpts.Modules;
Chris Lattner641a0be2006-10-20 06:23:14 +000065}
66
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000067HeaderSearch::~HeaderSearch() {
68 // Delete headermaps.
69 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
70 delete HeaderMaps[i].second;
71}
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattner59a9ebd2006-10-18 05:34:33 +000073void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000074 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
75 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000076 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
77 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
78 NumOnceOnlyFiles += FileInfo[i].isImport;
79 if (MaxNumIncludes < FileInfo[i].NumIncludes)
80 MaxNumIncludes = FileInfo[i].NumIncludes;
81 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
82 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000083 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
84 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
85 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000086
Chris Lattner23b7eb62007-06-15 23:05:46 +000087 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
88 fprintf(stderr, " %d #includes skipped due to"
89 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000090
Chris Lattner23b7eb62007-06-15 23:05:46 +000091 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
92 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000093}
94
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000095/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +000096/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +000097const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000098 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +000099 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000100 if (!HeaderMaps.empty()) {
101 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000102 // Pointer equality comparison of FileEntries works because they are
103 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000104 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000105 return HeaderMaps[i].second;
106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Chris Lattner5159f612010-11-23 08:35:12 +0000108 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000109 HeaderMaps.push_back(std::make_pair(FE, HM));
110 return HM;
111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Craig Topperd2d442c2014-05-17 23:10:59 +0000113 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000114}
115
Douglas Gregor279a6c32012-01-29 17:08:11 +0000116std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000117 return getModuleFileName(Module->Name, Module->ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000118}
119
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000120std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
121 StringRef ModuleMapPath) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000122 // If we don't have a module cache path, we can't do anything.
123 if (ModuleCachePath.empty())
124 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000125
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000126 SmallString<256> Result(ModuleCachePath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000127 llvm::sys::fs::make_absolute(Result);
128
129 if (HSOpts->DisableModuleHash) {
130 llvm::sys::path::append(Result, ModuleName + ".pcm");
131 } else {
132 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
133 // be globally unique to this particular module. To avoid false-negatives
134 // on case-insensitive filesystems, we use lower-case, which is safe because
135 // to cause a collision the modules must have the same name, which is an
136 // error if they are imported in the same translation.
137 SmallString<256> AbsModuleMapPath(ModuleMapPath);
138 llvm::sys::fs::make_absolute(AbsModuleMapPath);
139 llvm::APInt Code(64, llvm::hash_value(AbsModuleMapPath.str().lower()));
140 SmallString<128> HashStr;
141 Code.toStringUnsigned(HashStr, /*Radix*/36);
142 llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
143 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000144 return Result.str().str();
145}
146
147Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000148 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000149 Module *Module = ModMap.findModule(ModuleName);
150 if (Module || !AllowSearch)
151 return Module;
152
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000153 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000154 // maps, searching for a module map that describes this module.
155 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
156 if (SearchDirs[Idx].isFramework()) {
157 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000158 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000159 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
160 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
161 if (const DirectoryEntry *FrameworkDir
162 = FileMgr.getDirectory(FrameworkDirName)) {
163 bool IsSystem
164 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
165 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000166 if (Module)
167 break;
168 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000169 }
170
171 // FIXME: Figure out how header maps and module maps will work together.
172
173 // Only deal with normal search directories.
174 if (!SearchDirs[Idx].isNormalDir())
175 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000176
177 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000178 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000179 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
180 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000181 // We just loaded a module map file; check whether the module is
182 // available now.
183 Module = ModMap.findModule(ModuleName);
184 if (Module)
185 break;
186 }
187
188 // Search for a module map in a subdirectory with the same name as the
189 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000190 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000191 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
192 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000193 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
194 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000195 // If we just loaded a module map file, look for the module again.
196 Module = ModMap.findModule(ModuleName);
197 if (Module)
198 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000199 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000200
201 // If we've already performed the exhaustive search for module maps in this
202 // search directory, don't do it again.
203 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
204 continue;
205
206 // Load all module maps in the immediate subdirectories of this search
207 // directory.
208 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
209
210 // Look again for the module.
211 Module = ModMap.findModule(ModuleName);
212 if (Module)
213 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000214 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000215
Douglas Gregor279a6c32012-01-29 17:08:11 +0000216 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000217}
218
Chris Lattnerf62f7582007-12-17 07:52:39 +0000219//===----------------------------------------------------------------------===//
220// File lookup within a DirectoryLookup scope
221//===----------------------------------------------------------------------===//
222
Chris Lattner8d720d02007-12-17 17:57:27 +0000223/// getName - Return the directory or filename corresponding to this lookup
224/// object.
225const char *DirectoryLookup::getName() const {
226 if (isNormalDir())
227 return getDir()->getName();
228 if (isFramework())
229 return getFrameworkDir()->getName();
230 assert(isHeaderMap() && "Unknown DirectoryLookup");
231 return getHeaderMap()->getFileName();
232}
233
Richard Smith8c71eba2014-03-05 20:51:45 +0000234static const FileEntry *
235getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
236 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
237 ModuleMap::KnownHeader *SuggestedModule) {
238 // If we have a module map that might map this header, load it and
239 // check whether we'll have a suggestion for a module.
240 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
241 if (SuggestedModule) {
242 const FileEntry *File = HS.getFileMgr().getFile(FileName,
243 /*OpenFile=*/false);
244 if (File) {
245 // If there is a module that corresponds to this header, suggest it.
246 *SuggestedModule = HS.findModuleForHeader(File);
247
248 // FIXME: This appears to be a no-op. We loaded the module map for this
249 // directory at the start of this function.
250 if (!SuggestedModule->getModule() &&
251 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
252 *SuggestedModule = HS.findModuleForHeader(File);
253 }
254
255 return File;
256 }
257
258 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
259}
Chris Lattner8d720d02007-12-17 17:57:27 +0000260
Chris Lattnerf62f7582007-12-17 07:52:39 +0000261/// LookupFile - Lookup the specified file in this search path, returning it
262/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000263const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000264 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000265 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000266 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000267 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000268 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000269 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000270 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000271 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000272 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000273 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000274
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000275 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000276 if (isNormalDir()) {
277 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000278 TmpDir = getDir()->getName();
279 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000280 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000281 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000282 SearchPath->clear();
283 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
284 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000285 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000286 RelativePath->clear();
287 RelativePath->append(Filename.begin(), Filename.end());
288 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000289
290 return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
291 isSystemHeaderDirectory(),
292 SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000293 }
Mike Stump11289f42009-09-09 15:08:12 +0000294
Chris Lattner712e3872007-12-17 08:13:48 +0000295 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000296 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000297 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000298
Chris Lattner44bd21b2007-12-17 08:17:39 +0000299 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000300 const HeaderMap *HM = getHeaderMap();
301 SmallString<1024> Path;
302 StringRef Dest = HM->lookupFilename(Filename, Path);
303 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000304 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000305
306 const FileEntry *Result;
307
308 // Check if the headermap maps the filename to a framework include
309 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
310 // framework include.
311 if (llvm::sys::path::is_relative(Dest)) {
312 MappedName.clear();
313 MappedName.append(Dest.begin(), Dest.end());
314 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000315 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000316 Result = HM->LookupFile(Filename, HS.getFileMgr());
317
318 } else {
319 Result = HS.getFileMgr().getFile(Dest);
320 }
321
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000322 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000323 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000325 SearchPath->clear();
326 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
327 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000328 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000329 RelativePath->clear();
330 RelativePath->append(Filename.begin(), Filename.end());
331 }
332 }
333 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000334}
335
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000336/// \brief Given a framework directory, find the top-most framework directory.
337///
338/// \param FileMgr The file manager to use for directory lookups.
339/// \param DirName The name of the framework directory.
340/// \param SubmodulePath Will be populated with the submodule path from the
341/// returned top-level module to the originally named framework.
342static const DirectoryEntry *
343getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
344 SmallVectorImpl<std::string> &SubmodulePath) {
345 assert(llvm::sys::path::extension(DirName) == ".framework" &&
346 "Not a framework directory");
347
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000348 // Note: as an egregious but useful hack we use the real path here, because
349 // frameworks moving between top-level frameworks to embedded frameworks tend
350 // to be symlinked, and we base the logical structure of modules on the
351 // physical layout. In particular, we need to deal with crazy includes like
352 //
353 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
354 //
355 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
356 // which one should access with, e.g.,
357 //
358 // #include <Bar/Wibble.h>
359 //
360 // Similar issues occur when a top-level framework has moved into an
361 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000362 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000363 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000364 do {
365 // Get the parent directory name.
366 DirName = llvm::sys::path::parent_path(DirName);
367 if (DirName.empty())
368 break;
369
370 // Determine whether this directory exists.
371 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
372 if (!Dir)
373 break;
374
375 // If this is a framework directory, then we're a subframework of this
376 // framework.
377 if (llvm::sys::path::extension(DirName) == ".framework") {
378 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
379 TopFrameworkDir = Dir;
380 }
381 } while (true);
382
383 return TopFrameworkDir;
384}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000385
Chris Lattner712e3872007-12-17 08:13:48 +0000386/// DoFrameworkLookup - Do a lookup of the specified file in the current
387/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000388const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000389 StringRef Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000390 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000391 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000392 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000393 ModuleMap::KnownHeader *SuggestedModule,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000394 bool &InUserSpecifiedSystemFramework) const
Douglas Gregor97eec242011-09-15 22:00:41 +0000395{
Chris Lattner712e3872007-12-17 08:13:48 +0000396 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000397
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000398 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000399 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000400 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattner712e3872007-12-17 08:13:48 +0000402 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000403 // HeaderSearch. Possible answers are yes/no and unknown.
404 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000405 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000406
Chris Lattner712e3872007-12-17 08:13:48 +0000407 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000408 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000409 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattner712e3872007-12-17 08:13:48 +0000411 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000413 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000414 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000415 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000416 if (FrameworkName.empty() || FrameworkName.back() != '/')
417 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000419 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000420 StringRef ModuleName(Filename.begin(), SlashPos);
421 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000423 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
424 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000425
Daniel Dunbar17138612012-04-05 17:09:40 +0000426 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000427 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000428 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattner5ed76da2006-10-22 07:24:13 +0000430 // If the framework dir doesn't exist, we fail.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000431 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000432 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattner5ed76da2006-10-22 07:24:13 +0000434 // Otherwise, if it does, remember that this is the right direntry for this
435 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000436 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000437
438 // If this is a user search directory, check if the framework has been
439 // user-specified as a system framework.
440 if (getDirCharacteristic() == SrcMgr::C_User) {
441 SmallString<1024> SystemFrameworkMarker(FrameworkName);
442 SystemFrameworkMarker += ".system_framework";
443 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
444 CacheEntry.IsUserSpecifiedSystemFramework = true;
445 }
446 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000447 }
Mike Stump11289f42009-09-09 15:08:12 +0000448
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000449 // Set the 'user-specified system framework' flag.
450 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
451
Craig Topperd2d442c2014-05-17 23:10:59 +0000452 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000453 RelativePath->clear();
454 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
455 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000456
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000457 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000458 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000459
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000460 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000461
Craig Topperd2d442c2014-05-17 23:10:59 +0000462 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000463 SearchPath->clear();
464 // Without trailing '/'.
465 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
466 }
467
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000468 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000469 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
470 /*openFile=*/!SuggestedModule);
471 if (!FE) {
472 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
473 const char *Private = "Private";
474 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
475 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000476 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000477 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
478 Private+strlen(Private));
479
480 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000483 // If we found the header and are allowed to suggest a module, do so now.
484 if (FE && SuggestedModule) {
485 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000486 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000487 bool FoundFramework = false;
488 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000489 // Determine whether this directory exists.
490 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
491 if (!Dir)
492 break;
493
494 // If this is a framework directory, then we're a subframework of this
495 // framework.
496 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
497 FoundFramework = true;
498 break;
499 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000500
501 // Get the parent directory name.
502 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
503 if (FrameworkPath.empty())
504 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000505 } while (true);
506
507 if (FoundFramework) {
508 // Find the top-level framework based on this framework.
509 SmallVector<std::string, 4> SubmodulePath;
510 const DirectoryEntry *TopFrameworkDir
511 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
512
513 // Determine the name of the top-level framework.
514 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
515
516 // Load this framework module. If that succeeds, find the suggested module
517 // for this header, if any.
518 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
519 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
520 *SuggestedModule = HS.findModuleForHeader(FE);
521 }
522 } else {
523 *SuggestedModule = HS.findModuleForHeader(FE);
524 }
525 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000526 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000527}
528
Douglas Gregor89929282012-01-30 06:01:29 +0000529void HeaderSearch::setTarget(const TargetInfo &Target) {
530 ModMap.setTarget(Target);
531}
532
Chris Lattnerf62f7582007-12-17 07:52:39 +0000533
Chris Lattner712e3872007-12-17 08:13:48 +0000534//===----------------------------------------------------------------------===//
535// Header File Location.
536//===----------------------------------------------------------------------===//
537
Reid Klecknera97d4c02014-02-18 23:49:24 +0000538/// \brief Return true with a diagnostic if the file that MSVC would have found
539/// fails to match the one that Clang would have found with MSVC header search
540/// disabled.
541static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
542 const FileEntry *MSFE, const FileEntry *FE,
543 SourceLocation IncludeLoc) {
544 if (MSFE && FE != MSFE) {
545 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
546 return true;
547 }
548 return false;
549}
Chris Lattner712e3872007-12-17 08:13:48 +0000550
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000551static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
552 assert(!Str.empty());
553 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
554 std::copy(Str.begin(), Str.end(), CopyStr);
555 CopyStr[Str.size()] = '\0';
556 return CopyStr;
557}
558
James Dennettc07ab2c2012-06-20 00:56:32 +0000559/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000560/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000561/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
562/// non-empty, indicates where the \#including file(s) are, in case a relative
563/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000564const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000565 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
566 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
567 ArrayRef<const FileEntry *> Includers, SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000568 SmallVectorImpl<char> *RelativePath,
Will Wilson0fafd342013-12-27 19:46:16 +0000569 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
Daniel Jasper97da9172013-10-22 08:09:47 +0000570 if (!HSOpts->ModuleMapFiles.empty()) {
571 // Preload all explicitly specified module map files. This enables modules
572 // map files lying in a directory structure separate from the header files
573 // that they describe. These cannot be loaded lazily upon encountering a
Will Wilson9ef61a72013-12-19 16:24:17 +0000574 // header file, as there is no other known mapping from a header file to its
Daniel Jasper97da9172013-10-22 08:09:47 +0000575 // module map file.
576 for (llvm::SetVector<std::string>::iterator
577 I = HSOpts->ModuleMapFiles.begin(),
578 E = HSOpts->ModuleMapFiles.end();
579 I != E; ++I) {
580 const FileEntry *File = FileMgr.getFile(*I);
581 if (!File)
582 continue;
583 loadModuleMapFile(File, /*IsSystem=*/false);
584 }
585 HSOpts->ModuleMapFiles.clear();
586 }
587
Douglas Gregor97eec242011-09-15 22:00:41 +0000588 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000589 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000590
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000591 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000592 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000593 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000594
595 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000596 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000597
Craig Topperd2d442c2014-05-17 23:10:59 +0000598 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000599 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000600 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000601 RelativePath->clear();
602 RelativePath->append(Filename.begin(), Filename.end());
603 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000604 // Otherwise, just return the file.
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000605 return FileMgr.getFile(Filename, /*openFile=*/true);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000606 }
Mike Stump11289f42009-09-09 15:08:12 +0000607
Reid Klecknera97d4c02014-02-18 23:49:24 +0000608 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000609 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000610 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000611
Douglas Gregor9f93e382011-07-28 04:45:53 +0000612 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000613 // directory. This cannot be based on CurDir, because each includer could be
614 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
615 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000616 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000617 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000618 SmallString<1024> TmpDir;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000619 for (ArrayRef<const FileEntry *>::iterator I = Includers.begin(),
620 E = Includers.end();
Will Wilson0fafd342013-12-27 19:46:16 +0000621 I != E; ++I) {
622 const FileEntry *Includer = *I;
623 // Concatenate the requested file onto the directory.
624 // FIXME: Portability. Filename concatenation should be in sys::Path.
625 TmpDir = Includer->getDir()->getName();
626 TmpDir.push_back('/');
627 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000628
Richard Smith6f548ec2014-03-06 18:08:08 +0000629 // FIXME: We don't cache the result of getFileInfo across the call to
630 // getFileAndSuggestModule, because it's a reference to an element of
631 // a container that could be reallocated across this call.
632 bool IncluderIsSystemHeader =
633 getFileInfo(Includer).DirInfo != SrcMgr::C_User;
Will Wilson0fafd342013-12-27 19:46:16 +0000634 if (const FileEntry *FE =
Richard Smith8c71eba2014-03-05 20:51:45 +0000635 getFileAndSuggestModule(*this, TmpDir.str(), Includer->getDir(),
Richard Smith6f548ec2014-03-06 18:08:08 +0000636 IncluderIsSystemHeader,
Richard Smith8c71eba2014-03-05 20:51:45 +0000637 SuggestedModule)) {
Will Wilson0fafd342013-12-27 19:46:16 +0000638 // Leave CurDir unset.
639 // This file is a system header or C++ unfriendly if the old file is.
640 //
641 // Note that we only use one of FromHFI/ToHFI at once, due to potential
642 // reallocation of the underlying vector potentially making the first
643 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000644 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000645 unsigned DirInfo = FromHFI.DirInfo;
646 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
647 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000648
Will Wilson0fafd342013-12-27 19:46:16 +0000649 HeaderFileInfo &ToHFI = getFileInfo(FE);
650 ToHFI.DirInfo = DirInfo;
651 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
652 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000653
Craig Topperd2d442c2014-05-17 23:10:59 +0000654 if (SearchPath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000655 StringRef SearchPathRef(Includer->getDir()->getName());
656 SearchPath->clear();
657 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
658 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000659 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000660 RelativePath->clear();
661 RelativePath->append(Filename.begin(), Filename.end());
662 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000663 if (I == Includers.begin())
664 return FE;
665
666 // Otherwise, we found the path via MSVC header search rules. If
667 // -Wmsvc-include is enabled, we have to keep searching to see if we
668 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000669 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000670 return FE;
671 } else {
672 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000673 if (SuggestedModule) {
674 MSSuggestedModule = *SuggestedModule;
675 *SuggestedModule = ModuleMap::KnownHeader();
676 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000677 break;
678 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000679 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000680 }
681 }
Mike Stump11289f42009-09-09 15:08:12 +0000682
Craig Topperd2d442c2014-05-17 23:10:59 +0000683 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000684
685 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000686 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000687
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000688 // If this is a #include_next request, start searching after the directory the
689 // file was found in.
690 if (FromDir)
691 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattnerd4275422007-07-22 07:28:00 +0000693 // Cache all of the lookups performed by this method. Many headers are
694 // multiply included, and the "pragma once" optimization prevents them from
695 // being relex/pp'd, but they would still have to search through a
696 // (potentially huge) series of SearchDirs to find it.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000697 LookupFileCacheInfo &CacheLookup =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000698 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattnerd4275422007-07-22 07:28:00 +0000699
700 // If the entry has been previously looked up, the first value will be
701 // non-zero. If the value is equal to i (the start point of our search), then
702 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000703 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000704 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000705 i = CacheLookup.HitIdx;
706 if (CacheLookup.MappedName)
707 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000708 } else {
709 // Otherwise, this is the first query, or the previous query didn't match
710 // our search start. We will fill in our found location below, so prime the
711 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000712 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000713 }
Mike Stump11289f42009-09-09 15:08:12 +0000714
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000715 SmallString<64> MappedName;
716
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000717 // Check each directory in sequence to see if it contains this file.
718 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000719 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000720 bool HasBeenMapped = false;
Mike Stump11289f42009-09-09 15:08:12 +0000721 const FileEntry *FE =
Douglas Gregor97eec242011-09-15 22:00:41 +0000722 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000723 SuggestedModule, InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000724 HasBeenMapped, MappedName);
725 if (HasBeenMapped) {
726 CacheLookup.MappedName =
727 copyString(Filename, LookupFileCache.getAllocator());
728 }
Chris Lattner712e3872007-12-17 08:13:48 +0000729 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner712e3872007-12-17 08:13:48 +0000731 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattner712e3872007-12-17 08:13:48 +0000733 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000734 HeaderFileInfo &HFI = getFileInfo(FE);
735 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000736
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000737 // If the directory characteristic is User but this framework was
738 // user-specified to be treated as a system framework, promote the
739 // characteristic.
740 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
741 HFI.DirInfo = SrcMgr::C_System;
742
Richard Smith8acadcb2012-06-13 20:27:03 +0000743 // If the filename matches a known system header prefix, override
744 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000745 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
746 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
747 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000748 : SrcMgr::C_User;
749 break;
750 }
751 }
752
Douglas Gregor9f93e382011-07-28 04:45:53 +0000753 // If this file is found in a header map and uses the framework style of
754 // includes, then this header is part of a framework we're building.
755 if (CurDir->isIndexHeaderMap()) {
756 size_t SlashPos = Filename.find('/');
757 if (SlashPos != StringRef::npos) {
758 HFI.IndexHeaderMapHeader = 1;
759 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
760 SlashPos));
761 }
762 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000763
Richard Smith8c71eba2014-03-05 20:51:45 +0000764 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
765 if (SuggestedModule)
766 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000767 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000768 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000769
Chris Lattner712e3872007-12-17 08:13:48 +0000770 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000771 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000772 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000773 }
Mike Stump11289f42009-09-09 15:08:12 +0000774
Douglas Gregord8575e12011-07-30 06:28:34 +0000775 // If we are including a file with a quoted include "foo.h" from inside
776 // a header in a framework that is currently being built, and we couldn't
777 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
778 // "Foo" is the name of the framework in which the including header was found.
Will Wilson0fafd342013-12-27 19:46:16 +0000779 if (!Includers.empty() && !isAngled &&
780 Filename.find('/') == StringRef::npos) {
781 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front());
Douglas Gregord8575e12011-07-30 06:28:34 +0000782 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000783 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000784 ScratchFilename += IncludingHFI.Framework;
785 ScratchFilename += '/';
786 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000787
Reid Klecknera97d4c02014-02-18 23:49:24 +0000788 const FileEntry *FE = LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000789 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
790 Includers.front(), SearchPath, RelativePath, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000791
Richard Smith8c71eba2014-03-05 20:51:45 +0000792 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
793 if (SuggestedModule)
794 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000795 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000796 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000797
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000798 LookupFileCacheInfo &CacheLookup
Douglas Gregord8575e12011-07-30 06:28:34 +0000799 = LookupFileCache.GetOrCreateValue(Filename).getValue();
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000800 CacheLookup.HitIdx
801 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000802 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000803 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000804 }
805 }
806
Craig Topperd2d442c2014-05-17 23:10:59 +0000807 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000808 if (SuggestedModule)
809 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000810 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000811 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000812
Chris Lattnerd4275422007-07-22 07:28:00 +0000813 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000814 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000815 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000816}
817
Chris Lattner63dd32b2006-10-20 04:42:40 +0000818/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000819/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000820/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
821/// is a subframework within Carbon.framework. If so, return the FileEntry
822/// for the designated file, otherwise return null.
823const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000824LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000825 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000826 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000827 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000828 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000829 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattner63dd32b2006-10-20 04:42:40 +0000831 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000832 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000833 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000834 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattner63dd32b2006-10-20 04:42:40 +0000836 // Look up the base framework name of the ContextFileEnt.
Chris Lattner48043482006-10-27 05:12:36 +0000837 const char *ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattner63dd32b2006-10-20 04:42:40 +0000839 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000840 const unsigned DotFrameworkLen = 10;
841 const char *FrameworkPos = strstr(ContextName, ".framework");
Craig Topperd2d442c2014-05-17 23:10:59 +0000842 if (FrameworkPos == nullptr ||
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000843 (FrameworkPos[DotFrameworkLen] != '/' &&
844 FrameworkPos[DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000845 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000846
Daniel Dunbar17138612012-04-05 17:09:40 +0000847 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000848
Chris Lattner63dd32b2006-10-20 04:42:40 +0000849 // Append Frameworks/HIToolbox.framework/
850 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000851 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000852 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000853
Daniel Dunbar17138612012-04-05 17:09:40 +0000854 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
Chris Lattner8afa6de2010-11-21 09:55:08 +0000855 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000856
Chris Lattner5ed76da2006-10-22 07:24:13 +0000857 // Some other location?
Daniel Dunbar17138612012-04-05 17:09:40 +0000858 if (CacheLookup.getValue().Directory &&
Chris Lattner34d1f5a2007-02-08 19:08:49 +0000859 CacheLookup.getKeyLength() == FrameworkName.size() &&
860 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
861 CacheLookup.getKeyLength()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000862 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000863
Chris Lattner5ed76da2006-10-22 07:24:13 +0000864 // Cache subframework.
Craig Topperd2d442c2014-05-17 23:10:59 +0000865 if (!CacheLookup.getValue().Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000866 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000867
Chris Lattner5ed76da2006-10-22 07:24:13 +0000868 // If the framework dir doesn't exist, we fail.
Chris Lattner5159f612010-11-23 08:35:12 +0000869 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000870 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattner5ed76da2006-10-22 07:24:13 +0000872 // Otherwise, if it does, remember that this is the right direntry for this
873 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000874 CacheLookup.getValue().Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000875 }
Mike Stump11289f42009-09-09 15:08:12 +0000876
Craig Topperd2d442c2014-05-17 23:10:59 +0000877 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000878
Craig Topperd2d442c2014-05-17 23:10:59 +0000879 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000880 RelativePath->clear();
881 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
882 }
883
Chris Lattner63dd32b2006-10-20 04:42:40 +0000884 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000885 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000886 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000887 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000888 SearchPath->clear();
889 // Without trailing '/'.
890 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
891 }
892
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000893 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000894 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000895
Chris Lattner63dd32b2006-10-20 04:42:40 +0000896 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000897 HeadersFilename = FrameworkName;
898 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000899 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000900 SearchPath->clear();
901 // Without trailing '/'.
902 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
903 }
904
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000905 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000906 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000907 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000908 }
Mike Stump11289f42009-09-09 15:08:12 +0000909
Chris Lattner577377e2006-10-20 04:55:45 +0000910 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000911 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000912 // Note that the temporary 'DirInfo' is required here, as either call to
913 // getFileInfo could resize the vector and we don't want to rely on order
914 // of evaluation.
915 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
916 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000917
918 // If we're supposed to suggest a module, look for one now.
919 if (SuggestedModule) {
920 // Find the top-level framework based on this framework.
921 FrameworkName.pop_back(); // remove the trailing '/'
922 SmallVector<std::string, 4> SubmodulePath;
923 const DirectoryEntry *TopFrameworkDir
924 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
925
926 // Determine the name of the top-level framework.
927 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
928
929 // Load this framework module. If that succeeds, find the suggested module
930 // for this header, if any.
931 bool IsSystem = false;
932 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
933 *SuggestedModule = findModuleForHeader(FE);
934 }
935 }
936
Chris Lattner577377e2006-10-20 04:55:45 +0000937 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000938}
939
Chandler Carruthb0ffe502011-12-09 01:33:57 +0000940/// \brief Helper static function to normalize a path for injection into
941/// a synthetic header.
942/*static*/ std::string
943HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
944 // Implicit include paths should be resolved relative to the current
945 // working directory first, and then use the regular header search
946 // mechanism. The proper way to handle this is to have the
947 // predefines buffer located at the current working directory, but
948 // it has no file entry. For now, workaround this by using an
949 // absolute path if we find the file here, and otherwise letting
950 // header search handle it.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000951 SmallString<128> Path(File);
Chandler Carruthb0ffe502011-12-09 01:33:57 +0000952 llvm::sys::fs::make_absolute(Path);
953 bool exists;
954 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
955 Path = File;
956 else if (exists)
957 FileMgr.getFile(File);
958
959 return Lexer::Stringify(Path.str());
960}
961
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000962//===----------------------------------------------------------------------===//
963// File Info Management.
964//===----------------------------------------------------------------------===//
965
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000966/// \brief Merge the header file info provided by \p OtherHFI into the current
967/// header file info (\p HFI)
968static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
969 const HeaderFileInfo &OtherHFI) {
970 HFI.isImport |= OtherHFI.isImport;
971 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000972 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000973 HFI.NumIncludes += OtherHFI.NumIncludes;
974
975 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
976 HFI.ControllingMacro = OtherHFI.ControllingMacro;
977 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
978 }
979
980 if (OtherHFI.External) {
981 HFI.DirInfo = OtherHFI.DirInfo;
982 HFI.External = OtherHFI.External;
983 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
984 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000985
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000986 if (HFI.Framework.empty())
987 HFI.Framework = OtherHFI.Framework;
988
989 HFI.Resolved = true;
990}
991
Steve Naroff3fa455a2009-04-24 20:03:17 +0000992/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000993/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000994HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000995 if (FE->getUID() >= FileInfo.size())
996 FileInfo.resize(FE->getUID()+1);
Douglas Gregor09b69892011-02-10 17:09:37 +0000997
998 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000999 if (ExternalSource && !HFI.Resolved)
1000 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Ben Langmuird285c502014-03-13 16:46:36 +00001001 HFI.IsValid = 1;
Douglas Gregor09b69892011-02-10 17:09:37 +00001002 return HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001003}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001004
Ben Langmuird285c502014-03-13 16:46:36 +00001005bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
1006 if (FE->getUID() >= FileInfo.size())
1007 return false;
1008 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1009 if (HFI.IsValid) {
1010 Result = HFI;
1011 return true;
1012 }
1013 return false;
1014}
1015
Douglas Gregor37aa4932011-05-04 00:14:37 +00001016bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1017 // Check if we've ever seen this file as a header.
1018 if (File->getUID() >= FileInfo.size())
1019 return false;
1020
1021 // Resolve header file info from the external source, if needed.
1022 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001023 if (ExternalSource && !HFI.Resolved)
1024 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregor37aa4932011-05-04 00:14:37 +00001025
Argyrios Kyrtzidis0d355df2012-12-10 20:08:37 +00001026 return HFI.isPragmaOnce || HFI.isImport ||
1027 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001028}
1029
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001030void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001031 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001032 bool isCompilingModuleHeader) {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001033 if (FE->getUID() >= FileInfo.size())
1034 FileInfo.resize(FE->getUID()+1);
1035
1036 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1037 HFI.isModuleHeader = true;
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001038 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001039 HFI.setHeaderRole(Role);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001040}
1041
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001042bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1043 ++NumIncluded; // Count # of attempted #includes.
1044
1045 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001046 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001048 // If this is a #import directive, check that we have not already imported
1049 // this header.
1050 if (isImport) {
1051 // If this has already been imported, don't import it again.
1052 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001053
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001054 // Has this already been #import'ed or #include'd?
1055 if (FileInfo.NumIncludes) return false;
1056 } else {
1057 // Otherwise, if this is a #include of a file that was previously #import'd
1058 // or if this is the second #include of a #pragma once file, ignore it.
1059 if (FileInfo.isImport)
1060 return false;
1061 }
Mike Stump11289f42009-09-09 15:08:12 +00001062
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001063 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1064 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001065 if (const IdentifierInfo *ControllingMacro
Douglas Gregor99734e72009-04-25 23:30:02 +00001066 = FileInfo.getControllingMacro(ExternalLookup))
1067 if (ControllingMacro->hasMacroDefinition()) {
1068 ++NumMultiIncludeFileOptzn;
1069 return false;
1070 }
Mike Stump11289f42009-09-09 15:08:12 +00001071
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001072 // Increment the number of times this file has been included.
1073 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001075 return true;
1076}
1077
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001078size_t HeaderSearch::getTotalMemory() const {
1079 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001080 + llvm::capacity_in_bytes(FileInfo)
1081 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001082 + LookupFileCache.getAllocator().getTotalMemory()
1083 + FrameworkMap.getAllocator().getTotalMemory();
1084}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001085
1086StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1087 return FrameworkNames.GetOrCreateValue(Framework).getKey();
1088}
Douglas Gregor718292f2011-11-11 19:10:28 +00001089
1090bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001091 const DirectoryEntry *Root,
1092 bool IsSystem) {
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001093 if (!enabledModules())
1094 return false;
1095
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001096 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001097
1098 StringRef DirName = FileName;
1099 do {
1100 // Get the parent directory name.
1101 DirName = llvm::sys::path::parent_path(DirName);
1102 if (DirName.empty())
1103 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001104
Douglas Gregor718292f2011-11-11 19:10:28 +00001105 // Determine whether this directory exists.
1106 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1107 if (!Dir)
1108 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001109
Ben Langmuir984e1df2014-03-19 20:23:34 +00001110 // Try to load the module map file in this directory.
1111 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/false)) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001112 case LMM_NewlyLoaded:
1113 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001114 // Success. All of the directories we stepped through inherit this module
1115 // map file.
1116 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1117 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1118 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001119
1120 case LMM_NoDirectory:
1121 case LMM_InvalidModuleMap:
1122 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001123 }
1124
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001125 // If we hit the top of our search, we're done.
1126 if (Dir == Root)
1127 return false;
1128
Douglas Gregor718292f2011-11-11 19:10:28 +00001129 // Keep track of all of the directories we checked, so we can mark them as
1130 // having module maps if we eventually do find a module map.
1131 FixUpDirectories.push_back(Dir);
1132 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001133}
1134
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001135ModuleMap::KnownHeader
1136HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001137 if (ExternalSource) {
1138 // Make sure the external source has handled header info about this file,
1139 // which includes whether the file is part of a module.
1140 (void)getFileInfo(File);
1141 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001142 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001143}
1144
Ben Langmuir984e1df2014-03-19 20:23:34 +00001145static const FileEntry *getPrivateModuleMap(StringRef ModuleMapPath,
1146 const DirectoryEntry *Directory,
1147 FileManager &FileMgr) {
1148 StringRef Filename = llvm::sys::path::filename(ModuleMapPath);
1149 SmallString<128> PrivateFilename(Directory->getName());
1150 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001151 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001152 else if (Filename == "module.modulemap")
1153 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1154 else
1155 return nullptr;
1156 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001157}
1158
Ben Langmuir984e1df2014-03-19 20:23:34 +00001159bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1160 switch (loadModuleMapFileImpl(File, IsSystem)) {
1161 case LMM_AlreadyLoaded:
1162 case LMM_NewlyLoaded:
1163 return false;
1164 case LMM_NoDirectory:
1165 case LMM_InvalidModuleMap:
1166 return true;
1167 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001168 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001169}
1170
1171HeaderSearch::LoadModuleMapResult
1172HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem) {
1173 assert(File && "expected FileEntry");
1174
1175 const DirectoryEntry *Dir = File->getDir();
1176 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1177 if (KnownDir != DirectoryHasModuleMap.end())
1178 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1179
1180 if (ModMap.parseModuleMapFile(File, IsSystem)) {
1181 DirectoryHasModuleMap[Dir] = false;
1182 return LMM_InvalidModuleMap;
1183 }
1184
1185 // Try to load a corresponding private module map.
1186 if (const FileEntry *PMMFile =
1187 getPrivateModuleMap(File->getName(), Dir, FileMgr)) {
1188 if (ModMap.parseModuleMapFile(PMMFile, IsSystem)) {
1189 DirectoryHasModuleMap[Dir] = false;
1190 return LMM_InvalidModuleMap;
1191 }
1192 }
1193
1194 // This directory has a module map.
1195 DirectoryHasModuleMap[Dir] = true;
1196 return LMM_NewlyLoaded;
1197}
1198
1199const FileEntry *
1200HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1201 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1202 // module.map at the framework root is also accepted.
1203 SmallString<128> ModuleMapFileName(Dir->getName());
1204 if (IsFramework)
1205 llvm::sys::path::append(ModuleMapFileName, "Modules");
1206 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1207 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1208 return F;
1209
1210 // Continue to allow module.map
1211 ModuleMapFileName = Dir->getName();
1212 llvm::sys::path::append(ModuleMapFileName, "module.map");
1213 return FileMgr.getFile(ModuleMapFileName);
1214}
1215
1216Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001217 const DirectoryEntry *Dir,
1218 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001219 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001220 return Module;
1221
1222 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001223 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001224 case LMM_InvalidModuleMap:
1225 break;
1226
1227 case LMM_AlreadyLoaded:
1228 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001229 return nullptr;
1230
Douglas Gregor56c64012011-11-17 01:41:17 +00001231 case LMM_NewlyLoaded:
1232 return ModMap.findModule(Name);
1233 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001234
Douglas Gregor9194a912012-11-06 19:39:40 +00001235
Ben Langmuirc3ea5652014-03-20 18:27:26 +00001236 // Try to infer a module map from the framework directory.
Craig Topperd2d442c2014-05-17 23:10:59 +00001237 return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001238}
1239
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001240
Douglas Gregor80b69042011-11-12 00:22:19 +00001241HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001242HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1243 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001244 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001245 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001246
Douglas Gregor80b69042011-11-12 00:22:19 +00001247 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001248}
1249
Douglas Gregor80b69042011-11-12 00:22:19 +00001250HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001251HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1252 bool IsFramework) {
1253 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001254 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor80b69042011-11-12 00:22:19 +00001255 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001256
Ben Langmuir984e1df2014-03-19 20:23:34 +00001257 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1258 LoadModuleMapResult Result = loadModuleMapFileImpl(ModuleMapFile, IsSystem);
1259 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1260 // E.g. Foo.framework/Modules/module.modulemap
1261 // ^Dir ^ModuleMapFile
1262 if (Result == LMM_NewlyLoaded)
1263 DirectoryHasModuleMap[Dir] = true;
1264 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001265 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001266 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001267}
Douglas Gregor718292f2011-11-11 19:10:28 +00001268
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001269void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001270 Modules.clear();
1271
1272 // Load module maps for each of the header search directories.
1273 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor963c5532013-06-21 16:28:10 +00001274 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor07f43572012-01-29 18:15:03 +00001275 if (SearchDirs[Idx].isFramework()) {
Rafael Espindolac0809172014-06-12 14:02:15 +00001276 std::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001277 SmallString<128> DirNative;
Douglas Gregor07f43572012-01-29 18:15:03 +00001278 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1279 DirNative);
1280
1281 // Search each of the ".framework" directories to load them as modules.
Douglas Gregor07f43572012-01-29 18:15:03 +00001282 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1283 Dir != DirEnd && !EC; Dir.increment(EC)) {
1284 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1285 continue;
1286
1287 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1288 if (!FrameworkDir)
1289 continue;
1290
1291 // Load this framework module.
1292 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1293 IsSystem);
1294 }
1295 continue;
1296 }
1297
1298 // FIXME: Deal with header maps.
1299 if (SearchDirs[Idx].isHeaderMap())
1300 continue;
1301
1302 // Try to load a module map file for the search directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001303 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, /*IsFramework*/false);
Douglas Gregor07f43572012-01-29 18:15:03 +00001304
1305 // Try to load module map files for immediate subdirectories of this search
1306 // directory.
Douglas Gregor0339a642013-03-21 01:08:50 +00001307 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001308 }
1309
1310 // Populate the list of modules.
1311 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1312 MEnd = ModMap.module_end();
1313 M != MEnd; ++M) {
1314 Modules.push_back(M->getValue());
1315 }
1316}
Douglas Gregor0339a642013-03-21 01:08:50 +00001317
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001318void HeaderSearch::loadTopLevelSystemModules() {
1319 // Load module maps for each of the header search directories.
1320 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001321 // We only care about normal header directories.
1322 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001323 continue;
1324 }
1325
1326 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001327 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001328 SearchDirs[Idx].isSystemHeaderDirectory(),
1329 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001330 }
1331}
1332
Douglas Gregor0339a642013-03-21 01:08:50 +00001333void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1334 if (SearchDir.haveSearchedAllModuleMaps())
1335 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001336
1337 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001338 SmallString<128> DirNative;
1339 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1340 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1341 Dir != DirEnd && !EC; Dir.increment(EC)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001342 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1343 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001344 }
1345
1346 SearchDir.setSearchedAllModuleMaps(true);
1347}