blob: 7a98f5418334f54f10b426d49ff9f0ca02ecd2cb [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"
Richard Smith20e883e2015-04-29 23:20:19 +000021#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000022#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000024#include "llvm/ADT/SmallString.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000025#include "llvm/Support/Capacity.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/Path.h"
Daniel Jasperba7f2f72013-09-24 09:14:14 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000029#include <cstdio>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000030#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000031#include <limits.h>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000032#endif
Chris Lattner59a9ebd2006-10-18 05:34:33 +000033using namespace clang;
34
Douglas Gregor99734e72009-04-25 23:30:02 +000035const IdentifierInfo *
36HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
37 if (ControllingMacro)
38 return ControllingMacro;
39
40 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000041 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000042
43 ControllingMacro = External->GetIdentifier(ControllingMacroID);
44 return ControllingMacro;
45}
46
Douglas Gregor09b69892011-02-10 17:09:37 +000047ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
48
Dmitri Gribenkof8579502013-01-12 19:30:44 +000049HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000050 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000051 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000052 const TargetInfo *Target)
Will Wilsonba2f1462013-12-27 20:02:27 +000053 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
Daniel Jasper21a0f552014-11-25 09:45:48 +000054 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this),
55 LangOpts(LangOpts) {
Nico Weber3b1d1212011-05-24 04:31:14 +000056 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000057 SystemDirIdx = 0;
58 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000059
Craig Topperd2d442c2014-05-17 23:10:59 +000060 ExternalLookup = nullptr;
61 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000062 NumIncluded = 0;
63 NumMultiIncludeFileOptzn = 0;
64 NumFrameworkLookups = NumSubFrameworkLookups = 0;
65}
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 Langmuir9d6448b2014-08-09 00:57:23 +0000117 const FileEntry *ModuleMap =
118 getModuleMap().getModuleMapFileForUniquing(Module);
Ben Langmuird89dc562015-02-19 20:23:22 +0000119 return getModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000120}
121
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000122std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
Ben Langmuird89dc562015-02-19 20:23:22 +0000123 StringRef ModuleMapPath) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000124 // If we don't have a module cache path, we can't do anything.
125 if (ModuleCachePath.empty())
126 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000127
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000128 SmallString<256> Result(ModuleCachePath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000129 llvm::sys::fs::make_absolute(Result);
130
131 if (HSOpts->DisableModuleHash) {
132 llvm::sys::path::append(Result, ModuleName + ".pcm");
133 } else {
134 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000135 // ideally be globally unique to this particular module. Name collisions
136 // in the hash are safe (because any translation unit can only import one
137 // module with each name), but result in a loss of caching.
138 //
139 // To avoid false-negatives, we form as canonical a path as we can, and map
140 // to lower-case in case we're on a case-insensitive file system.
141 auto *Dir =
142 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
143 if (!Dir)
144 return std::string();
145 auto DirName = FileMgr.getCanonicalName(Dir);
146 auto FileName = llvm::sys::path::filename(ModuleMapPath);
147
148 llvm::hash_code Hash =
149 llvm::hash_combine(DirName.lower(), FileName.lower());
150
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000151 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000152 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000153 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000154 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000155 return Result.str().str();
156}
157
158Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000159 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000160 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000161 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000162 return Module;
163
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000164 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000165 // maps, searching for a module map that describes this module.
166 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
167 if (SearchDirs[Idx].isFramework()) {
168 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000169 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000170 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
171 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
172 if (const DirectoryEntry *FrameworkDir
173 = FileMgr.getDirectory(FrameworkDirName)) {
174 bool IsSystem
175 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
176 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000177 if (Module)
178 break;
179 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000180 }
181
182 // FIXME: Figure out how header maps and module maps will work together.
183
184 // Only deal with normal search directories.
185 if (!SearchDirs[Idx].isNormalDir())
186 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000187
188 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000189 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000190 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
191 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000192 // We just loaded a module map file; check whether the module is
193 // available now.
194 Module = ModMap.findModule(ModuleName);
195 if (Module)
196 break;
197 }
198
199 // Search for a module map in a subdirectory with the same name as the
200 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000201 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000202 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
203 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000204 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
205 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000206 // If we just loaded a module map file, look for the module again.
207 Module = ModMap.findModule(ModuleName);
208 if (Module)
209 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000210 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000211
212 // If we've already performed the exhaustive search for module maps in this
213 // search directory, don't do it again.
214 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
215 continue;
216
217 // Load all module maps in the immediate subdirectories of this search
218 // directory.
219 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
220
221 // Look again for the module.
222 Module = ModMap.findModule(ModuleName);
223 if (Module)
224 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000225 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000226
Douglas Gregor279a6c32012-01-29 17:08:11 +0000227 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000228}
229
Chris Lattnerf62f7582007-12-17 07:52:39 +0000230//===----------------------------------------------------------------------===//
231// File lookup within a DirectoryLookup scope
232//===----------------------------------------------------------------------===//
233
Chris Lattner8d720d02007-12-17 17:57:27 +0000234/// getName - Return the directory or filename corresponding to this lookup
235/// object.
236const char *DirectoryLookup::getName() const {
237 if (isNormalDir())
238 return getDir()->getName();
239 if (isFramework())
240 return getFrameworkDir()->getName();
241 assert(isHeaderMap() && "Unknown DirectoryLookup");
242 return getHeaderMap()->getFileName();
243}
244
Richard Smith8c71eba2014-03-05 20:51:45 +0000245static const FileEntry *
246getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
247 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
248 ModuleMap::KnownHeader *SuggestedModule) {
249 // If we have a module map that might map this header, load it and
250 // check whether we'll have a suggestion for a module.
251 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
252 if (SuggestedModule) {
253 const FileEntry *File = HS.getFileMgr().getFile(FileName,
254 /*OpenFile=*/false);
255 if (File) {
256 // If there is a module that corresponds to this header, suggest it.
257 *SuggestedModule = HS.findModuleForHeader(File);
258
259 // FIXME: This appears to be a no-op. We loaded the module map for this
260 // directory at the start of this function.
261 if (!SuggestedModule->getModule() &&
262 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
263 *SuggestedModule = HS.findModuleForHeader(File);
264 }
265
266 return File;
267 }
268
269 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
270}
Chris Lattner8d720d02007-12-17 17:57:27 +0000271
Chris Lattnerf62f7582007-12-17 07:52:39 +0000272/// LookupFile - Lookup the specified file in this search path, returning it
273/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000274const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000275 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000276 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000277 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000278 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000279 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000280 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000281 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000282 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000283 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000284 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000285
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000286 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000287 if (isNormalDir()) {
288 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000289 TmpDir = getDir()->getName();
290 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000291 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000292 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000293 SearchPath->clear();
294 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
295 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000296 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000297 RelativePath->clear();
298 RelativePath->append(Filename.begin(), Filename.end());
299 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000300
Yaron Keren92e1b622015-03-18 10:17:07 +0000301 return getFileAndSuggestModule(HS, TmpDir, getDir(),
Richard Smith8c71eba2014-03-05 20:51:45 +0000302 isSystemHeaderDirectory(),
303 SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000304 }
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner712e3872007-12-17 08:13:48 +0000306 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000307 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000308 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000309
Chris Lattner44bd21b2007-12-17 08:17:39 +0000310 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000311 const HeaderMap *HM = getHeaderMap();
312 SmallString<1024> Path;
313 StringRef Dest = HM->lookupFilename(Filename, Path);
314 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000315 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000316
317 const FileEntry *Result;
318
319 // Check if the headermap maps the filename to a framework include
320 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
321 // framework include.
322 if (llvm::sys::path::is_relative(Dest)) {
323 MappedName.clear();
324 MappedName.append(Dest.begin(), Dest.end());
325 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000326 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000327 Result = HM->LookupFile(Filename, HS.getFileMgr());
328
329 } else {
330 Result = HS.getFileMgr().getFile(Dest);
331 }
332
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000333 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000334 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000336 SearchPath->clear();
337 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
338 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000339 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000340 RelativePath->clear();
341 RelativePath->append(Filename.begin(), Filename.end());
342 }
343 }
344 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000345}
346
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000347/// \brief Given a framework directory, find the top-most framework directory.
348///
349/// \param FileMgr The file manager to use for directory lookups.
350/// \param DirName The name of the framework directory.
351/// \param SubmodulePath Will be populated with the submodule path from the
352/// returned top-level module to the originally named framework.
353static const DirectoryEntry *
354getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
355 SmallVectorImpl<std::string> &SubmodulePath) {
356 assert(llvm::sys::path::extension(DirName) == ".framework" &&
357 "Not a framework directory");
358
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000359 // Note: as an egregious but useful hack we use the real path here, because
360 // frameworks moving between top-level frameworks to embedded frameworks tend
361 // to be symlinked, and we base the logical structure of modules on the
362 // physical layout. In particular, we need to deal with crazy includes like
363 //
364 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
365 //
366 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
367 // which one should access with, e.g.,
368 //
369 // #include <Bar/Wibble.h>
370 //
371 // Similar issues occur when a top-level framework has moved into an
372 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000373 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000374 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000375 do {
376 // Get the parent directory name.
377 DirName = llvm::sys::path::parent_path(DirName);
378 if (DirName.empty())
379 break;
380
381 // Determine whether this directory exists.
382 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
383 if (!Dir)
384 break;
385
386 // If this is a framework directory, then we're a subframework of this
387 // framework.
388 if (llvm::sys::path::extension(DirName) == ".framework") {
389 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
390 TopFrameworkDir = Dir;
391 }
392 } while (true);
393
394 return TopFrameworkDir;
395}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000396
Chris Lattner712e3872007-12-17 08:13:48 +0000397/// DoFrameworkLookup - Do a lookup of the specified file in the current
398/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000399const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000400 StringRef Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000401 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000402 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000403 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000404 ModuleMap::KnownHeader *SuggestedModule,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000405 bool &InUserSpecifiedSystemFramework) const
Douglas Gregor97eec242011-09-15 22:00:41 +0000406{
Chris Lattner712e3872007-12-17 08:13:48 +0000407 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000409 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000410 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000411 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner712e3872007-12-17 08:13:48 +0000413 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000414 // HeaderSearch. Possible answers are yes/no and unknown.
415 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000416 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattner712e3872007-12-17 08:13:48 +0000418 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000419 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000420 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattner712e3872007-12-17 08:13:48 +0000422 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000424 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000425 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000426 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000427 if (FrameworkName.empty() || FrameworkName.back() != '/')
428 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000430 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000431 StringRef ModuleName(Filename.begin(), SlashPos);
432 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000434 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
435 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000436
Daniel Dunbar17138612012-04-05 17:09:40 +0000437 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000438 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000439 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000440
Chris Lattner5ed76da2006-10-22 07:24:13 +0000441 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000442 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000443 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000444
Chris Lattner5ed76da2006-10-22 07:24:13 +0000445 // Otherwise, if it does, remember that this is the right direntry for this
446 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000447 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000448
449 // If this is a user search directory, check if the framework has been
450 // user-specified as a system framework.
451 if (getDirCharacteristic() == SrcMgr::C_User) {
452 SmallString<1024> SystemFrameworkMarker(FrameworkName);
453 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000454 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000455 CacheEntry.IsUserSpecifiedSystemFramework = true;
456 }
457 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000458 }
Mike Stump11289f42009-09-09 15:08:12 +0000459
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000460 // Set the 'user-specified system framework' flag.
461 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
462
Craig Topperd2d442c2014-05-17 23:10:59 +0000463 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000464 RelativePath->clear();
465 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
466 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000467
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000468 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000469 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000470
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000471 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000472
Craig Topperd2d442c2014-05-17 23:10:59 +0000473 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000474 SearchPath->clear();
475 // Without trailing '/'.
476 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
477 }
478
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000479 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000480 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000481 /*openFile=*/!SuggestedModule);
482 if (!FE) {
483 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
484 const char *Private = "Private";
485 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
486 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000487 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000488 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
489 Private+strlen(Private));
490
Yaron Keren92e1b622015-03-18 10:17:07 +0000491 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000492 }
Mike Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000494 // If we found the header and are allowed to suggest a module, do so now.
495 if (FE && SuggestedModule) {
496 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000497 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000498 bool FoundFramework = false;
499 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000500 // Determine whether this directory exists.
501 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
502 if (!Dir)
503 break;
504
505 // If this is a framework directory, then we're a subframework of this
506 // framework.
507 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
508 FoundFramework = true;
509 break;
510 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000511
512 // Get the parent directory name.
513 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
514 if (FrameworkPath.empty())
515 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000516 } while (true);
517
518 if (FoundFramework) {
519 // Find the top-level framework based on this framework.
520 SmallVector<std::string, 4> SubmodulePath;
521 const DirectoryEntry *TopFrameworkDir
522 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
523
524 // Determine the name of the top-level framework.
525 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
526
527 // Load this framework module. If that succeeds, find the suggested module
528 // for this header, if any.
529 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
530 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
531 *SuggestedModule = HS.findModuleForHeader(FE);
532 }
533 } else {
534 *SuggestedModule = HS.findModuleForHeader(FE);
535 }
536 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000537 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000538}
539
Douglas Gregor89929282012-01-30 06:01:29 +0000540void HeaderSearch::setTarget(const TargetInfo &Target) {
541 ModMap.setTarget(Target);
542}
543
Chris Lattnerf62f7582007-12-17 07:52:39 +0000544
Chris Lattner712e3872007-12-17 08:13:48 +0000545//===----------------------------------------------------------------------===//
546// Header File Location.
547//===----------------------------------------------------------------------===//
548
Reid Klecknera97d4c02014-02-18 23:49:24 +0000549/// \brief Return true with a diagnostic if the file that MSVC would have found
550/// fails to match the one that Clang would have found with MSVC header search
551/// disabled.
552static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
553 const FileEntry *MSFE, const FileEntry *FE,
554 SourceLocation IncludeLoc) {
555 if (MSFE && FE != MSFE) {
556 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
557 return true;
558 }
559 return false;
560}
Chris Lattner712e3872007-12-17 08:13:48 +0000561
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000562static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
563 assert(!Str.empty());
564 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
565 std::copy(Str.begin(), Str.end(), CopyStr);
566 CopyStr[Str.size()] = '\0';
567 return CopyStr;
568}
569
James Dennettc07ab2c2012-06-20 00:56:32 +0000570/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000571/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000572/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
573/// non-empty, indicates where the \#including file(s) are, in case a relative
574/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000575const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000576 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
577 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
579 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Will Wilson0fafd342013-12-27 19:46:16 +0000580 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
Douglas Gregor97eec242011-09-15 22:00:41 +0000581 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000582 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000583
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000584 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000585 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000586 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000587
588 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000589 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000590
Craig Topperd2d442c2014-05-17 23:10:59 +0000591 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000592 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000593 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000594 RelativePath->clear();
595 RelativePath->append(Filename.begin(), Filename.end());
596 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000597 // Otherwise, just return the file.
Richard Smitha0aafa32015-05-18 03:52:30 +0000598 const FileEntry *File = FileMgr.getFile(Filename, /*openFile=*/true);
599 if (File && SuggestedModule) {
600 // If there is a module that corresponds to this header, suggest it.
601 hasModuleMap(Filename, File->getDir(), /*SystemHeaderDir*/false);
602 *SuggestedModule = findModuleForHeader(File);
603 }
604 return File;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Reid Klecknera97d4c02014-02-18 23:49:24 +0000607 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000608 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000609 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000610
Douglas Gregor9f93e382011-07-28 04:45:53 +0000611 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000612 // directory. This cannot be based on CurDir, because each includer could be
613 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
614 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000615 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000616 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000617 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000618 bool First = true;
619 for (const auto &IncluderAndDir : Includers) {
620 const FileEntry *Includer = IncluderAndDir.first;
621
Will Wilson0fafd342013-12-27 19:46:16 +0000622 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000623 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000624 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000625 TmpDir.push_back('/');
626 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000627
Richard Smith6f548ec2014-03-06 18:08:08 +0000628 // FIXME: We don't cache the result of getFileInfo across the call to
629 // getFileAndSuggestModule, because it's a reference to an element of
630 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000631 //
632 // FIXME: If we have no includer, that means we're processing a #include
633 // from a module build. We should treat this as a system header if we're
634 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000635 bool IncluderIsSystemHeader =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000636 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000637 if (const FileEntry *FE = getFileAndSuggestModule(
Yaron Keren92e1b622015-03-18 10:17:07 +0000638 *this, TmpDir, IncluderAndDir.second,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000639 IncluderIsSystemHeader, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000640 if (!Includer) {
641 assert(First && "only first includer can have no file");
642 return FE;
643 }
644
Will Wilson0fafd342013-12-27 19:46:16 +0000645 // Leave CurDir unset.
646 // This file is a system header or C++ unfriendly if the old file is.
647 //
648 // Note that we only use one of FromHFI/ToHFI at once, due to potential
649 // reallocation of the underlying vector potentially making the first
650 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000651 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000652 unsigned DirInfo = FromHFI.DirInfo;
653 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
654 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000655
Will Wilson0fafd342013-12-27 19:46:16 +0000656 HeaderFileInfo &ToHFI = getFileInfo(FE);
657 ToHFI.DirInfo = DirInfo;
658 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
659 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000660
Craig Topperd2d442c2014-05-17 23:10:59 +0000661 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000662 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000663 SearchPath->clear();
664 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
665 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000666 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000667 RelativePath->clear();
668 RelativePath->append(Filename.begin(), Filename.end());
669 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000670 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000671 return FE;
672
673 // Otherwise, we found the path via MSVC header search rules. If
674 // -Wmsvc-include is enabled, we have to keep searching to see if we
675 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000676 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000677 return FE;
678 } else {
679 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000680 if (SuggestedModule) {
681 MSSuggestedModule = *SuggestedModule;
682 *SuggestedModule = ModuleMap::KnownHeader();
683 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000684 break;
685 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000686 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000687 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000688 }
689 }
Mike Stump11289f42009-09-09 15:08:12 +0000690
Craig Topperd2d442c2014-05-17 23:10:59 +0000691 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000692
693 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000694 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000696 // If this is a #include_next request, start searching after the directory the
697 // file was found in.
698 if (FromDir)
699 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000700
Chris Lattnerd4275422007-07-22 07:28:00 +0000701 // Cache all of the lookups performed by this method. Many headers are
702 // multiply included, and the "pragma once" optimization prevents them from
703 // being relex/pp'd, but they would still have to search through a
704 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000705 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000706
707 // If the entry has been previously looked up, the first value will be
708 // non-zero. If the value is equal to i (the start point of our search), then
709 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000710 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000711 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000712 i = CacheLookup.HitIdx;
713 if (CacheLookup.MappedName)
714 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000715 } else {
716 // Otherwise, this is the first query, or the previous query didn't match
717 // our search start. We will fill in our found location below, so prime the
718 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000719 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000720 }
Mike Stump11289f42009-09-09 15:08:12 +0000721
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000722 SmallString<64> MappedName;
723
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000724 // Check each directory in sequence to see if it contains this file.
725 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000726 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000727 bool HasBeenMapped = false;
Mike Stump11289f42009-09-09 15:08:12 +0000728 const FileEntry *FE =
Douglas Gregor97eec242011-09-15 22:00:41 +0000729 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000730 SuggestedModule, InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000731 HasBeenMapped, MappedName);
732 if (HasBeenMapped) {
733 CacheLookup.MappedName =
734 copyString(Filename, LookupFileCache.getAllocator());
735 }
Chris Lattner712e3872007-12-17 08:13:48 +0000736 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner712e3872007-12-17 08:13:48 +0000738 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000739
Chris Lattner712e3872007-12-17 08:13:48 +0000740 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000741 HeaderFileInfo &HFI = getFileInfo(FE);
742 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000743
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000744 // If the directory characteristic is User but this framework was
745 // user-specified to be treated as a system framework, promote the
746 // characteristic.
747 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
748 HFI.DirInfo = SrcMgr::C_System;
749
Richard Smith8acadcb2012-06-13 20:27:03 +0000750 // If the filename matches a known system header prefix, override
751 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000752 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
753 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
754 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000755 : SrcMgr::C_User;
756 break;
757 }
758 }
759
Douglas Gregor9f93e382011-07-28 04:45:53 +0000760 // If this file is found in a header map and uses the framework style of
761 // includes, then this header is part of a framework we're building.
762 if (CurDir->isIndexHeaderMap()) {
763 size_t SlashPos = Filename.find('/');
764 if (SlashPos != StringRef::npos) {
765 HFI.IndexHeaderMapHeader = 1;
766 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
767 SlashPos));
768 }
769 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000770
Richard Smith8c71eba2014-03-05 20:51:45 +0000771 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
772 if (SuggestedModule)
773 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000774 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000775 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000776
Chris Lattner712e3872007-12-17 08:13:48 +0000777 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000778 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000779 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000780 }
Mike Stump11289f42009-09-09 15:08:12 +0000781
Douglas Gregord8575e12011-07-30 06:28:34 +0000782 // If we are including a file with a quoted include "foo.h" from inside
783 // a header in a framework that is currently being built, and we couldn't
784 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
785 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000786 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000787 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000788 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000789 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000790 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000791 ScratchFilename += IncludingHFI.Framework;
792 ScratchFilename += '/';
793 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000794
Reid Klecknera97d4c02014-02-18 23:49:24 +0000795 const FileEntry *FE = LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000796 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
797 Includers.front(), SearchPath, RelativePath, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000798
Richard Smith8c71eba2014-03-05 20:51:45 +0000799 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
800 if (SuggestedModule)
801 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000802 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000803 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000804
David Blaikie3c8c46e2014-11-19 05:48:40 +0000805 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000806 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000807 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000808 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000809 }
810 }
811
Craig Topperd2d442c2014-05-17 23:10:59 +0000812 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000813 if (SuggestedModule)
814 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000815 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000816 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000817
Chris Lattnerd4275422007-07-22 07:28:00 +0000818 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000819 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000820 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000821}
822
Chris Lattner63dd32b2006-10-20 04:42:40 +0000823/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000824/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000825/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
826/// is a subframework within Carbon.framework. If so, return the FileEntry
827/// for the designated file, otherwise return null.
828const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000829LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000830 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000831 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000832 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000833 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000834 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattner63dd32b2006-10-20 04:42:40 +0000836 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000837 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000838 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000839 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000840
Chris Lattner63dd32b2006-10-20 04:42:40 +0000841 // Look up the base framework name of the ContextFileEnt.
Chris Lattner48043482006-10-27 05:12:36 +0000842 const char *ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000843
Chris Lattner63dd32b2006-10-20 04:42:40 +0000844 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000845 const unsigned DotFrameworkLen = 10;
846 const char *FrameworkPos = strstr(ContextName, ".framework");
Craig Topperd2d442c2014-05-17 23:10:59 +0000847 if (FrameworkPos == nullptr ||
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000848 (FrameworkPos[DotFrameworkLen] != '/' &&
849 FrameworkPos[DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000850 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000851
Daniel Dunbar17138612012-04-05 17:09:40 +0000852 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000853
Chris Lattner63dd32b2006-10-20 04:42:40 +0000854 // Append Frameworks/HIToolbox.framework/
855 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000856 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000857 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000858
David Blaikie13156b62014-11-19 03:06:06 +0000859 auto &CacheLookup =
860 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
861 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattner5ed76da2006-10-22 07:24:13 +0000863 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000864 if (CacheLookup.second.Directory &&
865 CacheLookup.first().size() == FrameworkName.size() &&
866 memcmp(CacheLookup.first().data(), &FrameworkName[0],
867 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000868 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattner5ed76da2006-10-22 07:24:13 +0000870 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000871 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000872 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Chris Lattner5ed76da2006-10-22 07:24:13 +0000874 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000875 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000876 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattner5ed76da2006-10-22 07:24:13 +0000878 // Otherwise, if it does, remember that this is the right direntry for this
879 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000880 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000881 }
Mike Stump11289f42009-09-09 15:08:12 +0000882
Craig Topperd2d442c2014-05-17 23:10:59 +0000883 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000884
Craig Topperd2d442c2014-05-17 23:10:59 +0000885 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000886 RelativePath->clear();
887 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
888 }
889
Chris Lattner63dd32b2006-10-20 04:42:40 +0000890 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000891 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000892 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000893 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000894 SearchPath->clear();
895 // Without trailing '/'.
896 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
897 }
898
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000899 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000900 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattner63dd32b2006-10-20 04:42:40 +0000902 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000903 HeadersFilename = FrameworkName;
904 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000905 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000906 SearchPath->clear();
907 // Without trailing '/'.
908 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
909 }
910
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000911 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000912 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000913 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Chris Lattner577377e2006-10-20 04:55:45 +0000916 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000917 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000918 // Note that the temporary 'DirInfo' is required here, as either call to
919 // getFileInfo could resize the vector and we don't want to rely on order
920 // of evaluation.
921 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
922 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000923
924 // If we're supposed to suggest a module, look for one now.
925 if (SuggestedModule) {
926 // Find the top-level framework based on this framework.
927 FrameworkName.pop_back(); // remove the trailing '/'
928 SmallVector<std::string, 4> SubmodulePath;
929 const DirectoryEntry *TopFrameworkDir
930 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
931
932 // Determine the name of the top-level framework.
933 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
934
935 // Load this framework module. If that succeeds, find the suggested module
936 // for this header, if any.
937 bool IsSystem = false;
938 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
939 *SuggestedModule = findModuleForHeader(FE);
940 }
941 }
942
Chris Lattner577377e2006-10-20 04:55:45 +0000943 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000944}
945
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000946//===----------------------------------------------------------------------===//
947// File Info Management.
948//===----------------------------------------------------------------------===//
949
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000950/// \brief Merge the header file info provided by \p OtherHFI into the current
951/// header file info (\p HFI)
952static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
953 const HeaderFileInfo &OtherHFI) {
954 HFI.isImport |= OtherHFI.isImport;
955 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000956 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000957 HFI.NumIncludes += OtherHFI.NumIncludes;
958
959 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
960 HFI.ControllingMacro = OtherHFI.ControllingMacro;
961 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
962 }
963
964 if (OtherHFI.External) {
965 HFI.DirInfo = OtherHFI.DirInfo;
966 HFI.External = OtherHFI.External;
967 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
968 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000969
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000970 if (HFI.Framework.empty())
971 HFI.Framework = OtherHFI.Framework;
972
973 HFI.Resolved = true;
974}
975
Steve Naroff3fa455a2009-04-24 20:03:17 +0000976/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000977/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000978HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000979 if (FE->getUID() >= FileInfo.size())
980 FileInfo.resize(FE->getUID()+1);
Douglas Gregor09b69892011-02-10 17:09:37 +0000981
982 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000983 if (ExternalSource && !HFI.Resolved)
984 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Ben Langmuird285c502014-03-13 16:46:36 +0000985 HFI.IsValid = 1;
Douglas Gregor09b69892011-02-10 17:09:37 +0000986 return HFI;
Mike Stump11289f42009-09-09 15:08:12 +0000987}
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000988
Ben Langmuird285c502014-03-13 16:46:36 +0000989bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
990 if (FE->getUID() >= FileInfo.size())
991 return false;
992 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
993 if (HFI.IsValid) {
994 Result = HFI;
995 return true;
996 }
997 return false;
998}
999
Douglas Gregor37aa4932011-05-04 00:14:37 +00001000bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1001 // Check if we've ever seen this file as a header.
1002 if (File->getUID() >= FileInfo.size())
1003 return false;
1004
1005 // Resolve header file info from the external source, if needed.
1006 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001007 if (ExternalSource && !HFI.Resolved)
1008 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregor37aa4932011-05-04 00:14:37 +00001009
Argyrios Kyrtzidis0d355df2012-12-10 20:08:37 +00001010 return HFI.isPragmaOnce || HFI.isImport ||
1011 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001012}
1013
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001014void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001015 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001016 bool isCompilingModuleHeader) {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001017 if (FE->getUID() >= FileInfo.size())
1018 FileInfo.resize(FE->getUID()+1);
1019
1020 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1021 HFI.isModuleHeader = true;
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001022 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001023 HFI.setHeaderRole(Role);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001024}
1025
Richard Smith20e883e2015-04-29 23:20:19 +00001026bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1027 const FileEntry *File,
1028 bool isImport) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001029 ++NumIncluded; // Count # of attempted #includes.
1030
1031 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001032 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001034 // If this is a #import directive, check that we have not already imported
1035 // this header.
1036 if (isImport) {
1037 // If this has already been imported, don't import it again.
1038 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001040 // Has this already been #import'ed or #include'd?
1041 if (FileInfo.NumIncludes) return false;
1042 } else {
1043 // Otherwise, if this is a #include of a file that was previously #import'd
1044 // or if this is the second #include of a #pragma once file, ignore it.
1045 if (FileInfo.isImport)
1046 return false;
1047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001049 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1050 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001051 if (const IdentifierInfo *ControllingMacro
Douglas Gregor99734e72009-04-25 23:30:02 +00001052 = FileInfo.getControllingMacro(ExternalLookup))
Richard Smith20e883e2015-04-29 23:20:19 +00001053 if (PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001054 ++NumMultiIncludeFileOptzn;
1055 return false;
1056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001058 // Increment the number of times this file has been included.
1059 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001061 return true;
1062}
1063
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001064size_t HeaderSearch::getTotalMemory() const {
1065 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001066 + llvm::capacity_in_bytes(FileInfo)
1067 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001068 + LookupFileCache.getAllocator().getTotalMemory()
1069 + FrameworkMap.getAllocator().getTotalMemory();
1070}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001071
1072StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001073 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001074}
Douglas Gregor718292f2011-11-11 19:10:28 +00001075
1076bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001077 const DirectoryEntry *Root,
1078 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001079 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001080 return false;
1081
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001082 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001083
1084 StringRef DirName = FileName;
1085 do {
1086 // Get the parent directory name.
1087 DirName = llvm::sys::path::parent_path(DirName);
1088 if (DirName.empty())
1089 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001090
Douglas Gregor718292f2011-11-11 19:10:28 +00001091 // Determine whether this directory exists.
1092 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1093 if (!Dir)
1094 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001095
Ben Langmuir984e1df2014-03-19 20:23:34 +00001096 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001097 switch (loadModuleMapFile(Dir, IsSystem,
1098 llvm::sys::path::extension(Dir->getName()) ==
1099 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001100 case LMM_NewlyLoaded:
1101 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001102 // Success. All of the directories we stepped through inherit this module
1103 // map file.
1104 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1105 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1106 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001107
1108 case LMM_NoDirectory:
1109 case LMM_InvalidModuleMap:
1110 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001111 }
1112
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001113 // If we hit the top of our search, we're done.
1114 if (Dir == Root)
1115 return false;
1116
Douglas Gregor718292f2011-11-11 19:10:28 +00001117 // Keep track of all of the directories we checked, so we can mark them as
1118 // having module maps if we eventually do find a module map.
1119 FixUpDirectories.push_back(Dir);
1120 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001121}
1122
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001123ModuleMap::KnownHeader
1124HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001125 if (ExternalSource) {
1126 // Make sure the external source has handled header info about this file,
1127 // which includes whether the file is part of a module.
1128 (void)getFileInfo(File);
1129 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001130 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001131}
1132
Richard Smith9acb99e32014-12-10 03:09:48 +00001133static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001134 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001135 StringRef Filename = llvm::sys::path::filename(File->getName());
1136 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001137 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001138 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001139 else if (Filename == "module.modulemap")
1140 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1141 else
1142 return nullptr;
1143 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001144}
1145
Ben Langmuir984e1df2014-03-19 20:23:34 +00001146bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001147 // Find the directory for the module. For frameworks, that may require going
1148 // up from the 'Modules' directory.
1149 const DirectoryEntry *Dir = nullptr;
1150 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1151 Dir = FileMgr.getDirectory(".");
1152 else {
1153 Dir = File->getDir();
1154 StringRef DirName(Dir->getName());
1155 if (llvm::sys::path::filename(DirName) == "Modules") {
1156 DirName = llvm::sys::path::parent_path(DirName);
1157 if (DirName.endswith(".framework"))
1158 Dir = FileMgr.getDirectory(DirName);
1159 // FIXME: This assert can fail if there's a race between the above check
1160 // and the removal of the directory.
1161 assert(Dir && "parent must exist");
1162 }
1163 }
1164
1165 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001166 case LMM_AlreadyLoaded:
1167 case LMM_NewlyLoaded:
1168 return false;
1169 case LMM_NoDirectory:
1170 case LMM_InvalidModuleMap:
1171 return true;
1172 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001173 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001174}
1175
1176HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001177HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1178 const DirectoryEntry *Dir) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001179 assert(File && "expected FileEntry");
1180
Richard Smith9887d792014-10-17 01:42:53 +00001181 // Check whether we've already loaded this module map, and mark it as being
1182 // loaded in case we recursively try to load it from itself.
1183 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1184 if (!AddResult.second)
1185 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001186
Richard Smith9acb99e32014-12-10 03:09:48 +00001187 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001188 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001189 return LMM_InvalidModuleMap;
1190 }
1191
1192 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001193 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1194 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001195 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001196 return LMM_InvalidModuleMap;
1197 }
1198 }
1199
1200 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001201 return LMM_NewlyLoaded;
1202}
1203
1204const FileEntry *
1205HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001206 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001207 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001208 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1209 // module.map at the framework root is also accepted.
1210 SmallString<128> ModuleMapFileName(Dir->getName());
1211 if (IsFramework)
1212 llvm::sys::path::append(ModuleMapFileName, "Modules");
1213 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1214 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1215 return F;
1216
1217 // Continue to allow module.map
1218 ModuleMapFileName = Dir->getName();
1219 llvm::sys::path::append(ModuleMapFileName, "module.map");
1220 return FileMgr.getFile(ModuleMapFileName);
1221}
1222
1223Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001224 const DirectoryEntry *Dir,
1225 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001226 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001227 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001228
Douglas Gregor56c64012011-11-17 01:41:17 +00001229 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001230 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001231 case LMM_InvalidModuleMap:
1232 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001233
Douglas Gregor56c64012011-11-17 01:41:17 +00001234 case LMM_AlreadyLoaded:
1235 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001236 return nullptr;
1237
Douglas Gregor56c64012011-11-17 01:41:17 +00001238 case LMM_NewlyLoaded:
1239 return ModMap.findModule(Name);
1240 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001241
Douglas Gregor9194a912012-11-06 19:39:40 +00001242
Ben Langmuirc3ea5652014-03-20 18:27:26 +00001243 // Try to infer a module map from the framework directory.
Richard Smith47972af2015-06-16 00:08:24 +00001244 if (HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001245 return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
1246
1247 return nullptr;
Douglas Gregor56c64012011-11-17 01:41:17 +00001248}
1249
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001250
Douglas Gregor80b69042011-11-12 00:22:19 +00001251HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001252HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1253 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001254 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001255 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001256
Douglas Gregor80b69042011-11-12 00:22:19 +00001257 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001258}
1259
Douglas Gregor80b69042011-11-12 00:22:19 +00001260HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001261HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1262 bool IsFramework) {
1263 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001264 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001265 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001266
Ben Langmuir984e1df2014-03-19 20:23:34 +00001267 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001268 LoadModuleMapResult Result =
1269 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001270 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1271 // E.g. Foo.framework/Modules/module.modulemap
1272 // ^Dir ^ModuleMapFile
1273 if (Result == LMM_NewlyLoaded)
1274 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001275 else if (Result == LMM_InvalidModuleMap)
1276 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001277 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001278 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001279 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001280}
Douglas Gregor718292f2011-11-11 19:10:28 +00001281
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001282void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001283 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001284
Richard Smith47972af2015-06-16 00:08:24 +00001285 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001286 // Load module maps for each of the header search directories.
1287 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1288 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1289 if (SearchDirs[Idx].isFramework()) {
1290 std::error_code EC;
1291 SmallString<128> DirNative;
1292 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1293 DirNative);
1294
1295 // Search each of the ".framework" directories to load them as modules.
Yaron Keren92e1b622015-03-18 10:17:07 +00001296 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001297 Dir != DirEnd && !EC; Dir.increment(EC)) {
1298 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1299 continue;
1300
1301 const DirectoryEntry *FrameworkDir =
1302 FileMgr.getDirectory(Dir->path());
1303 if (!FrameworkDir)
1304 continue;
1305
1306 // Load this framework module.
1307 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1308 IsSystem);
1309 }
1310 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001311 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001312
1313 // FIXME: Deal with header maps.
1314 if (SearchDirs[Idx].isHeaderMap())
1315 continue;
1316
1317 // Try to load a module map file for the search directory.
1318 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1319 /*IsFramework*/ false);
1320
1321 // Try to load module map files for immediate subdirectories of this
1322 // search directory.
1323 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001324 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001325 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001326
Douglas Gregor07f43572012-01-29 18:15:03 +00001327 // Populate the list of modules.
1328 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1329 MEnd = ModMap.module_end();
1330 M != MEnd; ++M) {
1331 Modules.push_back(M->getValue());
1332 }
1333}
Douglas Gregor0339a642013-03-21 01:08:50 +00001334
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001335void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001336 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001337 return;
1338
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001339 // Load module maps for each of the header search directories.
1340 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001341 // We only care about normal header directories.
1342 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001343 continue;
1344 }
1345
1346 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001347 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001348 SearchDirs[Idx].isSystemHeaderDirectory(),
1349 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001350 }
1351}
1352
Douglas Gregor0339a642013-03-21 01:08:50 +00001353void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001354 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001355 "Should not be loading subdirectory module maps");
1356
Douglas Gregor0339a642013-03-21 01:08:50 +00001357 if (SearchDir.haveSearchedAllModuleMaps())
1358 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001359
1360 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001361 SmallString<128> DirNative;
1362 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Yaron Keren92e1b622015-03-18 10:17:07 +00001363 for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001364 Dir != DirEnd && !EC; Dir.increment(EC)) {
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001365 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1366 if (IsFramework == SearchDir.isFramework())
1367 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1368 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001369 }
1370
1371 SearchDir.setSearchedAllModuleMaps(true);
1372}