blob: 1ebcc0a1c657c835e702ad67657f075ba121719f [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"
Richard Smith2aedca32015-07-01 02:29:35 +000017#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderMap.h"
19#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000020#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000021#include "clang/Lex/Lexer.h"
Richard Smith20e883e2015-04-29 23:20:19 +000022#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000025#include "llvm/ADT/SmallString.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000026#include "llvm/Support/Capacity.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/Path.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000029#include <cstdio>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000030#include <utility>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000031#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000032#include <limits.h>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000033#endif
Chris Lattner59a9ebd2006-10-18 05:34:33 +000034using namespace clang;
35
Douglas Gregor99734e72009-04-25 23:30:02 +000036const IdentifierInfo *
Richard Smith2aedca32015-07-01 02:29:35 +000037HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
38 if (ControllingMacro) {
Chandler Carruth59666772016-11-04 06:32:57 +000039 if (ControllingMacro->isOutOfDate()) {
40 assert(External && "We must have an external source if we have a "
41 "controlling macro that is out of date.");
Richard Smith2aedca32015-07-01 02:29:35 +000042 External->updateOutOfDateIdentifier(
43 *const_cast<IdentifierInfo *>(ControllingMacro));
Chandler Carruth59666772016-11-04 06:32:57 +000044 }
Douglas Gregor99734e72009-04-25 23:30:02 +000045 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000046 }
Douglas Gregor99734e72009-04-25 23:30:02 +000047
48 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000049 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000050
51 ControllingMacro = External->GetIdentifier(ControllingMacroID);
52 return ControllingMacro;
53}
54
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000055ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
Douglas Gregor09b69892011-02-10 17:09:37 +000056
David Blaikie9c28cb32017-01-06 01:04:46 +000057HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000058 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000059 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000060 const TargetInfo *Target)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000061 : HSOpts(std::move(HSOpts)), Diags(Diags),
62 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
63 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
Nico Weber3b1d1212011-05-24 04:31:14 +000064 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000065 SystemDirIdx = 0;
66 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000067
Craig Topperd2d442c2014-05-17 23:10:59 +000068 ExternalLookup = nullptr;
69 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000070 NumIncluded = 0;
71 NumMultiIncludeFileOptzn = 0;
72 NumFrameworkLookups = NumSubFrameworkLookups = 0;
73}
74
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000075HeaderSearch::~HeaderSearch() {
76 // Delete headermaps.
77 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
78 delete HeaderMaps[i].second;
79}
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner59a9ebd2006-10-18 05:34:33 +000081void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000082 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
83 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000084 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
85 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
86 NumOnceOnlyFiles += FileInfo[i].isImport;
87 if (MaxNumIncludes < FileInfo[i].NumIncludes)
88 MaxNumIncludes = FileInfo[i].NumIncludes;
89 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
90 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000091 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
92 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
93 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner23b7eb62007-06-15 23:05:46 +000095 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
96 fprintf(stderr, " %d #includes skipped due to"
97 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000098
Chris Lattner23b7eb62007-06-15 23:05:46 +000099 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
100 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000101}
102
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000103/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000104/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000105const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000106 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000107 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000108 if (!HeaderMaps.empty()) {
109 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000110 // Pointer equality comparison of FileEntries works because they are
111 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000112 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000113 return HeaderMaps[i].second;
114 }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Chris Lattner5159f612010-11-23 08:35:12 +0000116 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000117 HeaderMaps.push_back(std::make_pair(FE, HM));
118 return HM;
119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Craig Topperd2d442c2014-05-17 23:10:59 +0000121 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000122}
123
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000124/// \brief Get filenames for all registered header maps.
125void HeaderSearch::getHeaderMapFileNames(
126 SmallVectorImpl<std::string> &Names) const {
127 for (auto &HM : HeaderMaps)
128 Names.push_back(HM.first->getName());
129}
130
Douglas Gregor279a6c32012-01-29 17:08:11 +0000131std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000132 const FileEntry *ModuleMap =
133 getModuleMap().getModuleMapFileForUniquing(Module);
Manman Ren11f2a472016-08-18 17:42:15 +0000134 return getModuleFileName(Module->Name, ModuleMap->getName(),
135 /*UsePrebuiltPath*/false);
Douglas Gregor279a6c32012-01-29 17:08:11 +0000136}
137
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000138std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
Manman Ren11f2a472016-08-18 17:42:15 +0000139 StringRef ModuleMapPath,
140 bool UsePrebuiltPath) {
141 if (UsePrebuiltPath) {
142 if (HSOpts->PrebuiltModulePaths.empty())
143 return std::string();
144
145 // Go though each prebuilt module path and try to find the pcm file.
146 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
147 SmallString<256> Result(Dir);
148 llvm::sys::fs::make_absolute(Result);
149
150 llvm::sys::path::append(Result, ModuleName + ".pcm");
151 if (getFileMgr().getFile(Result.str()))
152 return Result.str().str();
153 }
154 return std::string();
155 }
156
Richard Smithd520a252015-07-21 18:07:47 +0000157 // If we don't have a module cache path or aren't supposed to use one, we
158 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000159 if (getModuleCachePath().empty())
Douglas Gregor279a6c32012-01-29 17:08:11 +0000160 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000161
Richard Smith3938f0c2015-08-15 00:34:15 +0000162 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000163 llvm::sys::fs::make_absolute(Result);
164
165 if (HSOpts->DisableModuleHash) {
166 llvm::sys::path::append(Result, ModuleName + ".pcm");
167 } else {
168 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000169 // ideally be globally unique to this particular module. Name collisions
170 // in the hash are safe (because any translation unit can only import one
171 // module with each name), but result in a loss of caching.
172 //
173 // To avoid false-negatives, we form as canonical a path as we can, and map
174 // to lower-case in case we're on a case-insensitive file system.
Richard Smith3f57cff2017-03-09 00:58:22 +0000175 std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
176 if (Parent.empty())
177 Parent = ".";
178 auto *Dir = FileMgr.getDirectory(Parent);
Richard Smith54cc3c22014-12-11 20:50:24 +0000179 if (!Dir)
180 return std::string();
181 auto DirName = FileMgr.getCanonicalName(Dir);
182 auto FileName = llvm::sys::path::filename(ModuleMapPath);
183
184 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000185 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000186
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000187 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000188 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000189 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000190 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000191 return Result.str().str();
192}
193
194Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000195 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000196 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000197 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000198 return Module;
Graydon Hoare4d867642016-12-21 00:24:39 +0000199
200 StringRef SearchName = ModuleName;
201 Module = lookupModule(ModuleName, SearchName);
202
203 // The facility for "private modules" -- adjacent, optional module maps named
204 // module.private.modulemap that are supposed to define private submodules --
205 // is sometimes misused by frameworks that name their associated private
206 // module FooPrivate, rather than as a submodule named Foo.Private as
207 // intended. Here we compensate for such cases by looking in directories named
208 // Foo.framework, when we previously looked and failed to find a
209 // FooPrivate.framework.
210 if (!Module && SearchName.consume_back("Private"))
211 Module = lookupModule(ModuleName, SearchName);
212 return Module;
213}
214
215Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName) {
216 Module *Module = nullptr;
217
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000218 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000219 // maps, searching for a module map that describes this module.
220 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
221 if (SearchDirs[Idx].isFramework()) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000222 // Search for or infer a module map for a framework. Here we use
223 // SearchName rather than ModuleName, to permit finding private modules
224 // named FooPrivate in buggy frameworks named Foo.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000225 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000226 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
Graydon Hoare4d867642016-12-21 00:24:39 +0000227 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
228 if (const DirectoryEntry *FrameworkDir
Douglas Gregor279a6c32012-01-29 17:08:11 +0000229 = FileMgr.getDirectory(FrameworkDirName)) {
230 bool IsSystem
231 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
232 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000233 if (Module)
234 break;
235 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000236 }
237
238 // FIXME: Figure out how header maps and module maps will work together.
239
240 // Only deal with normal search directories.
241 if (!SearchDirs[Idx].isNormalDir())
242 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000243
244 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000245 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000246 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
247 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000248 // We just loaded a module map file; check whether the module is
249 // available now.
250 Module = ModMap.findModule(ModuleName);
251 if (Module)
252 break;
253 }
254
255 // Search for a module map in a subdirectory with the same name as the
256 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000257 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000258 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
259 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000260 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
261 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000262 // If we just loaded a module map file, look for the module again.
263 Module = ModMap.findModule(ModuleName);
264 if (Module)
265 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000266 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000267
268 // If we've already performed the exhaustive search for module maps in this
269 // search directory, don't do it again.
270 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
271 continue;
272
273 // Load all module maps in the immediate subdirectories of this search
274 // directory.
275 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
276
277 // Look again for the module.
278 Module = ModMap.findModule(ModuleName);
279 if (Module)
280 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000281 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000282
Douglas Gregor279a6c32012-01-29 17:08:11 +0000283 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000284}
285
Chris Lattnerf62f7582007-12-17 07:52:39 +0000286//===----------------------------------------------------------------------===//
287// File lookup within a DirectoryLookup scope
288//===----------------------------------------------------------------------===//
289
Chris Lattner8d720d02007-12-17 17:57:27 +0000290/// getName - Return the directory or filename corresponding to this lookup
291/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000292StringRef DirectoryLookup::getName() const {
Chris Lattner8d720d02007-12-17 17:57:27 +0000293 if (isNormalDir())
294 return getDir()->getName();
295 if (isFramework())
296 return getFrameworkDir()->getName();
297 assert(isHeaderMap() && "Unknown DirectoryLookup");
298 return getHeaderMap()->getFileName();
299}
300
Richard Smith3d5b48c2015-10-16 21:42:56 +0000301const FileEntry *HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000302 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
303 bool IsSystemHeaderDir, Module *RequestingModule,
304 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000305 // If we have a module map that might map this header, load it and
306 // check whether we'll have a suggestion for a module.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000307 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000308 if (!File)
309 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000310
Richard Smith3d5b48c2015-10-16 21:42:56 +0000311 // If there is a module that corresponds to this header, suggest it.
312 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
313 RequestingModule, SuggestedModule,
314 IsSystemHeaderDir))
315 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000316
Richard Smith3d5b48c2015-10-16 21:42:56 +0000317 return File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000318}
Chris Lattner8d720d02007-12-17 17:57:27 +0000319
Chris Lattnerf62f7582007-12-17 07:52:39 +0000320/// LookupFile - Lookup the specified file in this search path, returning it
321/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000322const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000323 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000324 HeaderSearch &HS,
Taewook Ohf42103c2016-06-13 20:40:21 +0000325 SourceLocation IncludeLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000327 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000328 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000329 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000330 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000331 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000332 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000333 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000334 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000335
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000336 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000337 if (isNormalDir()) {
338 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000339 TmpDir = getDir()->getName();
340 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000341 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000342 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000343 SearchPath->clear();
344 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
345 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000346 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000347 RelativePath->clear();
348 RelativePath->append(Filename.begin(), Filename.end());
349 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000350
Taewook Ohf42103c2016-06-13 20:40:21 +0000351 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000352 isSystemHeaderDirectory(),
353 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000354 }
Mike Stump11289f42009-09-09 15:08:12 +0000355
Chris Lattner712e3872007-12-17 08:13:48 +0000356 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000357 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000358 RequestingModule, SuggestedModule,
359 InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000360
Chris Lattner44bd21b2007-12-17 08:17:39 +0000361 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000362 const HeaderMap *HM = getHeaderMap();
363 SmallString<1024> Path;
364 StringRef Dest = HM->lookupFilename(Filename, Path);
365 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000366 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000367
368 const FileEntry *Result;
369
370 // Check if the headermap maps the filename to a framework include
371 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
372 // framework include.
373 if (llvm::sys::path::is_relative(Dest)) {
374 MappedName.clear();
375 MappedName.append(Dest.begin(), Dest.end());
376 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000377 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000378 Result = HM->LookupFile(Filename, HS.getFileMgr());
379
380 } else {
381 Result = HS.getFileMgr().getFile(Dest);
382 }
383
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000384 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000385 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000386 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000387 SearchPath->clear();
388 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
389 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000390 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000391 RelativePath->clear();
392 RelativePath->append(Filename.begin(), Filename.end());
393 }
394 }
395 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000396}
397
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000398/// \brief Given a framework directory, find the top-most framework directory.
399///
400/// \param FileMgr The file manager to use for directory lookups.
401/// \param DirName The name of the framework directory.
402/// \param SubmodulePath Will be populated with the submodule path from the
403/// returned top-level module to the originally named framework.
404static const DirectoryEntry *
405getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
406 SmallVectorImpl<std::string> &SubmodulePath) {
407 assert(llvm::sys::path::extension(DirName) == ".framework" &&
408 "Not a framework directory");
409
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000410 // Note: as an egregious but useful hack we use the real path here, because
411 // frameworks moving between top-level frameworks to embedded frameworks tend
412 // to be symlinked, and we base the logical structure of modules on the
413 // physical layout. In particular, we need to deal with crazy includes like
414 //
415 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
416 //
417 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
418 // which one should access with, e.g.,
419 //
420 // #include <Bar/Wibble.h>
421 //
422 // Similar issues occur when a top-level framework has moved into an
423 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000424 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000425 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000426 do {
427 // Get the parent directory name.
428 DirName = llvm::sys::path::parent_path(DirName);
429 if (DirName.empty())
430 break;
431
432 // Determine whether this directory exists.
433 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
434 if (!Dir)
435 break;
436
437 // If this is a framework directory, then we're a subframework of this
438 // framework.
439 if (llvm::sys::path::extension(DirName) == ".framework") {
440 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
441 TopFrameworkDir = Dir;
442 }
443 } while (true);
444
445 return TopFrameworkDir;
446}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000447
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000448static bool needModuleLookup(Module *RequestingModule,
449 bool HasSuggestedModule) {
450 return HasSuggestedModule ||
451 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
452}
453
Chris Lattner712e3872007-12-17 08:13:48 +0000454/// DoFrameworkLookup - Do a lookup of the specified file in the current
455/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000456const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000457 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
458 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000459 ModuleMap::KnownHeader *SuggestedModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000460 bool &InUserSpecifiedSystemFramework) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000461 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000462
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000463 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000464 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000465 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000466
Chris Lattner712e3872007-12-17 08:13:48 +0000467 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000468 // HeaderSearch. Possible answers are yes/no and unknown.
469 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000470 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000471
Chris Lattner712e3872007-12-17 08:13:48 +0000472 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000473 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000474 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattner712e3872007-12-17 08:13:48 +0000476 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000477
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000478 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000479 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000480 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000481 if (FrameworkName.empty() || FrameworkName.back() != '/')
482 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000483
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000484 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000485 StringRef ModuleName(Filename.begin(), SlashPos);
486 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000488 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
489 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000490
Daniel Dunbar17138612012-04-05 17:09:40 +0000491 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000492 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000493 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000494
Chris Lattner5ed76da2006-10-22 07:24:13 +0000495 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000496 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000497 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattner5ed76da2006-10-22 07:24:13 +0000499 // Otherwise, if it does, remember that this is the right direntry for this
500 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000501 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000502
503 // If this is a user search directory, check if the framework has been
504 // user-specified as a system framework.
505 if (getDirCharacteristic() == SrcMgr::C_User) {
506 SmallString<1024> SystemFrameworkMarker(FrameworkName);
507 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000508 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000509 CacheEntry.IsUserSpecifiedSystemFramework = true;
510 }
511 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000514 // Set the 'user-specified system framework' flag.
515 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
516
Craig Topperd2d442c2014-05-17 23:10:59 +0000517 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000518 RelativePath->clear();
519 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
520 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000521
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000522 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000523 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000525 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000526
Craig Topperd2d442c2014-05-17 23:10:59 +0000527 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000528 SearchPath->clear();
529 // Without trailing '/'.
530 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
531 }
532
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000533 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000534 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000535 /*openFile=*/!SuggestedModule);
536 if (!FE) {
537 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
538 const char *Private = "Private";
539 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
540 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000541 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000542 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
543 Private+strlen(Private));
544
Yaron Keren92e1b622015-03-18 10:17:07 +0000545 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000548 // If we found the header and are allowed to suggest a module, do so now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000549 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000550 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000551 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000552 bool FoundFramework = false;
553 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000554 // Determine whether this directory exists.
555 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
556 if (!Dir)
557 break;
558
559 // If this is a framework directory, then we're a subframework of this
560 // framework.
561 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
562 FoundFramework = true;
563 break;
564 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000565
566 // Get the parent directory name.
567 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
568 if (FrameworkPath.empty())
569 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000570 } while (true);
571
Richard Smith3d5b48c2015-10-16 21:42:56 +0000572 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000573 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000574 if (!HS.findUsableModuleForFrameworkHeader(
575 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
576 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000577 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000578 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
579 SuggestedModule, IsSystem))
580 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000581 }
582 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000583 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000584}
585
Douglas Gregor89929282012-01-30 06:01:29 +0000586void HeaderSearch::setTarget(const TargetInfo &Target) {
587 ModMap.setTarget(Target);
588}
589
Chris Lattnerf62f7582007-12-17 07:52:39 +0000590
Chris Lattner712e3872007-12-17 08:13:48 +0000591//===----------------------------------------------------------------------===//
592// Header File Location.
593//===----------------------------------------------------------------------===//
594
Reid Klecknera97d4c02014-02-18 23:49:24 +0000595/// \brief Return true with a diagnostic if the file that MSVC would have found
596/// fails to match the one that Clang would have found with MSVC header search
597/// disabled.
598static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
599 const FileEntry *MSFE, const FileEntry *FE,
600 SourceLocation IncludeLoc) {
601 if (MSFE && FE != MSFE) {
602 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
603 return true;
604 }
605 return false;
606}
Chris Lattner712e3872007-12-17 08:13:48 +0000607
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000608static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
609 assert(!Str.empty());
610 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
611 std::copy(Str.begin(), Str.end(), CopyStr);
612 CopyStr[Str.size()] = '\0';
613 return CopyStr;
614}
615
James Dennettc07ab2c2012-06-20 00:56:32 +0000616/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000617/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000618/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
619/// non-empty, indicates where the \#including file(s) are, in case a relative
620/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000621const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000622 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
623 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000624 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
625 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000626 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000627 bool *IsMapped, bool SkipCache, bool BuildSystemModule) {
628 if (IsMapped)
629 *IsMapped = false;
630
Douglas Gregor97eec242011-09-15 22:00:41 +0000631 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000632 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000633
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000634 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000635 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000636 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000637
638 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000639 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000640
Craig Topperd2d442c2014-05-17 23:10:59 +0000641 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000642 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000643 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000644 RelativePath->clear();
645 RelativePath->append(Filename.begin(), Filename.end());
646 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000647 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000648 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000649 /*IsSystemHeaderDir*/false,
650 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000651 }
Mike Stump11289f42009-09-09 15:08:12 +0000652
Reid Klecknera97d4c02014-02-18 23:49:24 +0000653 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000654 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000655 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000656
Douglas Gregor9f93e382011-07-28 04:45:53 +0000657 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000658 // directory. This cannot be based on CurDir, because each includer could be
659 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
660 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000661 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000662 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000663 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000664 bool First = true;
665 for (const auto &IncluderAndDir : Includers) {
666 const FileEntry *Includer = IncluderAndDir.first;
667
Will Wilson0fafd342013-12-27 19:46:16 +0000668 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000669 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000670 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000671 TmpDir.push_back('/');
672 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000673
Richard Smith6f548ec2014-03-06 18:08:08 +0000674 // FIXME: We don't cache the result of getFileInfo across the call to
675 // getFileAndSuggestModule, because it's a reference to an element of
676 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000677 //
Manman Rene4a5d372016-05-17 02:15:12 +0000678 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000679 // from a module build. We should treat this as a system header if we're
680 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000681 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000682 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
683 BuildSystemModule;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000684 if (const FileEntry *FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000685 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000686 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000687 if (!Includer) {
688 assert(First && "only first includer can have no file");
689 return FE;
690 }
691
Will Wilson0fafd342013-12-27 19:46:16 +0000692 // Leave CurDir unset.
693 // This file is a system header or C++ unfriendly if the old file is.
694 //
695 // Note that we only use one of FromHFI/ToHFI at once, due to potential
696 // reallocation of the underlying vector potentially making the first
697 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000698 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000699 unsigned DirInfo = FromHFI.DirInfo;
700 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
701 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000702
Will Wilson0fafd342013-12-27 19:46:16 +0000703 HeaderFileInfo &ToHFI = getFileInfo(FE);
704 ToHFI.DirInfo = DirInfo;
705 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
706 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000707
Craig Topperd2d442c2014-05-17 23:10:59 +0000708 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000709 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000710 SearchPath->clear();
711 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
712 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000713 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000714 RelativePath->clear();
715 RelativePath->append(Filename.begin(), Filename.end());
716 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000717 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000718 return FE;
719
720 // Otherwise, we found the path via MSVC header search rules. If
721 // -Wmsvc-include is enabled, we have to keep searching to see if we
722 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000723 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000724 return FE;
725 } else {
726 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000727 if (SuggestedModule) {
728 MSSuggestedModule = *SuggestedModule;
729 *SuggestedModule = ModuleMap::KnownHeader();
730 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000731 break;
732 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000733 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000734 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000735 }
736 }
Mike Stump11289f42009-09-09 15:08:12 +0000737
Craig Topperd2d442c2014-05-17 23:10:59 +0000738 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000739
740 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000741 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000743 // If this is a #include_next request, start searching after the directory the
744 // file was found in.
745 if (FromDir)
746 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattnerd4275422007-07-22 07:28:00 +0000748 // Cache all of the lookups performed by this method. Many headers are
749 // multiply included, and the "pragma once" optimization prevents them from
750 // being relex/pp'd, but they would still have to search through a
751 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000752 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000753
754 // If the entry has been previously looked up, the first value will be
755 // non-zero. If the value is equal to i (the start point of our search), then
756 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000757 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000758 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000759 i = CacheLookup.HitIdx;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000760 if (CacheLookup.MappedName) {
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000761 Filename = CacheLookup.MappedName;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000762 if (IsMapped)
763 *IsMapped = true;
764 }
Chris Lattnerd4275422007-07-22 07:28:00 +0000765 } else {
766 // Otherwise, this is the first query, or the previous query didn't match
767 // our search start. We will fill in our found location below, so prime the
768 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000769 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000770 }
Mike Stump11289f42009-09-09 15:08:12 +0000771
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000772 SmallString<64> MappedName;
773
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000774 // Check each directory in sequence to see if it contains this file.
775 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000776 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000777 bool HasBeenMapped = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000778 const FileEntry *FE = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000779 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000780 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
781 MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000782 if (HasBeenMapped) {
783 CacheLookup.MappedName =
784 copyString(Filename, LookupFileCache.getAllocator());
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000785 if (IsMapped)
786 *IsMapped = true;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000787 }
Chris Lattner712e3872007-12-17 08:13:48 +0000788 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000789
Chris Lattner712e3872007-12-17 08:13:48 +0000790 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000791
Chris Lattner712e3872007-12-17 08:13:48 +0000792 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000793 HeaderFileInfo &HFI = getFileInfo(FE);
794 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000795
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000796 // If the directory characteristic is User but this framework was
797 // user-specified to be treated as a system framework, promote the
798 // characteristic.
799 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
800 HFI.DirInfo = SrcMgr::C_System;
801
Richard Smith8acadcb2012-06-13 20:27:03 +0000802 // If the filename matches a known system header prefix, override
803 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000804 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
805 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
806 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000807 : SrcMgr::C_User;
808 break;
809 }
810 }
811
Douglas Gregor9f93e382011-07-28 04:45:53 +0000812 // If this file is found in a header map and uses the framework style of
813 // includes, then this header is part of a framework we're building.
814 if (CurDir->isIndexHeaderMap()) {
815 size_t SlashPos = Filename.find('/');
816 if (SlashPos != StringRef::npos) {
817 HFI.IndexHeaderMapHeader = 1;
818 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
819 SlashPos));
820 }
821 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000822
Richard Smith8c71eba2014-03-05 20:51:45 +0000823 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
824 if (SuggestedModule)
825 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000826 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000827 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000828
Chris Lattner712e3872007-12-17 08:13:48 +0000829 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000830 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000831 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Douglas Gregord8575e12011-07-30 06:28:34 +0000834 // If we are including a file with a quoted include "foo.h" from inside
835 // a header in a framework that is currently being built, and we couldn't
836 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
837 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000838 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000839 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000840 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000841 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000842 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000843 ScratchFilename += IncludingHFI.Framework;
844 ScratchFilename += '/';
845 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000846
Richard Smith3d5b48c2015-10-16 21:42:56 +0000847 const FileEntry *FE =
848 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
849 CurDir, Includers.front(), SearchPath, RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000850 RequestingModule, SuggestedModule, IsMapped);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000851
Richard Smith8c71eba2014-03-05 20:51:45 +0000852 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
853 if (SuggestedModule)
854 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000855 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000856 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000857
David Blaikie3c8c46e2014-11-19 05:48:40 +0000858 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000859 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000860 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000861 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000862 }
863 }
864
Craig Topperd2d442c2014-05-17 23:10:59 +0000865 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000866 if (SuggestedModule)
867 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000868 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000869 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000870
Chris Lattnerd4275422007-07-22 07:28:00 +0000871 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000872 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000873 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000874}
875
Chris Lattner63dd32b2006-10-20 04:42:40 +0000876/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000877/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000878/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
879/// is a subframework within Carbon.framework. If so, return the FileEntry
880/// for the designated file, otherwise return null.
881const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000882LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000883 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000884 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000885 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000886 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000887 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000888 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000889
Chris Lattner63dd32b2006-10-20 04:42:40 +0000890 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000891 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000892 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000893 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattner63dd32b2006-10-20 04:42:40 +0000895 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +0000896 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000897
Chris Lattner63dd32b2006-10-20 04:42:40 +0000898 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000899 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +0000900 auto FrameworkPos = ContextName.find(".framework");
901 if (FrameworkPos == StringRef::npos ||
902 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
903 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000904 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Mehdi Amini004b9c72016-10-10 22:52:47 +0000906 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
907 FrameworkPos +
908 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000909
Chris Lattner63dd32b2006-10-20 04:42:40 +0000910 // Append Frameworks/HIToolbox.framework/
911 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000912 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000913 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000914
David Blaikie13156b62014-11-19 03:06:06 +0000915 auto &CacheLookup =
916 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
917 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000918
Chris Lattner5ed76da2006-10-22 07:24:13 +0000919 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000920 if (CacheLookup.second.Directory &&
921 CacheLookup.first().size() == FrameworkName.size() &&
922 memcmp(CacheLookup.first().data(), &FrameworkName[0],
923 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000924 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000925
Chris Lattner5ed76da2006-10-22 07:24:13 +0000926 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000927 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000928 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000929
Chris Lattner5ed76da2006-10-22 07:24:13 +0000930 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000931 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000932 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000933
Chris Lattner5ed76da2006-10-22 07:24:13 +0000934 // Otherwise, if it does, remember that this is the right direntry for this
935 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000936 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000937 }
Mike Stump11289f42009-09-09 15:08:12 +0000938
Craig Topperd2d442c2014-05-17 23:10:59 +0000939 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000940
Craig Topperd2d442c2014-05-17 23:10:59 +0000941 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000942 RelativePath->clear();
943 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
944 }
945
Chris Lattner63dd32b2006-10-20 04:42:40 +0000946 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000947 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000948 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000949 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000950 SearchPath->clear();
951 // Without trailing '/'.
952 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
953 }
954
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000955 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000956 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000957
Chris Lattner63dd32b2006-10-20 04:42:40 +0000958 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000959 HeadersFilename = FrameworkName;
960 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000961 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000962 SearchPath->clear();
963 // Without trailing '/'.
964 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
965 }
966
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000967 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000968 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000969 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000970 }
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattner577377e2006-10-20 04:55:45 +0000972 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000973 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000974 // Note that the temporary 'DirInfo' is required here, as either call to
975 // getFileInfo could resize the vector and we don't want to rely on order
976 // of evaluation.
977 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
978 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000979
Richard Smith3d5b48c2015-10-16 21:42:56 +0000980 FrameworkName.pop_back(); // remove the trailing '/'
981 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
982 SuggestedModule, /*IsSystem*/ false))
983 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000984
Chris Lattner577377e2006-10-20 04:55:45 +0000985 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000986}
987
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000988//===----------------------------------------------------------------------===//
989// File Info Management.
990//===----------------------------------------------------------------------===//
991
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000992/// \brief Merge the header file info provided by \p OtherHFI into the current
993/// header file info (\p HFI)
994static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
995 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +0000996 assert(OtherHFI.External && "expected to merge external HFI");
997
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000998 HFI.isImport |= OtherHFI.isImport;
999 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001000 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001001 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +00001002
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001003 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1004 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1005 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1006 }
Richard Smithd8879c82015-08-24 21:59:32 +00001007
1008 HFI.DirInfo = OtherHFI.DirInfo;
1009 HFI.External = (!HFI.IsValid || HFI.External);
1010 HFI.IsValid = true;
1011 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001012
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001013 if (HFI.Framework.empty())
1014 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001015}
1016
Steve Naroff3fa455a2009-04-24 20:03:17 +00001017/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001018/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001019HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001020 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +00001021 FileInfo.resize(FE->getUID() + 1);
1022
Richard Smithd8879c82015-08-24 21:59:32 +00001023 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +00001024 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001025 if (ExternalSource && !HFI->Resolved) {
1026 HFI->Resolved = true;
1027 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1028
1029 HFI = &FileInfo[FE->getUID()];
1030 if (ExternalHFI.External)
1031 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +00001032 }
1033
Richard Smithd8879c82015-08-24 21:59:32 +00001034 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +00001035 // We have local information about this header file, so it's no longer
1036 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001037 HFI->External = false;
1038 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001039}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001040
Richard Smith386bb072015-08-18 23:42:23 +00001041const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001042HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1043 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001044 // If we have an external source, ensure we have the latest information.
1045 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001046 HeaderFileInfo *HFI;
1047 if (ExternalSource) {
1048 if (FE->getUID() >= FileInfo.size()) {
1049 if (!WantExternal)
1050 return nullptr;
1051 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001052 }
Richard Smithd8879c82015-08-24 21:59:32 +00001053
1054 HFI = &FileInfo[FE->getUID()];
1055 if (!WantExternal && (!HFI->IsValid || HFI->External))
1056 return nullptr;
1057 if (!HFI->Resolved) {
1058 HFI->Resolved = true;
1059 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1060
1061 HFI = &FileInfo[FE->getUID()];
1062 if (ExternalHFI.External)
1063 mergeHeaderFileInfo(*HFI, ExternalHFI);
1064 }
1065 } else if (FE->getUID() >= FileInfo.size()) {
1066 return nullptr;
1067 } else {
1068 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001069 }
Richard Smith386bb072015-08-18 23:42:23 +00001070
Richard Smithd8879c82015-08-24 21:59:32 +00001071 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001072 return nullptr;
1073
Richard Smithd8879c82015-08-24 21:59:32 +00001074 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001075}
1076
Douglas Gregor37aa4932011-05-04 00:14:37 +00001077bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1078 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001079 if (auto *HFI = getExistingFileInfo(File))
1080 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1081 HFI->ControllingMacroID;
1082 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001083}
1084
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001085void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001086 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001087 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001088 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1089
1090 // Don't mark the file info as non-external if there's nothing to change.
1091 if (!isCompilingModuleHeader) {
1092 if (!isModularHeader)
1093 return;
1094 auto *HFI = getExistingFileInfo(FE);
1095 if (HFI && HFI->isModuleHeader)
1096 return;
1097 }
1098
Richard Smith386bb072015-08-18 23:42:23 +00001099 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001100 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001101 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001102}
1103
Richard Smith20e883e2015-04-29 23:20:19 +00001104bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001105 const FileEntry *File, bool isImport,
1106 bool ModulesEnabled, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001107 ++NumIncluded; // Count # of attempted #includes.
1108
1109 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001110 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001111
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001112 // FIXME: this is a workaround for the lack of proper modules-aware support
1113 // for #import / #pragma once
1114 auto TryEnterImported = [&](void) -> bool {
1115 if (!ModulesEnabled)
1116 return false;
Richard Smith040e1262017-06-02 01:55:39 +00001117 // Ensure FileInfo bits are up to date.
1118 ModMap.resolveHeaderDirectives(File);
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001119 // Modules with builtins are special; multiple modules use builtins as
1120 // modular headers, example:
1121 //
1122 // module stddef { header "stddef.h" export * }
1123 //
1124 // After module map parsing, this expands to:
1125 //
1126 // module stddef {
1127 // header "/path_to_builtin_dirs/stddef.h"
1128 // textual "stddef.h"
1129 // }
1130 //
1131 // It's common that libc++ and system modules will both define such
1132 // submodules. Make sure cached results for a builtin header won't
1133 // prevent other builtin modules to potentially enter the builtin header.
1134 // Note that builtins are header guarded and the decision to actually
1135 // enter them is postponed to the controlling macros logic below.
1136 bool TryEnterHdr = false;
1137 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1138 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1139 ModuleMap::isBuiltinHeader(
1140 llvm::sys::path::filename(File->getName()));
1141
1142 // Textual headers can be #imported from different modules. Since ObjC
1143 // headers find in the wild might rely only on #import and do not contain
1144 // controlling macros, be conservative and only try to enter textual headers
1145 // if such macro is present.
Bruno Cardoso Lopes4164dd92017-08-12 01:38:26 +00001146 if (!FileInfo.isModuleHeader &&
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001147 FileInfo.getControllingMacro(ExternalLookup))
1148 TryEnterHdr = true;
1149 return TryEnterHdr;
1150 };
1151
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001152 // If this is a #import directive, check that we have not already imported
1153 // this header.
1154 if (isImport) {
1155 // If this has already been imported, don't import it again.
1156 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001157
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001158 // Has this already been #import'ed or #include'd?
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001159 if (FileInfo.NumIncludes && !TryEnterImported())
1160 return false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001161 } else {
1162 // Otherwise, if this is a #include of a file that was previously #import'd
1163 // or if this is the second #include of a #pragma once file, ignore it.
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001164 if (FileInfo.isImport && !TryEnterImported())
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001165 return false;
1166 }
Mike Stump11289f42009-09-09 15:08:12 +00001167
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001168 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1169 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001170 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001171 = FileInfo.getControllingMacro(ExternalLookup)) {
1172 // If the header corresponds to a module, check whether the macro is already
1173 // defined in that module rather than checking in the current set of visible
1174 // modules.
1175 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1176 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001177 ++NumMultiIncludeFileOptzn;
1178 return false;
1179 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001180 }
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001182 // Increment the number of times this file has been included.
1183 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001184
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001185 return true;
1186}
1187
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001188size_t HeaderSearch::getTotalMemory() const {
1189 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001190 + llvm::capacity_in_bytes(FileInfo)
1191 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001192 + LookupFileCache.getAllocator().getTotalMemory()
1193 + FrameworkMap.getAllocator().getTotalMemory();
1194}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001195
1196StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001197 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001198}
Douglas Gregor718292f2011-11-11 19:10:28 +00001199
1200bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001201 const DirectoryEntry *Root,
1202 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001203 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001204 return false;
1205
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001206 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001207
1208 StringRef DirName = FileName;
1209 do {
1210 // Get the parent directory name.
1211 DirName = llvm::sys::path::parent_path(DirName);
1212 if (DirName.empty())
1213 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001214
Douglas Gregor718292f2011-11-11 19:10:28 +00001215 // Determine whether this directory exists.
1216 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1217 if (!Dir)
1218 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001219
Ben Langmuir984e1df2014-03-19 20:23:34 +00001220 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001221 switch (loadModuleMapFile(Dir, IsSystem,
1222 llvm::sys::path::extension(Dir->getName()) ==
1223 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001224 case LMM_NewlyLoaded:
1225 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001226 // Success. All of the directories we stepped through inherit this module
1227 // map file.
1228 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1229 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1230 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001231
1232 case LMM_NoDirectory:
1233 case LMM_InvalidModuleMap:
1234 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001235 }
1236
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001237 // If we hit the top of our search, we're done.
1238 if (Dir == Root)
1239 return false;
1240
Douglas Gregor718292f2011-11-11 19:10:28 +00001241 // Keep track of all of the directories we checked, so we can mark them as
1242 // having module maps if we eventually do find a module map.
1243 FixUpDirectories.push_back(Dir);
1244 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001245}
1246
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001247ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001248HeaderSearch::findModuleForHeader(const FileEntry *File,
1249 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001250 if (ExternalSource) {
1251 // Make sure the external source has handled header info about this file,
1252 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001253 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001254 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001255 return ModMap.findModuleForHeader(File, AllowTextual);
1256}
1257
1258static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1259 Module *RequestingModule,
1260 ModuleMap::KnownHeader *SuggestedModule) {
1261 ModuleMap::KnownHeader Module =
1262 HS.findModuleForHeader(File, /*AllowTextual*/true);
1263 if (SuggestedModule)
1264 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1265 ? ModuleMap::KnownHeader()
1266 : Module;
1267
1268 // If this module specifies [no_undeclared_includes], we cannot find any
1269 // file that's in a non-dependency module.
1270 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1271 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1272 if (!RequestingModule->directlyUses(Module.getModule())) {
1273 return false;
1274 }
1275 }
1276
1277 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001278}
1279
Richard Smith3d5b48c2015-10-16 21:42:56 +00001280bool HeaderSearch::findUsableModuleForHeader(
1281 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1282 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001283 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001284 // If there is a module that corresponds to this header, suggest it.
1285 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001286 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001287 }
1288 return true;
1289}
1290
1291bool HeaderSearch::findUsableModuleForFrameworkHeader(
1292 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1293 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1294 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001295 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001296 // Find the top-level framework based on this framework.
1297 SmallVector<std::string, 4> SubmodulePath;
1298 const DirectoryEntry *TopFrameworkDir
1299 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1300
1301 // Determine the name of the top-level framework.
1302 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1303
1304 // Load this framework module. If that succeeds, find the suggested module
1305 // for this header, if any.
1306 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1307
1308 // FIXME: This can find a module not part of ModuleName, which is
1309 // important so that we're consistent about whether this header
1310 // corresponds to a module. Possibly we should lock down framework modules
1311 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001312 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001313 }
1314 return true;
1315}
1316
Richard Smith9acb99e32014-12-10 03:09:48 +00001317static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001318 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001319 StringRef Filename = llvm::sys::path::filename(File->getName());
1320 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001321 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001322 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001323 else if (Filename == "module.modulemap")
1324 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1325 else
1326 return nullptr;
1327 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001328}
1329
Richard Smith8128f332017-05-05 22:18:51 +00001330bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +00001331 FileID ID, unsigned *Offset,
1332 StringRef OriginalModuleMapFile) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001333 // Find the directory for the module. For frameworks, that may require going
1334 // up from the 'Modules' directory.
1335 const DirectoryEntry *Dir = nullptr;
1336 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1337 Dir = FileMgr.getDirectory(".");
1338 else {
Richard Smith8b706102017-05-31 20:56:55 +00001339 if (!OriginalModuleMapFile.empty()) {
1340 // We're building a preprocessed module map. Find or invent the directory
1341 // that it originally occupied.
1342 Dir = FileMgr.getDirectory(
1343 llvm::sys::path::parent_path(OriginalModuleMapFile));
1344 if (!Dir) {
1345 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1346 Dir = FakeFile->getDir();
1347 }
1348 } else {
1349 Dir = File->getDir();
1350 }
1351
Richard Smith9acb99e32014-12-10 03:09:48 +00001352 StringRef DirName(Dir->getName());
1353 if (llvm::sys::path::filename(DirName) == "Modules") {
1354 DirName = llvm::sys::path::parent_path(DirName);
1355 if (DirName.endswith(".framework"))
1356 Dir = FileMgr.getDirectory(DirName);
1357 // FIXME: This assert can fail if there's a race between the above check
1358 // and the removal of the directory.
1359 assert(Dir && "parent must exist");
1360 }
1361 }
1362
Richard Smith8128f332017-05-05 22:18:51 +00001363 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001364 case LMM_AlreadyLoaded:
1365 case LMM_NewlyLoaded:
1366 return false;
1367 case LMM_NoDirectory:
1368 case LMM_InvalidModuleMap:
1369 return true;
1370 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001371 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001372}
1373
1374HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001375HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
Richard Smith8128f332017-05-05 22:18:51 +00001376 const DirectoryEntry *Dir, FileID ID,
1377 unsigned *Offset) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001378 assert(File && "expected FileEntry");
1379
Richard Smith9887d792014-10-17 01:42:53 +00001380 // Check whether we've already loaded this module map, and mark it as being
1381 // loaded in case we recursively try to load it from itself.
1382 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1383 if (!AddResult.second)
1384 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001385
Richard Smith8128f332017-05-05 22:18:51 +00001386 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
Richard Smith9887d792014-10-17 01:42:53 +00001387 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001388 return LMM_InvalidModuleMap;
1389 }
1390
1391 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001392 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1393 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001394 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001395 return LMM_InvalidModuleMap;
1396 }
1397 }
1398
1399 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001400 return LMM_NewlyLoaded;
1401}
1402
1403const FileEntry *
1404HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001405 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001406 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001407 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1408 // module.map at the framework root is also accepted.
1409 SmallString<128> ModuleMapFileName(Dir->getName());
1410 if (IsFramework)
1411 llvm::sys::path::append(ModuleMapFileName, "Modules");
1412 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1413 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1414 return F;
1415
1416 // Continue to allow module.map
1417 ModuleMapFileName = Dir->getName();
1418 llvm::sys::path::append(ModuleMapFileName, "module.map");
1419 return FileMgr.getFile(ModuleMapFileName);
1420}
1421
1422Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001423 const DirectoryEntry *Dir,
1424 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001425 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001426 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001427
Douglas Gregor56c64012011-11-17 01:41:17 +00001428 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001429 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001430 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001431 // Try to infer a module map from the framework directory.
1432 if (HSOpts->ImplicitModuleMaps)
1433 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001434 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001435
Douglas Gregor56c64012011-11-17 01:41:17 +00001436 case LMM_AlreadyLoaded:
1437 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001438 return nullptr;
1439
Douglas Gregor56c64012011-11-17 01:41:17 +00001440 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001441 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001442 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001443
Ben Langmuira5254002015-07-02 13:19:48 +00001444 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001445}
1446
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001447
Douglas Gregor80b69042011-11-12 00:22:19 +00001448HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001449HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1450 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001451 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001452 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001453
Douglas Gregor80b69042011-11-12 00:22:19 +00001454 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001455}
1456
Douglas Gregor80b69042011-11-12 00:22:19 +00001457HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001458HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1459 bool IsFramework) {
1460 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001461 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001462 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001463
Ben Langmuir984e1df2014-03-19 20:23:34 +00001464 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001465 LoadModuleMapResult Result =
1466 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001467 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1468 // E.g. Foo.framework/Modules/module.modulemap
1469 // ^Dir ^ModuleMapFile
1470 if (Result == LMM_NewlyLoaded)
1471 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001472 else if (Result == LMM_InvalidModuleMap)
1473 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001474 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001475 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001476 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001477}
Douglas Gregor718292f2011-11-11 19:10:28 +00001478
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001479void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001480 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001481
Richard Smith47972af2015-06-16 00:08:24 +00001482 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001483 // Load module maps for each of the header search directories.
1484 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1485 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1486 if (SearchDirs[Idx].isFramework()) {
1487 std::error_code EC;
1488 SmallString<128> DirNative;
1489 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1490 DirNative);
1491
1492 // Search each of the ".framework" directories to load them as modules.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001493 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1494 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001495 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001496 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001497 continue;
1498
1499 const DirectoryEntry *FrameworkDir =
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001500 FileMgr.getDirectory(Dir->getName());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001501 if (!FrameworkDir)
1502 continue;
1503
1504 // Load this framework module.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001505 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1506 FrameworkDir, IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001507 }
1508 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001509 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001510
1511 // FIXME: Deal with header maps.
1512 if (SearchDirs[Idx].isHeaderMap())
1513 continue;
1514
1515 // Try to load a module map file for the search directory.
1516 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1517 /*IsFramework*/ false);
1518
1519 // Try to load module map files for immediate subdirectories of this
1520 // search directory.
1521 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001522 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001523 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001524
Douglas Gregor07f43572012-01-29 18:15:03 +00001525 // Populate the list of modules.
1526 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1527 MEnd = ModMap.module_end();
1528 M != MEnd; ++M) {
1529 Modules.push_back(M->getValue());
1530 }
1531}
Douglas Gregor0339a642013-03-21 01:08:50 +00001532
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001533void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001534 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001535 return;
1536
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001537 // Load module maps for each of the header search directories.
1538 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001539 // We only care about normal header directories.
1540 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001541 continue;
1542 }
1543
1544 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001545 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001546 SearchDirs[Idx].isSystemHeaderDirectory(),
1547 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001548 }
1549}
1550
Douglas Gregor0339a642013-03-21 01:08:50 +00001551void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001552 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001553 "Should not be loading subdirectory module maps");
1554
Douglas Gregor0339a642013-03-21 01:08:50 +00001555 if (SearchDir.haveSearchedAllModuleMaps())
1556 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001557
1558 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001559 SmallString<128> DirNative;
1560 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001561 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1562 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001563 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001564 bool IsFramework =
1565 llvm::sys::path::extension(Dir->getName()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001566 if (IsFramework == SearchDir.isFramework())
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001567 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001568 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001569 }
1570
1571 SearchDir.setSearchedAllModuleMaps(true);
1572}
Richard Smith4eb83932016-04-27 21:57:05 +00001573
1574std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1575 bool *IsSystem) {
1576 // FIXME: We assume that the path name currently cached in the FileEntry is
1577 // the most appropriate one for this analysis (and that it's spelled the same
1578 // way as the corresponding header search path).
Mehdi Amini004b9c72016-10-10 22:52:47 +00001579 StringRef Name = File->getName();
Richard Smith4eb83932016-04-27 21:57:05 +00001580
1581 unsigned BestPrefixLength = 0;
1582 unsigned BestSearchDir;
1583
1584 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1585 // FIXME: Support this search within frameworks and header maps.
1586 if (!SearchDirs[I].isNormalDir())
1587 continue;
1588
Mehdi Amini0df59d82016-10-11 07:31:29 +00001589 StringRef Dir = SearchDirs[I].getDir()->getName();
Richard Smith4eb83932016-04-27 21:57:05 +00001590 for (auto NI = llvm::sys::path::begin(Name),
1591 NE = llvm::sys::path::end(Name),
1592 DI = llvm::sys::path::begin(Dir),
1593 DE = llvm::sys::path::end(Dir);
1594 /*termination condition in loop*/; ++NI, ++DI) {
1595 // '.' components in Name are ignored.
1596 while (NI != NE && *NI == ".")
1597 ++NI;
1598 if (NI == NE)
1599 break;
1600
1601 // '.' components in Dir are ignored.
1602 while (DI != DE && *DI == ".")
1603 ++DI;
1604 if (DI == DE) {
1605 // Dir is a prefix of Name, up to '.' components and choice of path
1606 // separators.
1607 unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1608 if (PrefixLength > BestPrefixLength) {
1609 BestPrefixLength = PrefixLength;
1610 BestSearchDir = I;
1611 }
1612 break;
1613 }
1614
1615 if (*NI != *DI)
1616 break;
1617 }
1618 }
1619
1620 if (IsSystem)
1621 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001622 return Name.drop_front(BestPrefixLength);
Richard Smith4eb83932016-04-27 21:57:05 +00001623}