blob: cf315767b61c89c18e1de8d6d2df16bc67ec3ac3 [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) {
39 if (ControllingMacro->isOutOfDate())
40 External->updateOutOfDateIdentifier(
41 *const_cast<IdentifierInfo *>(ControllingMacro));
Douglas Gregor99734e72009-04-25 23:30:02 +000042 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000043 }
Douglas Gregor99734e72009-04-25 23:30:02 +000044
45 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000046 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000047
48 ControllingMacro = External->GetIdentifier(ControllingMacroID);
49 return ControllingMacro;
50}
51
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000052ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
Douglas Gregor09b69892011-02-10 17:09:37 +000053
Dmitri Gribenkof8579502013-01-12 19:30:44 +000054HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000055 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000056 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000057 const TargetInfo *Target)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000058 : HSOpts(std::move(HSOpts)), Diags(Diags),
59 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
60 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
Nico Weber3b1d1212011-05-24 04:31:14 +000061 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000062 SystemDirIdx = 0;
63 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000064
Craig Topperd2d442c2014-05-17 23:10:59 +000065 ExternalLookup = nullptr;
66 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000067 NumIncluded = 0;
68 NumMultiIncludeFileOptzn = 0;
69 NumFrameworkLookups = NumSubFrameworkLookups = 0;
70}
71
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000072HeaderSearch::~HeaderSearch() {
73 // Delete headermaps.
74 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
75 delete HeaderMaps[i].second;
76}
Mike Stump11289f42009-09-09 15:08:12 +000077
Chris Lattner59a9ebd2006-10-18 05:34:33 +000078void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000079 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
80 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000081 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
82 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
83 NumOnceOnlyFiles += FileInfo[i].isImport;
84 if (MaxNumIncludes < FileInfo[i].NumIncludes)
85 MaxNumIncludes = FileInfo[i].NumIncludes;
86 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
87 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000088 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
89 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
90 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner23b7eb62007-06-15 23:05:46 +000092 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
93 fprintf(stderr, " %d #includes skipped due to"
94 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000095
Chris Lattner23b7eb62007-06-15 23:05:46 +000096 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
97 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000098}
99
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000100/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000101/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000102const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000103 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000104 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000105 if (!HeaderMaps.empty()) {
106 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000107 // Pointer equality comparison of FileEntries works because they are
108 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000109 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000110 return HeaderMaps[i].second;
111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattner5159f612010-11-23 08:35:12 +0000113 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000114 HeaderMaps.push_back(std::make_pair(FE, HM));
115 return HM;
116 }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Craig Topperd2d442c2014-05-17 23:10:59 +0000118 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000119}
120
Douglas Gregor279a6c32012-01-29 17:08:11 +0000121std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000122 const FileEntry *ModuleMap =
123 getModuleMap().getModuleMapFileForUniquing(Module);
Manman Ren11f2a472016-08-18 17:42:15 +0000124 return getModuleFileName(Module->Name, ModuleMap->getName(),
125 /*UsePrebuiltPath*/false);
Douglas Gregor279a6c32012-01-29 17:08:11 +0000126}
127
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000128std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
Manman Ren11f2a472016-08-18 17:42:15 +0000129 StringRef ModuleMapPath,
130 bool UsePrebuiltPath) {
131 if (UsePrebuiltPath) {
132 if (HSOpts->PrebuiltModulePaths.empty())
133 return std::string();
134
135 // Go though each prebuilt module path and try to find the pcm file.
136 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
137 SmallString<256> Result(Dir);
138 llvm::sys::fs::make_absolute(Result);
139
140 llvm::sys::path::append(Result, ModuleName + ".pcm");
141 if (getFileMgr().getFile(Result.str()))
142 return Result.str().str();
143 }
144 return std::string();
145 }
146
Richard Smithd520a252015-07-21 18:07:47 +0000147 // If we don't have a module cache path or aren't supposed to use one, we
148 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000149 if (getModuleCachePath().empty())
Douglas Gregor279a6c32012-01-29 17:08:11 +0000150 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000151
Richard Smith3938f0c2015-08-15 00:34:15 +0000152 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000153 llvm::sys::fs::make_absolute(Result);
154
155 if (HSOpts->DisableModuleHash) {
156 llvm::sys::path::append(Result, ModuleName + ".pcm");
157 } else {
158 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000159 // ideally be globally unique to this particular module. Name collisions
160 // in the hash are safe (because any translation unit can only import one
161 // module with each name), but result in a loss of caching.
162 //
163 // To avoid false-negatives, we form as canonical a path as we can, and map
164 // to lower-case in case we're on a case-insensitive file system.
165 auto *Dir =
166 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
167 if (!Dir)
168 return std::string();
169 auto DirName = FileMgr.getCanonicalName(Dir);
170 auto FileName = llvm::sys::path::filename(ModuleMapPath);
171
172 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000173 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000174
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000175 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000176 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000177 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000178 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000179 return Result.str().str();
180}
181
182Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000183 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000184 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000185 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000186 return Module;
187
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000188 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000189 // maps, searching for a module map that describes this module.
190 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
191 if (SearchDirs[Idx].isFramework()) {
192 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000193 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000194 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
195 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
196 if (const DirectoryEntry *FrameworkDir
197 = FileMgr.getDirectory(FrameworkDirName)) {
198 bool IsSystem
199 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
200 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000201 if (Module)
202 break;
203 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000204 }
205
206 // FIXME: Figure out how header maps and module maps will work together.
207
208 // Only deal with normal search directories.
209 if (!SearchDirs[Idx].isNormalDir())
210 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000211
212 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000213 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000214 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
215 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000216 // We just loaded a module map file; check whether the module is
217 // available now.
218 Module = ModMap.findModule(ModuleName);
219 if (Module)
220 break;
221 }
222
223 // Search for a module map in a subdirectory with the same name as the
224 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000225 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000226 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
227 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000228 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
229 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000230 // If we just loaded a module map file, look for the module again.
231 Module = ModMap.findModule(ModuleName);
232 if (Module)
233 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000234 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000235
236 // If we've already performed the exhaustive search for module maps in this
237 // search directory, don't do it again.
238 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
239 continue;
240
241 // Load all module maps in the immediate subdirectories of this search
242 // directory.
243 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
244
245 // Look again for the module.
246 Module = ModMap.findModule(ModuleName);
247 if (Module)
248 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000249 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000250
Douglas Gregor279a6c32012-01-29 17:08:11 +0000251 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000252}
253
Chris Lattnerf62f7582007-12-17 07:52:39 +0000254//===----------------------------------------------------------------------===//
255// File lookup within a DirectoryLookup scope
256//===----------------------------------------------------------------------===//
257
Chris Lattner8d720d02007-12-17 17:57:27 +0000258/// getName - Return the directory or filename corresponding to this lookup
259/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000260StringRef DirectoryLookup::getName() const {
Chris Lattner8d720d02007-12-17 17:57:27 +0000261 if (isNormalDir())
262 return getDir()->getName();
263 if (isFramework())
264 return getFrameworkDir()->getName();
265 assert(isHeaderMap() && "Unknown DirectoryLookup");
266 return getHeaderMap()->getFileName();
267}
268
Richard Smith3d5b48c2015-10-16 21:42:56 +0000269const FileEntry *HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000270 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
271 bool IsSystemHeaderDir, Module *RequestingModule,
272 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000273 // If we have a module map that might map this header, load it and
274 // check whether we'll have a suggestion for a module.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000275 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000276 if (!File)
277 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000278
Richard Smith3d5b48c2015-10-16 21:42:56 +0000279 // If there is a module that corresponds to this header, suggest it.
280 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
281 RequestingModule, SuggestedModule,
282 IsSystemHeaderDir))
283 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000284
Richard Smith3d5b48c2015-10-16 21:42:56 +0000285 return File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000286}
Chris Lattner8d720d02007-12-17 17:57:27 +0000287
Chris Lattnerf62f7582007-12-17 07:52:39 +0000288/// LookupFile - Lookup the specified file in this search path, returning it
289/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000290const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000291 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000292 HeaderSearch &HS,
Taewook Ohf42103c2016-06-13 20:40:21 +0000293 SourceLocation IncludeLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000294 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000295 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000296 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000297 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000298 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000299 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000300 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000301 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000302 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000303
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000304 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000305 if (isNormalDir()) {
306 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000307 TmpDir = getDir()->getName();
308 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000309 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000310 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000311 SearchPath->clear();
312 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
313 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000314 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000315 RelativePath->clear();
316 RelativePath->append(Filename.begin(), Filename.end());
317 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000318
Taewook Ohf42103c2016-06-13 20:40:21 +0000319 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000320 isSystemHeaderDirectory(),
321 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000322 }
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattner712e3872007-12-17 08:13:48 +0000324 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000325 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000326 RequestingModule, SuggestedModule,
327 InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattner44bd21b2007-12-17 08:17:39 +0000329 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000330 const HeaderMap *HM = getHeaderMap();
331 SmallString<1024> Path;
332 StringRef Dest = HM->lookupFilename(Filename, Path);
333 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000334 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000335
336 const FileEntry *Result;
337
338 // Check if the headermap maps the filename to a framework include
339 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
340 // framework include.
341 if (llvm::sys::path::is_relative(Dest)) {
342 MappedName.clear();
343 MappedName.append(Dest.begin(), Dest.end());
344 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000345 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000346 Result = HM->LookupFile(Filename, HS.getFileMgr());
347
348 } else {
349 Result = HS.getFileMgr().getFile(Dest);
350 }
351
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000352 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000353 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000354 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000355 SearchPath->clear();
356 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
357 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000358 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000359 RelativePath->clear();
360 RelativePath->append(Filename.begin(), Filename.end());
361 }
362 }
363 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000364}
365
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000366/// \brief Given a framework directory, find the top-most framework directory.
367///
368/// \param FileMgr The file manager to use for directory lookups.
369/// \param DirName The name of the framework directory.
370/// \param SubmodulePath Will be populated with the submodule path from the
371/// returned top-level module to the originally named framework.
372static const DirectoryEntry *
373getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
374 SmallVectorImpl<std::string> &SubmodulePath) {
375 assert(llvm::sys::path::extension(DirName) == ".framework" &&
376 "Not a framework directory");
377
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000378 // Note: as an egregious but useful hack we use the real path here, because
379 // frameworks moving between top-level frameworks to embedded frameworks tend
380 // to be symlinked, and we base the logical structure of modules on the
381 // physical layout. In particular, we need to deal with crazy includes like
382 //
383 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
384 //
385 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
386 // which one should access with, e.g.,
387 //
388 // #include <Bar/Wibble.h>
389 //
390 // Similar issues occur when a top-level framework has moved into an
391 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000392 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000393 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000394 do {
395 // Get the parent directory name.
396 DirName = llvm::sys::path::parent_path(DirName);
397 if (DirName.empty())
398 break;
399
400 // Determine whether this directory exists.
401 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
402 if (!Dir)
403 break;
404
405 // If this is a framework directory, then we're a subframework of this
406 // framework.
407 if (llvm::sys::path::extension(DirName) == ".framework") {
408 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
409 TopFrameworkDir = Dir;
410 }
411 } while (true);
412
413 return TopFrameworkDir;
414}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000415
Chris Lattner712e3872007-12-17 08:13:48 +0000416/// DoFrameworkLookup - Do a lookup of the specified file in the current
417/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000418const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000419 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
420 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000421 ModuleMap::KnownHeader *SuggestedModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000422 bool &InUserSpecifiedSystemFramework) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000423 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000425 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000426 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000427 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattner712e3872007-12-17 08:13:48 +0000429 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000430 // HeaderSearch. Possible answers are yes/no and unknown.
431 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000432 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattner712e3872007-12-17 08:13:48 +0000434 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000435 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000436 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000437
Chris Lattner712e3872007-12-17 08:13:48 +0000438 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000439
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000440 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000441 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000442 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000443 if (FrameworkName.empty() || FrameworkName.back() != '/')
444 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000445
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000446 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000447 StringRef ModuleName(Filename.begin(), SlashPos);
448 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000449
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000450 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
451 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000452
Daniel Dunbar17138612012-04-05 17:09:40 +0000453 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000454 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000455 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000456
Chris Lattner5ed76da2006-10-22 07:24:13 +0000457 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000458 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000459 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000460
Chris Lattner5ed76da2006-10-22 07:24:13 +0000461 // Otherwise, if it does, remember that this is the right direntry for this
462 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000463 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000464
465 // If this is a user search directory, check if the framework has been
466 // user-specified as a system framework.
467 if (getDirCharacteristic() == SrcMgr::C_User) {
468 SmallString<1024> SystemFrameworkMarker(FrameworkName);
469 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000470 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000471 CacheEntry.IsUserSpecifiedSystemFramework = true;
472 }
473 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000474 }
Mike Stump11289f42009-09-09 15:08:12 +0000475
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000476 // Set the 'user-specified system framework' flag.
477 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
478
Craig Topperd2d442c2014-05-17 23:10:59 +0000479 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000480 RelativePath->clear();
481 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
482 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000483
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000484 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000485 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000486
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000487 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000488
Craig Topperd2d442c2014-05-17 23:10:59 +0000489 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000490 SearchPath->clear();
491 // Without trailing '/'.
492 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
493 }
494
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000495 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000496 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000497 /*openFile=*/!SuggestedModule);
498 if (!FE) {
499 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
500 const char *Private = "Private";
501 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
502 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000503 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000504 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
505 Private+strlen(Private));
506
Yaron Keren92e1b622015-03-18 10:17:07 +0000507 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000510 // If we found the header and are allowed to suggest a module, do so now.
511 if (FE && SuggestedModule) {
512 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000513 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000514 bool FoundFramework = false;
515 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000516 // Determine whether this directory exists.
517 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
518 if (!Dir)
519 break;
520
521 // If this is a framework directory, then we're a subframework of this
522 // framework.
523 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
524 FoundFramework = true;
525 break;
526 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000527
528 // Get the parent directory name.
529 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
530 if (FrameworkPath.empty())
531 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000532 } while (true);
533
Richard Smith3d5b48c2015-10-16 21:42:56 +0000534 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000535 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000536 if (!HS.findUsableModuleForFrameworkHeader(
537 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
538 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000539 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000540 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
541 SuggestedModule, IsSystem))
542 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000543 }
544 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000545 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000546}
547
Douglas Gregor89929282012-01-30 06:01:29 +0000548void HeaderSearch::setTarget(const TargetInfo &Target) {
549 ModMap.setTarget(Target);
550}
551
Chris Lattnerf62f7582007-12-17 07:52:39 +0000552
Chris Lattner712e3872007-12-17 08:13:48 +0000553//===----------------------------------------------------------------------===//
554// Header File Location.
555//===----------------------------------------------------------------------===//
556
Reid Klecknera97d4c02014-02-18 23:49:24 +0000557/// \brief Return true with a diagnostic if the file that MSVC would have found
558/// fails to match the one that Clang would have found with MSVC header search
559/// disabled.
560static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
561 const FileEntry *MSFE, const FileEntry *FE,
562 SourceLocation IncludeLoc) {
563 if (MSFE && FE != MSFE) {
564 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
565 return true;
566 }
567 return false;
568}
Chris Lattner712e3872007-12-17 08:13:48 +0000569
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000570static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
571 assert(!Str.empty());
572 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
573 std::copy(Str.begin(), Str.end(), CopyStr);
574 CopyStr[Str.size()] = '\0';
575 return CopyStr;
576}
577
James Dennettc07ab2c2012-06-20 00:56:32 +0000578/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000579/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000580/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
581/// non-empty, indicates where the \#including file(s) are, in case a relative
582/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000583const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000584 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
585 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000586 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
587 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000588 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Manman Rene4a5d372016-05-17 02:15:12 +0000589 bool SkipCache, bool BuildSystemModule) {
Douglas Gregor97eec242011-09-15 22:00:41 +0000590 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000591 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000592
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000593 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000594 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000595 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000596
597 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000598 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000599
Craig Topperd2d442c2014-05-17 23:10:59 +0000600 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000601 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000602 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000603 RelativePath->clear();
604 RelativePath->append(Filename.begin(), Filename.end());
605 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000606 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000607 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000608 /*IsSystemHeaderDir*/false,
609 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000610 }
Mike Stump11289f42009-09-09 15:08:12 +0000611
Reid Klecknera97d4c02014-02-18 23:49:24 +0000612 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000613 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000614 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000615
Douglas Gregor9f93e382011-07-28 04:45:53 +0000616 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000617 // directory. This cannot be based on CurDir, because each includer could be
618 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
619 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000620 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000621 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000622 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000623 bool First = true;
624 for (const auto &IncluderAndDir : Includers) {
625 const FileEntry *Includer = IncluderAndDir.first;
626
Will Wilson0fafd342013-12-27 19:46:16 +0000627 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000628 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000629 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000630 TmpDir.push_back('/');
631 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000632
Richard Smith6f548ec2014-03-06 18:08:08 +0000633 // FIXME: We don't cache the result of getFileInfo across the call to
634 // getFileAndSuggestModule, because it's a reference to an element of
635 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000636 //
Manman Rene4a5d372016-05-17 02:15:12 +0000637 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000638 // from a module build. We should treat this as a system header if we're
639 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000640 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000641 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
642 BuildSystemModule;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000643 if (const FileEntry *FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000644 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000645 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000646 if (!Includer) {
647 assert(First && "only first includer can have no file");
648 return FE;
649 }
650
Will Wilson0fafd342013-12-27 19:46:16 +0000651 // Leave CurDir unset.
652 // This file is a system header or C++ unfriendly if the old file is.
653 //
654 // Note that we only use one of FromHFI/ToHFI at once, due to potential
655 // reallocation of the underlying vector potentially making the first
656 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000657 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000658 unsigned DirInfo = FromHFI.DirInfo;
659 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
660 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000661
Will Wilson0fafd342013-12-27 19:46:16 +0000662 HeaderFileInfo &ToHFI = getFileInfo(FE);
663 ToHFI.DirInfo = DirInfo;
664 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
665 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000666
Craig Topperd2d442c2014-05-17 23:10:59 +0000667 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000668 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000669 SearchPath->clear();
670 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
671 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000672 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000673 RelativePath->clear();
674 RelativePath->append(Filename.begin(), Filename.end());
675 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000676 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000677 return FE;
678
679 // Otherwise, we found the path via MSVC header search rules. If
680 // -Wmsvc-include is enabled, we have to keep searching to see if we
681 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000682 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000683 return FE;
684 } else {
685 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000686 if (SuggestedModule) {
687 MSSuggestedModule = *SuggestedModule;
688 *SuggestedModule = ModuleMap::KnownHeader();
689 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000690 break;
691 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000692 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000693 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000694 }
695 }
Mike Stump11289f42009-09-09 15:08:12 +0000696
Craig Topperd2d442c2014-05-17 23:10:59 +0000697 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000698
699 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000700 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000701
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000702 // If this is a #include_next request, start searching after the directory the
703 // file was found in.
704 if (FromDir)
705 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattnerd4275422007-07-22 07:28:00 +0000707 // Cache all of the lookups performed by this method. Many headers are
708 // multiply included, and the "pragma once" optimization prevents them from
709 // being relex/pp'd, but they would still have to search through a
710 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000711 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000712
713 // If the entry has been previously looked up, the first value will be
714 // non-zero. If the value is equal to i (the start point of our search), then
715 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000716 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000717 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000718 i = CacheLookup.HitIdx;
719 if (CacheLookup.MappedName)
720 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000721 } else {
722 // Otherwise, this is the first query, or the previous query didn't match
723 // our search start. We will fill in our found location below, so prime the
724 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000725 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000726 }
Mike Stump11289f42009-09-09 15:08:12 +0000727
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000728 SmallString<64> MappedName;
729
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000730 // Check each directory in sequence to see if it contains this file.
731 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000732 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000733 bool HasBeenMapped = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000734 const FileEntry *FE = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000735 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000736 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
737 MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000738 if (HasBeenMapped) {
739 CacheLookup.MappedName =
740 copyString(Filename, LookupFileCache.getAllocator());
741 }
Chris Lattner712e3872007-12-17 08:13:48 +0000742 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000743
Chris Lattner712e3872007-12-17 08:13:48 +0000744 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattner712e3872007-12-17 08:13:48 +0000746 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000747 HeaderFileInfo &HFI = getFileInfo(FE);
748 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000749
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000750 // If the directory characteristic is User but this framework was
751 // user-specified to be treated as a system framework, promote the
752 // characteristic.
753 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
754 HFI.DirInfo = SrcMgr::C_System;
755
Richard Smith8acadcb2012-06-13 20:27:03 +0000756 // If the filename matches a known system header prefix, override
757 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000758 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
759 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
760 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000761 : SrcMgr::C_User;
762 break;
763 }
764 }
765
Douglas Gregor9f93e382011-07-28 04:45:53 +0000766 // If this file is found in a header map and uses the framework style of
767 // includes, then this header is part of a framework we're building.
768 if (CurDir->isIndexHeaderMap()) {
769 size_t SlashPos = Filename.find('/');
770 if (SlashPos != StringRef::npos) {
771 HFI.IndexHeaderMapHeader = 1;
772 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
773 SlashPos));
774 }
775 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000776
Richard Smith8c71eba2014-03-05 20:51:45 +0000777 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
778 if (SuggestedModule)
779 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000780 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000781 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000782
Chris Lattner712e3872007-12-17 08:13:48 +0000783 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000784 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000785 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Douglas Gregord8575e12011-07-30 06:28:34 +0000788 // If we are including a file with a quoted include "foo.h" from inside
789 // a header in a framework that is currently being built, and we couldn't
790 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
791 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000792 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000793 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000794 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000795 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000796 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000797 ScratchFilename += IncludingHFI.Framework;
798 ScratchFilename += '/';
799 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000800
Richard Smith3d5b48c2015-10-16 21:42:56 +0000801 const FileEntry *FE =
802 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
803 CurDir, Includers.front(), SearchPath, RelativePath,
804 RequestingModule, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000805
Richard Smith8c71eba2014-03-05 20:51:45 +0000806 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
807 if (SuggestedModule)
808 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000809 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000810 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000811
David Blaikie3c8c46e2014-11-19 05:48:40 +0000812 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000813 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000814 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000815 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000816 }
817 }
818
Craig Topperd2d442c2014-05-17 23:10:59 +0000819 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000820 if (SuggestedModule)
821 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000822 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000823 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000824
Chris Lattnerd4275422007-07-22 07:28:00 +0000825 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000826 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000827 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000828}
829
Chris Lattner63dd32b2006-10-20 04:42:40 +0000830/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000831/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000832/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
833/// is a subframework within Carbon.framework. If so, return the FileEntry
834/// for the designated file, otherwise return null.
835const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000836LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000837 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000838 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000839 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000840 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000841 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000842 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000843
Chris Lattner63dd32b2006-10-20 04:42:40 +0000844 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000845 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000846 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000847 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Chris Lattner63dd32b2006-10-20 04:42:40 +0000849 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +0000850 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattner63dd32b2006-10-20 04:42:40 +0000852 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000853 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +0000854 auto FrameworkPos = ContextName.find(".framework");
855 if (FrameworkPos == StringRef::npos ||
856 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
857 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000858 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Mehdi Amini004b9c72016-10-10 22:52:47 +0000860 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
861 FrameworkPos +
862 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000863
Chris Lattner63dd32b2006-10-20 04:42:40 +0000864 // Append Frameworks/HIToolbox.framework/
865 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000866 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000867 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000868
David Blaikie13156b62014-11-19 03:06:06 +0000869 auto &CacheLookup =
870 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
871 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattner5ed76da2006-10-22 07:24:13 +0000873 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000874 if (CacheLookup.second.Directory &&
875 CacheLookup.first().size() == FrameworkName.size() &&
876 memcmp(CacheLookup.first().data(), &FrameworkName[0],
877 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000878 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattner5ed76da2006-10-22 07:24:13 +0000880 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000881 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000882 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattner5ed76da2006-10-22 07:24:13 +0000884 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000885 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000886 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000887
Chris Lattner5ed76da2006-10-22 07:24:13 +0000888 // Otherwise, if it does, remember that this is the right direntry for this
889 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000890 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
Craig Topperd2d442c2014-05-17 23:10:59 +0000893 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000894
Craig Topperd2d442c2014-05-17 23:10:59 +0000895 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000896 RelativePath->clear();
897 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
898 }
899
Chris Lattner63dd32b2006-10-20 04:42:40 +0000900 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000901 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000902 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000903 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000904 SearchPath->clear();
905 // Without trailing '/'.
906 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
907 }
908
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000909 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000910 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000911
Chris Lattner63dd32b2006-10-20 04:42:40 +0000912 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000913 HeadersFilename = FrameworkName;
914 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000915 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000916 SearchPath->clear();
917 // Without trailing '/'.
918 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
919 }
920
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000921 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000922 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000923 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Chris Lattner577377e2006-10-20 04:55:45 +0000926 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000927 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000928 // Note that the temporary 'DirInfo' is required here, as either call to
929 // getFileInfo could resize the vector and we don't want to rely on order
930 // of evaluation.
931 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
932 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000933
Richard Smith3d5b48c2015-10-16 21:42:56 +0000934 FrameworkName.pop_back(); // remove the trailing '/'
935 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
936 SuggestedModule, /*IsSystem*/ false))
937 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000938
Chris Lattner577377e2006-10-20 04:55:45 +0000939 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000940}
941
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000942//===----------------------------------------------------------------------===//
943// File Info Management.
944//===----------------------------------------------------------------------===//
945
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000946/// \brief Merge the header file info provided by \p OtherHFI into the current
947/// header file info (\p HFI)
948static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
949 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +0000950 assert(OtherHFI.External && "expected to merge external HFI");
951
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000952 HFI.isImport |= OtherHFI.isImport;
953 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000954 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000955 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +0000956
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000957 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
958 HFI.ControllingMacro = OtherHFI.ControllingMacro;
959 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
960 }
Richard Smithd8879c82015-08-24 21:59:32 +0000961
962 HFI.DirInfo = OtherHFI.DirInfo;
963 HFI.External = (!HFI.IsValid || HFI.External);
964 HFI.IsValid = true;
965 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000966
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000967 if (HFI.Framework.empty())
968 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000969}
970
Steve Naroff3fa455a2009-04-24 20:03:17 +0000971/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000972/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000973HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000974 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +0000975 FileInfo.resize(FE->getUID() + 1);
976
Richard Smithd8879c82015-08-24 21:59:32 +0000977 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +0000978 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +0000979 if (ExternalSource && !HFI->Resolved) {
980 HFI->Resolved = true;
981 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
982
983 HFI = &FileInfo[FE->getUID()];
984 if (ExternalHFI.External)
985 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +0000986 }
987
Richard Smithd8879c82015-08-24 21:59:32 +0000988 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +0000989 // We have local information about this header file, so it's no longer
990 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +0000991 HFI->External = false;
992 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +0000993}
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000994
Richard Smith386bb072015-08-18 23:42:23 +0000995const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +0000996HeaderSearch::getExistingFileInfo(const FileEntry *FE,
997 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +0000998 // If we have an external source, ensure we have the latest information.
999 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001000 HeaderFileInfo *HFI;
1001 if (ExternalSource) {
1002 if (FE->getUID() >= FileInfo.size()) {
1003 if (!WantExternal)
1004 return nullptr;
1005 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001006 }
Richard Smithd8879c82015-08-24 21:59:32 +00001007
1008 HFI = &FileInfo[FE->getUID()];
1009 if (!WantExternal && (!HFI->IsValid || HFI->External))
1010 return nullptr;
1011 if (!HFI->Resolved) {
1012 HFI->Resolved = true;
1013 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1014
1015 HFI = &FileInfo[FE->getUID()];
1016 if (ExternalHFI.External)
1017 mergeHeaderFileInfo(*HFI, ExternalHFI);
1018 }
1019 } else if (FE->getUID() >= FileInfo.size()) {
1020 return nullptr;
1021 } else {
1022 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001023 }
Richard Smith386bb072015-08-18 23:42:23 +00001024
Richard Smithd8879c82015-08-24 21:59:32 +00001025 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001026 return nullptr;
1027
Richard Smithd8879c82015-08-24 21:59:32 +00001028 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001029}
1030
Douglas Gregor37aa4932011-05-04 00:14:37 +00001031bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1032 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001033 if (auto *HFI = getExistingFileInfo(File))
1034 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1035 HFI->ControllingMacroID;
1036 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001037}
1038
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001039void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001040 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001041 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001042 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1043
1044 // Don't mark the file info as non-external if there's nothing to change.
1045 if (!isCompilingModuleHeader) {
1046 if (!isModularHeader)
1047 return;
1048 auto *HFI = getExistingFileInfo(FE);
1049 if (HFI && HFI->isModuleHeader)
1050 return;
1051 }
1052
Richard Smith386bb072015-08-18 23:42:23 +00001053 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001054 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001055 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001056}
1057
Richard Smith20e883e2015-04-29 23:20:19 +00001058bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1059 const FileEntry *File,
Richard Smith035f6dc2015-07-01 01:51:38 +00001060 bool isImport, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001061 ++NumIncluded; // Count # of attempted #includes.
1062
1063 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001064 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001066 // If this is a #import directive, check that we have not already imported
1067 // this header.
1068 if (isImport) {
1069 // If this has already been imported, don't import it again.
1070 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001072 // Has this already been #import'ed or #include'd?
1073 if (FileInfo.NumIncludes) return false;
1074 } else {
1075 // Otherwise, if this is a #include of a file that was previously #import'd
1076 // or if this is the second #include of a #pragma once file, ignore it.
1077 if (FileInfo.isImport)
1078 return false;
1079 }
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001081 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1082 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001083 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001084 = FileInfo.getControllingMacro(ExternalLookup)) {
1085 // If the header corresponds to a module, check whether the macro is already
1086 // defined in that module rather than checking in the current set of visible
1087 // modules.
1088 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1089 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001090 ++NumMultiIncludeFileOptzn;
1091 return false;
1092 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001093 }
Mike Stump11289f42009-09-09 15:08:12 +00001094
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001095 // Increment the number of times this file has been included.
1096 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001097
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001098 return true;
1099}
1100
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001101size_t HeaderSearch::getTotalMemory() const {
1102 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001103 + llvm::capacity_in_bytes(FileInfo)
1104 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001105 + LookupFileCache.getAllocator().getTotalMemory()
1106 + FrameworkMap.getAllocator().getTotalMemory();
1107}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001108
1109StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001110 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001111}
Douglas Gregor718292f2011-11-11 19:10:28 +00001112
1113bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001114 const DirectoryEntry *Root,
1115 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001116 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001117 return false;
1118
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001119 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001120
1121 StringRef DirName = FileName;
1122 do {
1123 // Get the parent directory name.
1124 DirName = llvm::sys::path::parent_path(DirName);
1125 if (DirName.empty())
1126 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001127
Douglas Gregor718292f2011-11-11 19:10:28 +00001128 // Determine whether this directory exists.
1129 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1130 if (!Dir)
1131 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001132
Ben Langmuir984e1df2014-03-19 20:23:34 +00001133 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001134 switch (loadModuleMapFile(Dir, IsSystem,
1135 llvm::sys::path::extension(Dir->getName()) ==
1136 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001137 case LMM_NewlyLoaded:
1138 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001139 // Success. All of the directories we stepped through inherit this module
1140 // map file.
1141 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1142 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1143 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001144
1145 case LMM_NoDirectory:
1146 case LMM_InvalidModuleMap:
1147 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001148 }
1149
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001150 // If we hit the top of our search, we're done.
1151 if (Dir == Root)
1152 return false;
1153
Douglas Gregor718292f2011-11-11 19:10:28 +00001154 // Keep track of all of the directories we checked, so we can mark them as
1155 // having module maps if we eventually do find a module map.
1156 FixUpDirectories.push_back(Dir);
1157 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001158}
1159
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001160ModuleMap::KnownHeader
1161HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001162 if (ExternalSource) {
1163 // Make sure the external source has handled header info about this file,
1164 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001165 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001166 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001167 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001168}
1169
Richard Smith3d5b48c2015-10-16 21:42:56 +00001170bool HeaderSearch::findUsableModuleForHeader(
1171 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1172 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1173 if (File && SuggestedModule) {
1174 // If there is a module that corresponds to this header, suggest it.
1175 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1176 *SuggestedModule = findModuleForHeader(File);
1177 }
1178 return true;
1179}
1180
1181bool HeaderSearch::findUsableModuleForFrameworkHeader(
1182 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1183 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1184 // If we're supposed to suggest a module, look for one now.
1185 if (SuggestedModule) {
1186 // Find the top-level framework based on this framework.
1187 SmallVector<std::string, 4> SubmodulePath;
1188 const DirectoryEntry *TopFrameworkDir
1189 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1190
1191 // Determine the name of the top-level framework.
1192 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1193
1194 // Load this framework module. If that succeeds, find the suggested module
1195 // for this header, if any.
1196 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1197
1198 // FIXME: This can find a module not part of ModuleName, which is
1199 // important so that we're consistent about whether this header
1200 // corresponds to a module. Possibly we should lock down framework modules
1201 // so that this is not possible.
1202 *SuggestedModule = findModuleForHeader(File);
1203 }
1204 return true;
1205}
1206
Richard Smith9acb99e32014-12-10 03:09:48 +00001207static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001208 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001209 StringRef Filename = llvm::sys::path::filename(File->getName());
1210 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001211 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001212 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001213 else if (Filename == "module.modulemap")
1214 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1215 else
1216 return nullptr;
1217 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001218}
1219
Ben Langmuir984e1df2014-03-19 20:23:34 +00001220bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001221 // Find the directory for the module. For frameworks, that may require going
1222 // up from the 'Modules' directory.
1223 const DirectoryEntry *Dir = nullptr;
1224 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1225 Dir = FileMgr.getDirectory(".");
1226 else {
1227 Dir = File->getDir();
1228 StringRef DirName(Dir->getName());
1229 if (llvm::sys::path::filename(DirName) == "Modules") {
1230 DirName = llvm::sys::path::parent_path(DirName);
1231 if (DirName.endswith(".framework"))
1232 Dir = FileMgr.getDirectory(DirName);
1233 // FIXME: This assert can fail if there's a race between the above check
1234 // and the removal of the directory.
1235 assert(Dir && "parent must exist");
1236 }
1237 }
1238
1239 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001240 case LMM_AlreadyLoaded:
1241 case LMM_NewlyLoaded:
1242 return false;
1243 case LMM_NoDirectory:
1244 case LMM_InvalidModuleMap:
1245 return true;
1246 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001247 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001248}
1249
1250HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001251HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1252 const DirectoryEntry *Dir) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001253 assert(File && "expected FileEntry");
1254
Richard Smith9887d792014-10-17 01:42:53 +00001255 // Check whether we've already loaded this module map, and mark it as being
1256 // loaded in case we recursively try to load it from itself.
1257 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1258 if (!AddResult.second)
1259 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001260
Richard Smith9acb99e32014-12-10 03:09:48 +00001261 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001262 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001263 return LMM_InvalidModuleMap;
1264 }
1265
1266 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001267 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1268 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001269 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001270 return LMM_InvalidModuleMap;
1271 }
1272 }
1273
1274 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001275 return LMM_NewlyLoaded;
1276}
1277
1278const FileEntry *
1279HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001280 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001281 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001282 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1283 // module.map at the framework root is also accepted.
1284 SmallString<128> ModuleMapFileName(Dir->getName());
1285 if (IsFramework)
1286 llvm::sys::path::append(ModuleMapFileName, "Modules");
1287 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1288 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1289 return F;
1290
1291 // Continue to allow module.map
1292 ModuleMapFileName = Dir->getName();
1293 llvm::sys::path::append(ModuleMapFileName, "module.map");
1294 return FileMgr.getFile(ModuleMapFileName);
1295}
1296
1297Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001298 const DirectoryEntry *Dir,
1299 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001300 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001301 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001302
Douglas Gregor56c64012011-11-17 01:41:17 +00001303 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001304 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001305 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001306 // Try to infer a module map from the framework directory.
1307 if (HSOpts->ImplicitModuleMaps)
1308 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001309 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001310
Douglas Gregor56c64012011-11-17 01:41:17 +00001311 case LMM_AlreadyLoaded:
1312 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001313 return nullptr;
1314
Douglas Gregor56c64012011-11-17 01:41:17 +00001315 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001316 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001317 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001318
Ben Langmuira5254002015-07-02 13:19:48 +00001319 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001320}
1321
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001322
Douglas Gregor80b69042011-11-12 00:22:19 +00001323HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001324HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1325 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001326 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001327 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001328
Douglas Gregor80b69042011-11-12 00:22:19 +00001329 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001330}
1331
Douglas Gregor80b69042011-11-12 00:22:19 +00001332HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001333HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1334 bool IsFramework) {
1335 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001336 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001337 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001338
Ben Langmuir984e1df2014-03-19 20:23:34 +00001339 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001340 LoadModuleMapResult Result =
1341 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001342 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1343 // E.g. Foo.framework/Modules/module.modulemap
1344 // ^Dir ^ModuleMapFile
1345 if (Result == LMM_NewlyLoaded)
1346 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001347 else if (Result == LMM_InvalidModuleMap)
1348 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001349 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001350 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001351 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001352}
Douglas Gregor718292f2011-11-11 19:10:28 +00001353
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001354void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001355 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001356
Richard Smith47972af2015-06-16 00:08:24 +00001357 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001358 // Load module maps for each of the header search directories.
1359 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1360 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1361 if (SearchDirs[Idx].isFramework()) {
1362 std::error_code EC;
1363 SmallString<128> DirNative;
1364 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1365 DirNative);
1366
1367 // Search each of the ".framework" directories to load them as modules.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001368 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1369 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001370 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001371 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001372 continue;
1373
1374 const DirectoryEntry *FrameworkDir =
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001375 FileMgr.getDirectory(Dir->getName());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001376 if (!FrameworkDir)
1377 continue;
1378
1379 // Load this framework module.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001380 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1381 FrameworkDir, IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001382 }
1383 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001384 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001385
1386 // FIXME: Deal with header maps.
1387 if (SearchDirs[Idx].isHeaderMap())
1388 continue;
1389
1390 // Try to load a module map file for the search directory.
1391 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1392 /*IsFramework*/ false);
1393
1394 // Try to load module map files for immediate subdirectories of this
1395 // search directory.
1396 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001397 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001398 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001399
Douglas Gregor07f43572012-01-29 18:15:03 +00001400 // Populate the list of modules.
1401 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1402 MEnd = ModMap.module_end();
1403 M != MEnd; ++M) {
1404 Modules.push_back(M->getValue());
1405 }
1406}
Douglas Gregor0339a642013-03-21 01:08:50 +00001407
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001408void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001409 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001410 return;
1411
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001412 // Load module maps for each of the header search directories.
1413 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001414 // We only care about normal header directories.
1415 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001416 continue;
1417 }
1418
1419 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001420 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001421 SearchDirs[Idx].isSystemHeaderDirectory(),
1422 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001423 }
1424}
1425
Douglas Gregor0339a642013-03-21 01:08:50 +00001426void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001427 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001428 "Should not be loading subdirectory module maps");
1429
Douglas Gregor0339a642013-03-21 01:08:50 +00001430 if (SearchDir.haveSearchedAllModuleMaps())
1431 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001432
1433 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001434 SmallString<128> DirNative;
1435 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001436 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1437 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001438 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001439 bool IsFramework =
1440 llvm::sys::path::extension(Dir->getName()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001441 if (IsFramework == SearchDir.isFramework())
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001442 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001443 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001444 }
1445
1446 SearchDir.setSearchedAllModuleMaps(true);
1447}
Richard Smith4eb83932016-04-27 21:57:05 +00001448
1449std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1450 bool *IsSystem) {
1451 // FIXME: We assume that the path name currently cached in the FileEntry is
1452 // the most appropriate one for this analysis (and that it's spelled the same
1453 // way as the corresponding header search path).
Mehdi Amini004b9c72016-10-10 22:52:47 +00001454 StringRef Name = File->getName();
Richard Smith4eb83932016-04-27 21:57:05 +00001455
1456 unsigned BestPrefixLength = 0;
1457 unsigned BestSearchDir;
1458
1459 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1460 // FIXME: Support this search within frameworks and header maps.
1461 if (!SearchDirs[I].isNormalDir())
1462 continue;
1463
1464 const char *Dir = SearchDirs[I].getDir()->getName();
1465 for (auto NI = llvm::sys::path::begin(Name),
1466 NE = llvm::sys::path::end(Name),
1467 DI = llvm::sys::path::begin(Dir),
1468 DE = llvm::sys::path::end(Dir);
1469 /*termination condition in loop*/; ++NI, ++DI) {
1470 // '.' components in Name are ignored.
1471 while (NI != NE && *NI == ".")
1472 ++NI;
1473 if (NI == NE)
1474 break;
1475
1476 // '.' components in Dir are ignored.
1477 while (DI != DE && *DI == ".")
1478 ++DI;
1479 if (DI == DE) {
1480 // Dir is a prefix of Name, up to '.' components and choice of path
1481 // separators.
1482 unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1483 if (PrefixLength > BestPrefixLength) {
1484 BestPrefixLength = PrefixLength;
1485 BestSearchDir = I;
1486 }
1487 break;
1488 }
1489
1490 if (*NI != *DI)
1491 break;
1492 }
1493 }
1494
1495 if (IsSystem)
1496 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001497 return Name.drop_front(BestPrefixLength);
Richard Smith4eb83932016-04-27 21:57:05 +00001498}