blob: 3528f8820fca7a8c63982fab147fac9f7ebc8202 [file] [log] [blame]
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001//===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
Chris Lattner59a9ebd2006-10-18 05:34:33 +00002//
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"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000018#include "clang/Basic/Module.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/VirtualFileSystem.h"
21#include "clang/Lex/DirectoryLookup.h"
Richard Smith2aedca32015-07-01 02:29:35 +000022#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/HeaderMap.h"
24#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000025#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000026#include "clang/Lex/ModuleMap.h"
Richard Smith20e883e2015-04-29 23:20:19 +000027#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000028#include "llvm/ADT/APInt.h"
29#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000030#include "llvm/ADT/SmallString.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000031#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/Allocator.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000034#include "llvm/Support/Capacity.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000035#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "llvm/Support/FileSystem.h"
37#include "llvm/Support/Path.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
Chris Lattnerc25d8a72009-03-02 22:20:04 +000041#include <cstdio>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000042#include <cstring>
43#include <string>
44#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000045#include <utility>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000046
Chris Lattner59a9ebd2006-10-18 05:34:33 +000047using namespace clang;
48
Douglas Gregor99734e72009-04-25 23:30:02 +000049const IdentifierInfo *
Richard Smith2aedca32015-07-01 02:29:35 +000050HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
51 if (ControllingMacro) {
Chandler Carruth59666772016-11-04 06:32:57 +000052 if (ControllingMacro->isOutOfDate()) {
53 assert(External && "We must have an external source if we have a "
54 "controlling macro that is out of date.");
Richard Smith2aedca32015-07-01 02:29:35 +000055 External->updateOutOfDateIdentifier(
56 *const_cast<IdentifierInfo *>(ControllingMacro));
Chandler Carruth59666772016-11-04 06:32:57 +000057 }
Douglas Gregor99734e72009-04-25 23:30:02 +000058 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000059 }
Douglas Gregor99734e72009-04-25 23:30:02 +000060
61 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000062 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000063
64 ControllingMacro = External->GetIdentifier(ControllingMacroID);
65 return ControllingMacro;
66}
67
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000068ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
Douglas Gregor09b69892011-02-10 17:09:37 +000069
David Blaikie9c28cb32017-01-06 01:04:46 +000070HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000071 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000072 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000073 const TargetInfo *Target)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000074 : HSOpts(std::move(HSOpts)), Diags(Diags),
75 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000076 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
Chris Lattner641a0be2006-10-20 06:23:14 +000077
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000078HeaderSearch::~HeaderSearch() {
79 // Delete headermaps.
80 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
81 delete HeaderMaps[i].second;
82}
Mike Stump11289f42009-09-09 15:08:12 +000083
Chris Lattner59a9ebd2006-10-18 05:34:33 +000084void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000085 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
86 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000087 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
88 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
89 NumOnceOnlyFiles += FileInfo[i].isImport;
90 if (MaxNumIncludes < FileInfo[i].NumIncludes)
91 MaxNumIncludes = FileInfo[i].NumIncludes;
92 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
93 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000094 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
95 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
96 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000097
Chris Lattner23b7eb62007-06-15 23:05:46 +000098 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
99 fprintf(stderr, " %d #includes skipped due to"
100 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +0000101
Chris Lattner23b7eb62007-06-15 23:05:46 +0000102 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
103 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000104}
105
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000106/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000107/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000108const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000109 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000110 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000111 if (!HeaderMaps.empty()) {
112 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000113 // Pointer equality comparison of FileEntries works because they are
114 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000115 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000116 return HeaderMaps[i].second;
117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Chris Lattner5159f612010-11-23 08:35:12 +0000119 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000120 HeaderMaps.push_back(std::make_pair(FE, HM));
121 return HM;
122 }
Mike Stump11289f42009-09-09 15:08:12 +0000123
Craig Topperd2d442c2014-05-17 23:10:59 +0000124 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000125}
126
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000127/// \brief Get filenames for all registered header maps.
128void HeaderSearch::getHeaderMapFileNames(
129 SmallVectorImpl<std::string> &Names) const {
130 for (auto &HM : HeaderMaps)
131 Names.push_back(HM.first->getName());
132}
133
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000134std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000135 const FileEntry *ModuleMap =
136 getModuleMap().getModuleMapFileForUniquing(Module);
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000137 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000138}
139
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000140std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
141 bool FileMapOnly) {
142 // First check the module name to pcm file map.
143 auto i (HSOpts->PrebuiltModuleFiles.find(ModuleName));
144 if (i != HSOpts->PrebuiltModuleFiles.end())
145 return i->second;
146
147 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000148 return {};
Manman Ren11f2a472016-08-18 17:42:15 +0000149
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000150 // Then go through each prebuilt module directory and try to find the pcm
151 // file.
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000152 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
153 SmallString<256> Result(Dir);
154 llvm::sys::fs::make_absolute(Result);
155 llvm::sys::path::append(Result, ModuleName + ".pcm");
156 if (getFileMgr().getFile(Result.str()))
157 return Result.str().str();
Manman Ren11f2a472016-08-18 17:42:15 +0000158 }
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000159 return {};
160}
Manman Ren11f2a472016-08-18 17:42:15 +0000161
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000162std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
163 StringRef ModuleMapPath) {
Richard Smithd520a252015-07-21 18:07:47 +0000164 // If we don't have a module cache path or aren't supposed to use one, we
165 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000166 if (getModuleCachePath().empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000167 return {};
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000168
Richard Smith3938f0c2015-08-15 00:34:15 +0000169 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000170 llvm::sys::fs::make_absolute(Result);
171
172 if (HSOpts->DisableModuleHash) {
173 llvm::sys::path::append(Result, ModuleName + ".pcm");
174 } else {
175 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000176 // ideally be globally unique to this particular module. Name collisions
177 // in the hash are safe (because any translation unit can only import one
178 // module with each name), but result in a loss of caching.
179 //
180 // To avoid false-negatives, we form as canonical a path as we can, and map
181 // to lower-case in case we're on a case-insensitive file system.
Richard Smith3f57cff2017-03-09 00:58:22 +0000182 std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
183 if (Parent.empty())
184 Parent = ".";
185 auto *Dir = FileMgr.getDirectory(Parent);
Richard Smith54cc3c22014-12-11 20:50:24 +0000186 if (!Dir)
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000187 return {};
Richard Smith54cc3c22014-12-11 20:50:24 +0000188 auto DirName = FileMgr.getCanonicalName(Dir);
189 auto FileName = llvm::sys::path::filename(ModuleMapPath);
190
191 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000192 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000193
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000194 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000195 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000196 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000197 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000198 return Result.str().str();
199}
200
201Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000202 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000203 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000204 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000205 return Module;
Graydon Hoare4d867642016-12-21 00:24:39 +0000206
207 StringRef SearchName = ModuleName;
208 Module = lookupModule(ModuleName, SearchName);
209
210 // The facility for "private modules" -- adjacent, optional module maps named
211 // module.private.modulemap that are supposed to define private submodules --
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000212 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
213 //
214 // Foo.Private is now depracated in favor of Foo_Private. Users of FooPrivate
215 // should also rename to Foo_Private. Representing private as submodules
216 // could force building unwanted dependencies into the parent module and cause
217 // dependency cycles.
218 if (!Module && SearchName.consume_back("_Private"))
219 Module = lookupModule(ModuleName, SearchName);
Graydon Hoare4d867642016-12-21 00:24:39 +0000220 if (!Module && SearchName.consume_back("Private"))
221 Module = lookupModule(ModuleName, SearchName);
222 return Module;
223}
224
225Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName) {
226 Module *Module = nullptr;
227
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000228 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000229 // maps, searching for a module map that describes this module.
230 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
231 if (SearchDirs[Idx].isFramework()) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000232 // Search for or infer a module map for a framework. Here we use
233 // SearchName rather than ModuleName, to permit finding private modules
234 // named FooPrivate in buggy frameworks named Foo.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000235 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000236 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
Graydon Hoare4d867642016-12-21 00:24:39 +0000237 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
238 if (const DirectoryEntry *FrameworkDir
Douglas Gregor279a6c32012-01-29 17:08:11 +0000239 = FileMgr.getDirectory(FrameworkDirName)) {
240 bool IsSystem
241 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
242 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000243 if (Module)
244 break;
245 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000246 }
247
248 // FIXME: Figure out how header maps and module maps will work together.
249
250 // Only deal with normal search directories.
251 if (!SearchDirs[Idx].isNormalDir())
252 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000253
254 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000255 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000256 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
257 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000258 // We just loaded a module map file; check whether the module is
259 // available now.
260 Module = ModMap.findModule(ModuleName);
261 if (Module)
262 break;
263 }
264
265 // Search for a module map in a subdirectory with the same name as the
266 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000267 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000268 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
269 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000270 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
271 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000272 // If we just loaded a module map file, look for the module again.
273 Module = ModMap.findModule(ModuleName);
274 if (Module)
275 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000276 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000277
278 // If we've already performed the exhaustive search for module maps in this
279 // search directory, don't do it again.
280 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
281 continue;
282
283 // Load all module maps in the immediate subdirectories of this search
284 // directory.
285 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
286
287 // Look again for the module.
288 Module = ModMap.findModule(ModuleName);
289 if (Module)
290 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000291 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000292
Douglas Gregor279a6c32012-01-29 17:08:11 +0000293 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000294}
295
Chris Lattnerf62f7582007-12-17 07:52:39 +0000296//===----------------------------------------------------------------------===//
297// File lookup within a DirectoryLookup scope
298//===----------------------------------------------------------------------===//
299
Chris Lattner8d720d02007-12-17 17:57:27 +0000300/// getName - Return the directory or filename corresponding to this lookup
301/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000302StringRef DirectoryLookup::getName() const {
Chris Lattner8d720d02007-12-17 17:57:27 +0000303 if (isNormalDir())
304 return getDir()->getName();
305 if (isFramework())
306 return getFrameworkDir()->getName();
307 assert(isHeaderMap() && "Unknown DirectoryLookup");
308 return getHeaderMap()->getFileName();
309}
310
Richard Smith3d5b48c2015-10-16 21:42:56 +0000311const FileEntry *HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000312 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
313 bool IsSystemHeaderDir, Module *RequestingModule,
314 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000315 // If we have a module map that might map this header, load it and
316 // check whether we'll have a suggestion for a module.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000317 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000318 if (!File)
319 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000320
Richard Smith3d5b48c2015-10-16 21:42:56 +0000321 // If there is a module that corresponds to this header, suggest it.
322 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
323 RequestingModule, SuggestedModule,
324 IsSystemHeaderDir))
325 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000326
Richard Smith3d5b48c2015-10-16 21:42:56 +0000327 return File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000328}
Chris Lattner8d720d02007-12-17 17:57:27 +0000329
Chris Lattnerf62f7582007-12-17 07:52:39 +0000330/// LookupFile - Lookup the specified file in this search path, returning it
331/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000332const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000333 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000334 HeaderSearch &HS,
Taewook Ohf42103c2016-06-13 20:40:21 +0000335 SourceLocation IncludeLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000337 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000338 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000339 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000340 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000341 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000342 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000343 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000344 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000345
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000346 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000347 if (isNormalDir()) {
348 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000349 TmpDir = getDir()->getName();
350 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000351 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000353 SearchPath->clear();
354 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
355 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000356 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000357 RelativePath->clear();
358 RelativePath->append(Filename.begin(), Filename.end());
359 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000360
Taewook Ohf42103c2016-06-13 20:40:21 +0000361 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000362 isSystemHeaderDirectory(),
363 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000364 }
Mike Stump11289f42009-09-09 15:08:12 +0000365
Chris Lattner712e3872007-12-17 08:13:48 +0000366 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000367 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000368 RequestingModule, SuggestedModule,
369 InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattner44bd21b2007-12-17 08:17:39 +0000371 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000372 const HeaderMap *HM = getHeaderMap();
373 SmallString<1024> Path;
374 StringRef Dest = HM->lookupFilename(Filename, Path);
375 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000376 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000377
378 const FileEntry *Result;
379
380 // Check if the headermap maps the filename to a framework include
381 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
382 // framework include.
383 if (llvm::sys::path::is_relative(Dest)) {
384 MappedName.clear();
385 MappedName.append(Dest.begin(), Dest.end());
386 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000387 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000388 Result = HM->LookupFile(Filename, HS.getFileMgr());
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000389 } else {
390 Result = HS.getFileMgr().getFile(Dest);
391 }
392
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000393 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000394 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000395 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000396 SearchPath->clear();
397 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
398 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000399 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000400 RelativePath->clear();
401 RelativePath->append(Filename.begin(), Filename.end());
402 }
403 }
404 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000405}
406
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000407/// \brief Given a framework directory, find the top-most framework directory.
408///
409/// \param FileMgr The file manager to use for directory lookups.
410/// \param DirName The name of the framework directory.
411/// \param SubmodulePath Will be populated with the submodule path from the
412/// returned top-level module to the originally named framework.
413static const DirectoryEntry *
414getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
415 SmallVectorImpl<std::string> &SubmodulePath) {
416 assert(llvm::sys::path::extension(DirName) == ".framework" &&
417 "Not a framework directory");
418
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000419 // Note: as an egregious but useful hack we use the real path here, because
420 // frameworks moving between top-level frameworks to embedded frameworks tend
421 // to be symlinked, and we base the logical structure of modules on the
422 // physical layout. In particular, we need to deal with crazy includes like
423 //
424 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
425 //
426 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
427 // which one should access with, e.g.,
428 //
429 // #include <Bar/Wibble.h>
430 //
431 // Similar issues occur when a top-level framework has moved into an
432 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000433 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000434 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000435 do {
436 // Get the parent directory name.
437 DirName = llvm::sys::path::parent_path(DirName);
438 if (DirName.empty())
439 break;
440
441 // Determine whether this directory exists.
442 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
443 if (!Dir)
444 break;
445
446 // If this is a framework directory, then we're a subframework of this
447 // framework.
448 if (llvm::sys::path::extension(DirName) == ".framework") {
449 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
450 TopFrameworkDir = Dir;
451 }
452 } while (true);
453
454 return TopFrameworkDir;
455}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000456
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000457static bool needModuleLookup(Module *RequestingModule,
458 bool HasSuggestedModule) {
459 return HasSuggestedModule ||
460 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
461}
462
Chris Lattner712e3872007-12-17 08:13:48 +0000463/// DoFrameworkLookup - Do a lookup of the specified file in the current
464/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000465const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000466 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
467 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000468 ModuleMap::KnownHeader *SuggestedModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000469 bool &InUserSpecifiedSystemFramework) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000470 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000471
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000472 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000473 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000474 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattner712e3872007-12-17 08:13:48 +0000476 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000477 // HeaderSearch. Possible answers are yes/no and unknown.
478 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000479 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattner712e3872007-12-17 08:13:48 +0000481 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000482 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000483 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000484
Chris Lattner712e3872007-12-17 08:13:48 +0000485 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000486
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000487 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000488 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000489 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000490 if (FrameworkName.empty() || FrameworkName.back() != '/')
491 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000492
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000493 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000494 StringRef ModuleName(Filename.begin(), SlashPos);
495 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000497 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
498 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000499
Daniel Dunbar17138612012-04-05 17:09:40 +0000500 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000501 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000502 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattner5ed76da2006-10-22 07:24:13 +0000504 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000505 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000506 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattner5ed76da2006-10-22 07:24:13 +0000508 // Otherwise, if it does, remember that this is the right direntry for this
509 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000510 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000511
512 // If this is a user search directory, check if the framework has been
513 // user-specified as a system framework.
514 if (getDirCharacteristic() == SrcMgr::C_User) {
515 SmallString<1024> SystemFrameworkMarker(FrameworkName);
516 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000517 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000518 CacheEntry.IsUserSpecifiedSystemFramework = true;
519 }
520 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000521 }
Mike Stump11289f42009-09-09 15:08:12 +0000522
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000523 // Set the 'user-specified system framework' flag.
524 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
525
Craig Topperd2d442c2014-05-17 23:10:59 +0000526 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000527 RelativePath->clear();
528 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
529 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000530
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000531 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000532 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000533
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000534 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000535
Craig Topperd2d442c2014-05-17 23:10:59 +0000536 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000537 SearchPath->clear();
538 // Without trailing '/'.
539 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
540 }
541
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000542 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000543 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000544 /*openFile=*/!SuggestedModule);
545 if (!FE) {
546 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
547 const char *Private = "Private";
548 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
549 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000550 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000551 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
552 Private+strlen(Private));
553
Yaron Keren92e1b622015-03-18 10:17:07 +0000554 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000555 }
Mike Stump11289f42009-09-09 15:08:12 +0000556
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000557 // If we found the header and are allowed to suggest a module, do so now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000558 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000559 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000560 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000561 bool FoundFramework = false;
562 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000563 // Determine whether this directory exists.
564 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
565 if (!Dir)
566 break;
567
568 // If this is a framework directory, then we're a subframework of this
569 // framework.
570 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
571 FoundFramework = true;
572 break;
573 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000574
575 // Get the parent directory name.
576 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
577 if (FrameworkPath.empty())
578 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000579 } while (true);
580
Richard Smith3d5b48c2015-10-16 21:42:56 +0000581 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000582 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000583 if (!HS.findUsableModuleForFrameworkHeader(
584 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
585 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000586 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000587 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
588 SuggestedModule, IsSystem))
589 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000590 }
591 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000592 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000593}
594
Douglas Gregor89929282012-01-30 06:01:29 +0000595void HeaderSearch::setTarget(const TargetInfo &Target) {
596 ModMap.setTarget(Target);
597}
598
Chris Lattner712e3872007-12-17 08:13:48 +0000599//===----------------------------------------------------------------------===//
600// Header File Location.
601//===----------------------------------------------------------------------===//
602
Reid Klecknera97d4c02014-02-18 23:49:24 +0000603/// \brief Return true with a diagnostic if the file that MSVC would have found
604/// fails to match the one that Clang would have found with MSVC header search
605/// disabled.
606static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
607 const FileEntry *MSFE, const FileEntry *FE,
608 SourceLocation IncludeLoc) {
609 if (MSFE && FE != MSFE) {
610 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
611 return true;
612 }
613 return false;
614}
Chris Lattner712e3872007-12-17 08:13:48 +0000615
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000616static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
617 assert(!Str.empty());
618 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
619 std::copy(Str.begin(), Str.end(), CopyStr);
620 CopyStr[Str.size()] = '\0';
621 return CopyStr;
622}
623
James Dennettc07ab2c2012-06-20 00:56:32 +0000624/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000625/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000626/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
627/// non-empty, indicates where the \#including file(s) are, in case a relative
628/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000629const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000630 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
631 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000632 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
633 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000634 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000635 bool *IsMapped, bool SkipCache, bool BuildSystemModule) {
636 if (IsMapped)
637 *IsMapped = false;
638
Douglas Gregor97eec242011-09-15 22:00:41 +0000639 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000640 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000641
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000642 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000643 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000644 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000645
646 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000647 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Craig Topperd2d442c2014-05-17 23:10:59 +0000649 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000650 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000651 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000652 RelativePath->clear();
653 RelativePath->append(Filename.begin(), Filename.end());
654 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000655 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000656 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000657 /*IsSystemHeaderDir*/false,
658 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000659 }
Mike Stump11289f42009-09-09 15:08:12 +0000660
Reid Klecknera97d4c02014-02-18 23:49:24 +0000661 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000662 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000663 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000664
Douglas Gregor9f93e382011-07-28 04:45:53 +0000665 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000666 // directory. This cannot be based on CurDir, because each includer could be
667 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
668 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000669 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000670 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000671 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000672 bool First = true;
673 for (const auto &IncluderAndDir : Includers) {
674 const FileEntry *Includer = IncluderAndDir.first;
675
Will Wilson0fafd342013-12-27 19:46:16 +0000676 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000677 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000678 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000679 TmpDir.push_back('/');
680 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000681
Richard Smith6f548ec2014-03-06 18:08:08 +0000682 // FIXME: We don't cache the result of getFileInfo across the call to
683 // getFileAndSuggestModule, because it's a reference to an element of
684 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000685 //
Manman Rene4a5d372016-05-17 02:15:12 +0000686 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000687 // from a module build. We should treat this as a system header if we're
688 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000689 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000690 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
691 BuildSystemModule;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000692 if (const FileEntry *FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000693 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000694 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000695 if (!Includer) {
696 assert(First && "only first includer can have no file");
697 return FE;
698 }
699
Will Wilson0fafd342013-12-27 19:46:16 +0000700 // Leave CurDir unset.
701 // This file is a system header or C++ unfriendly if the old file is.
702 //
703 // Note that we only use one of FromHFI/ToHFI at once, due to potential
704 // reallocation of the underlying vector potentially making the first
705 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000706 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000707 unsigned DirInfo = FromHFI.DirInfo;
708 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
709 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000710
Will Wilson0fafd342013-12-27 19:46:16 +0000711 HeaderFileInfo &ToHFI = getFileInfo(FE);
712 ToHFI.DirInfo = DirInfo;
713 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
714 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000715
Craig Topperd2d442c2014-05-17 23:10:59 +0000716 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000717 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000718 SearchPath->clear();
719 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
720 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000721 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000722 RelativePath->clear();
723 RelativePath->append(Filename.begin(), Filename.end());
724 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000725 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000726 return FE;
727
728 // Otherwise, we found the path via MSVC header search rules. If
729 // -Wmsvc-include is enabled, we have to keep searching to see if we
730 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000731 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000732 return FE;
733 } else {
734 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000735 if (SuggestedModule) {
736 MSSuggestedModule = *SuggestedModule;
737 *SuggestedModule = ModuleMap::KnownHeader();
738 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000739 break;
740 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000741 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000742 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000743 }
744 }
Mike Stump11289f42009-09-09 15:08:12 +0000745
Craig Topperd2d442c2014-05-17 23:10:59 +0000746 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000747
748 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000749 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000751 // If this is a #include_next request, start searching after the directory the
752 // file was found in.
753 if (FromDir)
754 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattnerd4275422007-07-22 07:28:00 +0000756 // Cache all of the lookups performed by this method. Many headers are
757 // multiply included, and the "pragma once" optimization prevents them from
758 // being relex/pp'd, but they would still have to search through a
759 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000760 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000761
762 // If the entry has been previously looked up, the first value will be
763 // non-zero. If the value is equal to i (the start point of our search), then
764 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000765 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000766 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000767 i = CacheLookup.HitIdx;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000768 if (CacheLookup.MappedName) {
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000769 Filename = CacheLookup.MappedName;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000770 if (IsMapped)
771 *IsMapped = true;
772 }
Chris Lattnerd4275422007-07-22 07:28:00 +0000773 } else {
774 // Otherwise, this is the first query, or the previous query didn't match
775 // our search start. We will fill in our found location below, so prime the
776 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000777 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000780 SmallString<64> MappedName;
781
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000782 // Check each directory in sequence to see if it contains this file.
783 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000784 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000785 bool HasBeenMapped = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000786 const FileEntry *FE = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000787 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000788 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
789 MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000790 if (HasBeenMapped) {
791 CacheLookup.MappedName =
792 copyString(Filename, LookupFileCache.getAllocator());
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000793 if (IsMapped)
794 *IsMapped = true;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000795 }
Chris Lattner712e3872007-12-17 08:13:48 +0000796 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattner712e3872007-12-17 08:13:48 +0000798 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattner712e3872007-12-17 08:13:48 +0000800 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000801 HeaderFileInfo &HFI = getFileInfo(FE);
802 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000803
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000804 // If the directory characteristic is User but this framework was
805 // user-specified to be treated as a system framework, promote the
806 // characteristic.
807 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
808 HFI.DirInfo = SrcMgr::C_System;
809
Richard Smith8acadcb2012-06-13 20:27:03 +0000810 // If the filename matches a known system header prefix, override
811 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000812 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
813 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
814 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000815 : SrcMgr::C_User;
816 break;
817 }
818 }
819
Douglas Gregor9f93e382011-07-28 04:45:53 +0000820 // If this file is found in a header map and uses the framework style of
821 // includes, then this header is part of a framework we're building.
822 if (CurDir->isIndexHeaderMap()) {
823 size_t SlashPos = Filename.find('/');
824 if (SlashPos != StringRef::npos) {
825 HFI.IndexHeaderMapHeader = 1;
826 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
827 SlashPos));
828 }
829 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000830
Richard Smith8c71eba2014-03-05 20:51:45 +0000831 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
832 if (SuggestedModule)
833 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000834 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000835 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000836
Chris Lattner712e3872007-12-17 08:13:48 +0000837 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000838 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000839 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000840 }
Mike Stump11289f42009-09-09 15:08:12 +0000841
Douglas Gregord8575e12011-07-30 06:28:34 +0000842 // If we are including a file with a quoted include "foo.h" from inside
843 // a header in a framework that is currently being built, and we couldn't
844 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
845 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000846 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000847 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000848 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000849 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000850 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000851 ScratchFilename += IncludingHFI.Framework;
852 ScratchFilename += '/';
853 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000854
Richard Smith3d5b48c2015-10-16 21:42:56 +0000855 const FileEntry *FE =
856 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
857 CurDir, Includers.front(), SearchPath, RelativePath,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000858 RequestingModule, SuggestedModule, IsMapped);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000859
Richard Smith8c71eba2014-03-05 20:51:45 +0000860 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
861 if (SuggestedModule)
862 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000863 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000864 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000865
David Blaikie3c8c46e2014-11-19 05:48:40 +0000866 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000867 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000868 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000869 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000870 }
871 }
872
Craig Topperd2d442c2014-05-17 23:10:59 +0000873 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000874 if (SuggestedModule)
875 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000876 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000877 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000878
Chris Lattnerd4275422007-07-22 07:28:00 +0000879 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000880 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000881 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000882}
883
Chris Lattner63dd32b2006-10-20 04:42:40 +0000884/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000885/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000886/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
887/// is a subframework within Carbon.framework. If so, return the FileEntry
888/// for the designated file, otherwise return null.
889const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000890LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000891 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000892 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000893 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000894 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000895 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000896 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000897
Chris Lattner63dd32b2006-10-20 04:42:40 +0000898 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000899 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000900 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000901 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattner63dd32b2006-10-20 04:42:40 +0000903 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +0000904 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattner63dd32b2006-10-20 04:42:40 +0000906 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000907 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +0000908 auto FrameworkPos = ContextName.find(".framework");
909 if (FrameworkPos == StringRef::npos ||
910 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
911 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000912 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000913
Mehdi Amini004b9c72016-10-10 22:52:47 +0000914 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
915 FrameworkPos +
916 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000917
Chris Lattner63dd32b2006-10-20 04:42:40 +0000918 // Append Frameworks/HIToolbox.framework/
919 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000920 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000921 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000922
David Blaikie13156b62014-11-19 03:06:06 +0000923 auto &CacheLookup =
924 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
925 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000926
Chris Lattner5ed76da2006-10-22 07:24:13 +0000927 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000928 if (CacheLookup.second.Directory &&
929 CacheLookup.first().size() == FrameworkName.size() &&
930 memcmp(CacheLookup.first().data(), &FrameworkName[0],
931 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000932 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000933
Chris Lattner5ed76da2006-10-22 07:24:13 +0000934 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000935 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000936 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner5ed76da2006-10-22 07:24:13 +0000938 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000939 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000940 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner5ed76da2006-10-22 07:24:13 +0000942 // Otherwise, if it does, remember that this is the right direntry for this
943 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000944 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Craig Topperd2d442c2014-05-17 23:10:59 +0000947 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000948
Craig Topperd2d442c2014-05-17 23:10:59 +0000949 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000950 RelativePath->clear();
951 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
952 }
953
Chris Lattner63dd32b2006-10-20 04:42:40 +0000954 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000955 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000956 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000957 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000958 SearchPath->clear();
959 // Without trailing '/'.
960 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
961 }
962
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000963 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000964 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Chris Lattner63dd32b2006-10-20 04:42:40 +0000965 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000966 HeadersFilename = FrameworkName;
967 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000968 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000969 SearchPath->clear();
970 // Without trailing '/'.
971 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
972 }
973
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000974 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000975 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000976 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000977 }
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattner577377e2006-10-20 04:55:45 +0000979 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000980 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000981 // Note that the temporary 'DirInfo' is required here, as either call to
982 // getFileInfo could resize the vector and we don't want to rely on order
983 // of evaluation.
984 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
985 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000986
Richard Smith3d5b48c2015-10-16 21:42:56 +0000987 FrameworkName.pop_back(); // remove the trailing '/'
988 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
989 SuggestedModule, /*IsSystem*/ false))
990 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000991
Chris Lattner577377e2006-10-20 04:55:45 +0000992 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000993}
994
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000995//===----------------------------------------------------------------------===//
996// File Info Management.
997//===----------------------------------------------------------------------===//
998
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000999/// \brief Merge the header file info provided by \p OtherHFI into the current
1000/// header file info (\p HFI)
1001static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1002 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +00001003 assert(OtherHFI.External && "expected to merge external HFI");
1004
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001005 HFI.isImport |= OtherHFI.isImport;
1006 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001007 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001008 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +00001009
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001010 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1011 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1012 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1013 }
Richard Smithd8879c82015-08-24 21:59:32 +00001014
1015 HFI.DirInfo = OtherHFI.DirInfo;
1016 HFI.External = (!HFI.IsValid || HFI.External);
1017 HFI.IsValid = true;
1018 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001019
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001020 if (HFI.Framework.empty())
1021 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001022}
1023
Steve Naroff3fa455a2009-04-24 20:03:17 +00001024/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001025/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001026HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001027 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +00001028 FileInfo.resize(FE->getUID() + 1);
1029
Richard Smithd8879c82015-08-24 21:59:32 +00001030 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +00001031 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001032 if (ExternalSource && !HFI->Resolved) {
1033 HFI->Resolved = true;
1034 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1035
1036 HFI = &FileInfo[FE->getUID()];
1037 if (ExternalHFI.External)
1038 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +00001039 }
1040
Richard Smithd8879c82015-08-24 21:59:32 +00001041 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +00001042 // We have local information about this header file, so it's no longer
1043 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001044 HFI->External = false;
1045 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001046}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001047
Richard Smith386bb072015-08-18 23:42:23 +00001048const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001049HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1050 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001051 // If we have an external source, ensure we have the latest information.
1052 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001053 HeaderFileInfo *HFI;
1054 if (ExternalSource) {
1055 if (FE->getUID() >= FileInfo.size()) {
1056 if (!WantExternal)
1057 return nullptr;
1058 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001059 }
Richard Smithd8879c82015-08-24 21:59:32 +00001060
1061 HFI = &FileInfo[FE->getUID()];
1062 if (!WantExternal && (!HFI->IsValid || HFI->External))
1063 return nullptr;
1064 if (!HFI->Resolved) {
1065 HFI->Resolved = true;
1066 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1067
1068 HFI = &FileInfo[FE->getUID()];
1069 if (ExternalHFI.External)
1070 mergeHeaderFileInfo(*HFI, ExternalHFI);
1071 }
1072 } else if (FE->getUID() >= FileInfo.size()) {
1073 return nullptr;
1074 } else {
1075 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001076 }
Richard Smith386bb072015-08-18 23:42:23 +00001077
Richard Smithd8879c82015-08-24 21:59:32 +00001078 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001079 return nullptr;
1080
Richard Smithd8879c82015-08-24 21:59:32 +00001081 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001082}
1083
Douglas Gregor37aa4932011-05-04 00:14:37 +00001084bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1085 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001086 if (auto *HFI = getExistingFileInfo(File))
1087 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1088 HFI->ControllingMacroID;
1089 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001090}
1091
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001092void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001093 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001094 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001095 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1096
1097 // Don't mark the file info as non-external if there's nothing to change.
1098 if (!isCompilingModuleHeader) {
1099 if (!isModularHeader)
1100 return;
1101 auto *HFI = getExistingFileInfo(FE);
1102 if (HFI && HFI->isModuleHeader)
1103 return;
1104 }
1105
Richard Smith386bb072015-08-18 23:42:23 +00001106 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001107 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001108 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001109}
1110
Richard Smith20e883e2015-04-29 23:20:19 +00001111bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001112 const FileEntry *File, bool isImport,
1113 bool ModulesEnabled, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001114 ++NumIncluded; // Count # of attempted #includes.
1115
1116 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001117 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001119 // FIXME: this is a workaround for the lack of proper modules-aware support
1120 // for #import / #pragma once
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001121 auto TryEnterImported = [&]() -> bool {
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001122 if (!ModulesEnabled)
1123 return false;
Richard Smith040e1262017-06-02 01:55:39 +00001124 // Ensure FileInfo bits are up to date.
1125 ModMap.resolveHeaderDirectives(File);
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001126 // Modules with builtins are special; multiple modules use builtins as
1127 // modular headers, example:
1128 //
1129 // module stddef { header "stddef.h" export * }
1130 //
1131 // After module map parsing, this expands to:
1132 //
1133 // module stddef {
1134 // header "/path_to_builtin_dirs/stddef.h"
1135 // textual "stddef.h"
1136 // }
1137 //
1138 // It's common that libc++ and system modules will both define such
1139 // submodules. Make sure cached results for a builtin header won't
1140 // prevent other builtin modules to potentially enter the builtin header.
1141 // Note that builtins are header guarded and the decision to actually
1142 // enter them is postponed to the controlling macros logic below.
1143 bool TryEnterHdr = false;
1144 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1145 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1146 ModuleMap::isBuiltinHeader(
1147 llvm::sys::path::filename(File->getName()));
1148
1149 // Textual headers can be #imported from different modules. Since ObjC
1150 // headers find in the wild might rely only on #import and do not contain
1151 // controlling macros, be conservative and only try to enter textual headers
1152 // if such macro is present.
Bruno Cardoso Lopes4164dd92017-08-12 01:38:26 +00001153 if (!FileInfo.isModuleHeader &&
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001154 FileInfo.getControllingMacro(ExternalLookup))
1155 TryEnterHdr = true;
1156 return TryEnterHdr;
1157 };
1158
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001159 // If this is a #import directive, check that we have not already imported
1160 // this header.
1161 if (isImport) {
1162 // If this has already been imported, don't import it again.
1163 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001164
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001165 // Has this already been #import'ed or #include'd?
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001166 if (FileInfo.NumIncludes && !TryEnterImported())
1167 return false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001168 } else {
1169 // Otherwise, if this is a #include of a file that was previously #import'd
1170 // or if this is the second #include of a #pragma once file, ignore it.
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001171 if (FileInfo.isImport && !TryEnterImported())
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001172 return false;
1173 }
Mike Stump11289f42009-09-09 15:08:12 +00001174
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001175 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1176 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001177 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001178 = FileInfo.getControllingMacro(ExternalLookup)) {
1179 // If the header corresponds to a module, check whether the macro is already
1180 // defined in that module rather than checking in the current set of visible
1181 // modules.
1182 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1183 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001184 ++NumMultiIncludeFileOptzn;
1185 return false;
1186 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001187 }
Mike Stump11289f42009-09-09 15:08:12 +00001188
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001189 // Increment the number of times this file has been included.
1190 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001191
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001192 return true;
1193}
1194
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001195size_t HeaderSearch::getTotalMemory() const {
1196 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001197 + llvm::capacity_in_bytes(FileInfo)
1198 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001199 + LookupFileCache.getAllocator().getTotalMemory()
1200 + FrameworkMap.getAllocator().getTotalMemory();
1201}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001202
1203StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001204 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001205}
Douglas Gregor718292f2011-11-11 19:10:28 +00001206
1207bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001208 const DirectoryEntry *Root,
1209 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001210 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001211 return false;
1212
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001213 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001214
1215 StringRef DirName = FileName;
1216 do {
1217 // Get the parent directory name.
1218 DirName = llvm::sys::path::parent_path(DirName);
1219 if (DirName.empty())
1220 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001221
Douglas Gregor718292f2011-11-11 19:10:28 +00001222 // Determine whether this directory exists.
1223 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1224 if (!Dir)
1225 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001226
Ben Langmuir984e1df2014-03-19 20:23:34 +00001227 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001228 switch (loadModuleMapFile(Dir, IsSystem,
1229 llvm::sys::path::extension(Dir->getName()) ==
1230 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001231 case LMM_NewlyLoaded:
1232 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001233 // Success. All of the directories we stepped through inherit this module
1234 // map file.
1235 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1236 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1237 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001238
1239 case LMM_NoDirectory:
1240 case LMM_InvalidModuleMap:
1241 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001242 }
1243
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001244 // If we hit the top of our search, we're done.
1245 if (Dir == Root)
1246 return false;
1247
Douglas Gregor718292f2011-11-11 19:10:28 +00001248 // Keep track of all of the directories we checked, so we can mark them as
1249 // having module maps if we eventually do find a module map.
1250 FixUpDirectories.push_back(Dir);
1251 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001252}
1253
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001254ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001255HeaderSearch::findModuleForHeader(const FileEntry *File,
1256 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001257 if (ExternalSource) {
1258 // Make sure the external source has handled header info about this file,
1259 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001260 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001261 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001262 return ModMap.findModuleForHeader(File, AllowTextual);
1263}
1264
1265static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1266 Module *RequestingModule,
1267 ModuleMap::KnownHeader *SuggestedModule) {
1268 ModuleMap::KnownHeader Module =
1269 HS.findModuleForHeader(File, /*AllowTextual*/true);
1270 if (SuggestedModule)
1271 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1272 ? ModuleMap::KnownHeader()
1273 : Module;
1274
1275 // If this module specifies [no_undeclared_includes], we cannot find any
1276 // file that's in a non-dependency module.
1277 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1278 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1279 if (!RequestingModule->directlyUses(Module.getModule())) {
1280 return false;
1281 }
1282 }
1283
1284 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001285}
1286
Richard Smith3d5b48c2015-10-16 21:42:56 +00001287bool HeaderSearch::findUsableModuleForHeader(
1288 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1289 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001290 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001291 // If there is a module that corresponds to this header, suggest it.
1292 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001293 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001294 }
1295 return true;
1296}
1297
1298bool HeaderSearch::findUsableModuleForFrameworkHeader(
1299 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1300 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1301 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001302 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001303 // Find the top-level framework based on this framework.
1304 SmallVector<std::string, 4> SubmodulePath;
1305 const DirectoryEntry *TopFrameworkDir
1306 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1307
1308 // Determine the name of the top-level framework.
1309 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1310
1311 // Load this framework module. If that succeeds, find the suggested module
1312 // for this header, if any.
1313 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1314
1315 // FIXME: This can find a module not part of ModuleName, which is
1316 // important so that we're consistent about whether this header
1317 // corresponds to a module. Possibly we should lock down framework modules
1318 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001319 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001320 }
1321 return true;
1322}
1323
Richard Smith9acb99e32014-12-10 03:09:48 +00001324static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001325 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001326 StringRef Filename = llvm::sys::path::filename(File->getName());
1327 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001328 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001329 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001330 else if (Filename == "module.modulemap")
1331 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1332 else
1333 return nullptr;
1334 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001335}
1336
Richard Smith8128f332017-05-05 22:18:51 +00001337bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +00001338 FileID ID, unsigned *Offset,
1339 StringRef OriginalModuleMapFile) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001340 // Find the directory for the module. For frameworks, that may require going
1341 // up from the 'Modules' directory.
1342 const DirectoryEntry *Dir = nullptr;
1343 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1344 Dir = FileMgr.getDirectory(".");
1345 else {
Richard Smith8b706102017-05-31 20:56:55 +00001346 if (!OriginalModuleMapFile.empty()) {
1347 // We're building a preprocessed module map. Find or invent the directory
1348 // that it originally occupied.
1349 Dir = FileMgr.getDirectory(
1350 llvm::sys::path::parent_path(OriginalModuleMapFile));
1351 if (!Dir) {
1352 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1353 Dir = FakeFile->getDir();
1354 }
1355 } else {
1356 Dir = File->getDir();
1357 }
1358
Richard Smith9acb99e32014-12-10 03:09:48 +00001359 StringRef DirName(Dir->getName());
1360 if (llvm::sys::path::filename(DirName) == "Modules") {
1361 DirName = llvm::sys::path::parent_path(DirName);
1362 if (DirName.endswith(".framework"))
1363 Dir = FileMgr.getDirectory(DirName);
1364 // FIXME: This assert can fail if there's a race between the above check
1365 // and the removal of the directory.
1366 assert(Dir && "parent must exist");
1367 }
1368 }
1369
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001370 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001371 case LMM_AlreadyLoaded:
1372 case LMM_NewlyLoaded:
1373 return false;
1374 case LMM_NoDirectory:
1375 case LMM_InvalidModuleMap:
1376 return true;
1377 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001378 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001379}
1380
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001381HeaderSearch::LoadModuleMapResult
1382HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1383 const DirectoryEntry *Dir, FileID ID,
1384 unsigned *Offset) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001385 assert(File && "expected FileEntry");
1386
Richard Smith9887d792014-10-17 01:42:53 +00001387 // Check whether we've already loaded this module map, and mark it as being
1388 // loaded in case we recursively try to load it from itself.
1389 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1390 if (!AddResult.second)
1391 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001392
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001393 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
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 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001399 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001400 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001401 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001402 return LMM_InvalidModuleMap;
1403 }
1404 }
1405
1406 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001407 return LMM_NewlyLoaded;
1408}
1409
1410const FileEntry *
1411HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001412 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001413 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001414 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1415 // module.map at the framework root is also accepted.
1416 SmallString<128> ModuleMapFileName(Dir->getName());
1417 if (IsFramework)
1418 llvm::sys::path::append(ModuleMapFileName, "Modules");
1419 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1420 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1421 return F;
1422
1423 // Continue to allow module.map
1424 ModuleMapFileName = Dir->getName();
1425 llvm::sys::path::append(ModuleMapFileName, "module.map");
1426 return FileMgr.getFile(ModuleMapFileName);
1427}
1428
1429Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001430 const DirectoryEntry *Dir,
1431 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001432 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001433 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001434
Douglas Gregor56c64012011-11-17 01:41:17 +00001435 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001436 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001437 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001438 // Try to infer a module map from the framework directory.
1439 if (HSOpts->ImplicitModuleMaps)
1440 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001441 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001442
Douglas Gregor56c64012011-11-17 01:41:17 +00001443 case LMM_AlreadyLoaded:
1444 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001445 return nullptr;
1446
Douglas Gregor56c64012011-11-17 01:41:17 +00001447 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001448 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001449 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001450
Ben Langmuira5254002015-07-02 13:19:48 +00001451 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001452}
1453
Douglas Gregor80b69042011-11-12 00:22:19 +00001454HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001455HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1456 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001457 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001458 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001459
Douglas Gregor80b69042011-11-12 00:22:19 +00001460 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001461}
1462
Douglas Gregor80b69042011-11-12 00:22:19 +00001463HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001464HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1465 bool IsFramework) {
1466 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001467 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001468 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001469
Ben Langmuir984e1df2014-03-19 20:23:34 +00001470 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001471 LoadModuleMapResult Result =
1472 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001473 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1474 // E.g. Foo.framework/Modules/module.modulemap
1475 // ^Dir ^ModuleMapFile
1476 if (Result == LMM_NewlyLoaded)
1477 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001478 else if (Result == LMM_InvalidModuleMap)
1479 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001480 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001481 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001482 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001483}
Douglas Gregor718292f2011-11-11 19:10:28 +00001484
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001485void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001486 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001487
Richard Smith47972af2015-06-16 00:08:24 +00001488 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001489 // Load module maps for each of the header search directories.
1490 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1491 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1492 if (SearchDirs[Idx].isFramework()) {
1493 std::error_code EC;
1494 SmallString<128> DirNative;
1495 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1496 DirNative);
1497
1498 // Search each of the ".framework" directories to load them as modules.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001499 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1500 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001501 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001502 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001503 continue;
1504
1505 const DirectoryEntry *FrameworkDir =
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001506 FileMgr.getDirectory(Dir->getName());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001507 if (!FrameworkDir)
1508 continue;
1509
1510 // Load this framework module.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001511 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1512 FrameworkDir, IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001513 }
1514 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001515 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001516
1517 // FIXME: Deal with header maps.
1518 if (SearchDirs[Idx].isHeaderMap())
1519 continue;
1520
1521 // Try to load a module map file for the search directory.
1522 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1523 /*IsFramework*/ false);
1524
1525 // Try to load module map files for immediate subdirectories of this
1526 // search directory.
1527 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001528 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001529 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001530
Douglas Gregor07f43572012-01-29 18:15:03 +00001531 // Populate the list of modules.
1532 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1533 MEnd = ModMap.module_end();
1534 M != MEnd; ++M) {
1535 Modules.push_back(M->getValue());
1536 }
1537}
Douglas Gregor0339a642013-03-21 01:08:50 +00001538
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001539void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001540 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001541 return;
1542
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001543 // Load module maps for each of the header search directories.
1544 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001545 // We only care about normal header directories.
1546 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001547 continue;
1548 }
1549
1550 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001551 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001552 SearchDirs[Idx].isSystemHeaderDirectory(),
1553 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001554 }
1555}
1556
Douglas Gregor0339a642013-03-21 01:08:50 +00001557void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001558 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001559 "Should not be loading subdirectory module maps");
1560
Douglas Gregor0339a642013-03-21 01:08:50 +00001561 if (SearchDir.haveSearchedAllModuleMaps())
1562 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001563
1564 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001565 SmallString<128> DirNative;
1566 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001567 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1568 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001569 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001570 bool IsFramework =
1571 llvm::sys::path::extension(Dir->getName()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001572 if (IsFramework == SearchDir.isFramework())
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001573 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001574 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001575 }
1576
1577 SearchDir.setSearchedAllModuleMaps(true);
1578}
Richard Smith4eb83932016-04-27 21:57:05 +00001579
1580std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1581 bool *IsSystem) {
1582 // FIXME: We assume that the path name currently cached in the FileEntry is
Eric Liudffb1a82018-01-29 13:21:23 +00001583 // the most appropriate one for this analysis (and that it's spelled the
1584 // same way as the corresponding header search path).
1585 return suggestPathToFileForDiagnostics(File->getName(), /*BuildDir=*/"",
1586 IsSystem);
1587}
1588
1589std::string HeaderSearch::suggestPathToFileForDiagnostics(
1590 llvm::StringRef File, llvm::StringRef WorkingDir, bool *IsSystem) {
1591 using namespace llvm::sys;
Richard Smith4eb83932016-04-27 21:57:05 +00001592
1593 unsigned BestPrefixLength = 0;
1594 unsigned BestSearchDir;
1595
1596 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1597 // FIXME: Support this search within frameworks and header maps.
1598 if (!SearchDirs[I].isNormalDir())
1599 continue;
1600
Mehdi Amini0df59d82016-10-11 07:31:29 +00001601 StringRef Dir = SearchDirs[I].getDir()->getName();
Eric Liudffb1a82018-01-29 13:21:23 +00001602 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
1603 if (!WorkingDir.empty() && !path::is_absolute(Dir)) {
1604 auto err = fs::make_absolute(WorkingDir, DirPath);
1605 if (!err)
1606 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1607 Dir = DirPath;
1608 }
1609 for (auto NI = path::begin(File), NE = path::end(File),
1610 DI = path::begin(Dir), DE = path::end(Dir);
Richard Smith4eb83932016-04-27 21:57:05 +00001611 /*termination condition in loop*/; ++NI, ++DI) {
Eric Liudffb1a82018-01-29 13:21:23 +00001612 // '.' components in File are ignored.
Richard Smith4eb83932016-04-27 21:57:05 +00001613 while (NI != NE && *NI == ".")
1614 ++NI;
1615 if (NI == NE)
1616 break;
1617
1618 // '.' components in Dir are ignored.
1619 while (DI != DE && *DI == ".")
1620 ++DI;
1621 if (DI == DE) {
Eric Liudffb1a82018-01-29 13:21:23 +00001622 // Dir is a prefix of File, up to '.' components and choice of path
Richard Smith4eb83932016-04-27 21:57:05 +00001623 // separators.
Eric Liudffb1a82018-01-29 13:21:23 +00001624 unsigned PrefixLength = NI - path::begin(File);
Richard Smith4eb83932016-04-27 21:57:05 +00001625 if (PrefixLength > BestPrefixLength) {
1626 BestPrefixLength = PrefixLength;
1627 BestSearchDir = I;
1628 }
1629 break;
1630 }
1631
1632 if (*NI != *DI)
1633 break;
1634 }
1635 }
1636
1637 if (IsSystem)
1638 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
Eric Liudffb1a82018-01-29 13:21:23 +00001639 return File.drop_front(BestPrefixLength);
Richard Smith4eb83932016-04-27 21:57:05 +00001640}