blob: ddbb4d4b429d9fbe5c7877a059dcd53a3696a280 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner59a9ebd2006-10-18 05:34:33 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the DirectoryLookup and HeaderSearch interfaces.
10//
11//===----------------------------------------------------------------------===//
12
Chris Lattner59a9ebd2006-10-18 05:34:33 +000013#include "clang/Lex/HeaderSearch.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000014#include "clang/Basic/Diagnostic.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000017#include "clang/Basic/Module.h"
18#include "clang/Basic/SourceManager.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000019#include "clang/Lex/DirectoryLookup.h"
Richard Smith2aedca32015-07-01 02:29:35 +000020#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderMap.h"
22#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000023#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000024#include "clang/Lex/ModuleMap.h"
Richard Smith20e883e2015-04-29 23:20:19 +000025#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000026#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000028#include "llvm/ADT/SmallString.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000029#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/Support/Allocator.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000032#include "llvm/Support/Capacity.h"
Alexey Bataev4a0328c2019-08-13 19:32:36 +000033#include "llvm/Support/Errc.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000034#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/Support/FileSystem.h"
36#include "llvm/Support/Path.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000037#include "llvm/Support/VirtualFileSystem.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 Lattner59a9ebd2006-10-18 05:34:33 +000078void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000079 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
80 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000081 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
82 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
83 NumOnceOnlyFiles += FileInfo[i].isImport;
84 if (MaxNumIncludes < FileInfo[i].NumIncludes)
85 MaxNumIncludes = FileInfo[i].NumIncludes;
86 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
87 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000088 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
89 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
90 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner23b7eb62007-06-15 23:05:46 +000092 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
93 fprintf(stderr, " %d #includes skipped due to"
94 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000095
Chris Lattner23b7eb62007-06-15 23:05:46 +000096 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
97 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000098}
99
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000100/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000101/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000102const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000103 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000104 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000105 if (!HeaderMaps.empty()) {
106 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000107 // Pointer equality comparison of FileEntries works because they are
108 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000109 if (HeaderMaps[i].first == FE)
Fangrui Song48769772018-08-20 19:15:02 +0000110 return HeaderMaps[i].second.get();
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Fangrui Song48769772018-08-20 19:15:02 +0000113 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
114 HeaderMaps.emplace_back(FE, std::move(HM));
115 return HeaderMaps.back().second.get();
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000116 }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Craig Topperd2d442c2014-05-17 23:10:59 +0000118 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000119}
120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000121/// Get filenames for all registered header maps.
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000122void HeaderSearch::getHeaderMapFileNames(
123 SmallVectorImpl<std::string> &Names) const {
124 for (auto &HM : HeaderMaps)
125 Names.push_back(HM.first->getName());
126}
127
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000128std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000129 const FileEntry *ModuleMap =
130 getModuleMap().getModuleMapFileForUniquing(Module);
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000131 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000132}
133
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000134std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
135 bool FileMapOnly) {
136 // First check the module name to pcm file map.
137 auto i (HSOpts->PrebuiltModuleFiles.find(ModuleName));
138 if (i != HSOpts->PrebuiltModuleFiles.end())
139 return i->second;
140
141 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000142 return {};
Manman Ren11f2a472016-08-18 17:42:15 +0000143
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000144 // Then go through each prebuilt module directory and try to find the pcm
145 // file.
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000146 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
147 SmallString<256> Result(Dir);
148 llvm::sys::fs::make_absolute(Result);
149 llvm::sys::path::append(Result, ModuleName + ".pcm");
150 if (getFileMgr().getFile(Result.str()))
151 return Result.str().str();
Manman Ren11f2a472016-08-18 17:42:15 +0000152 }
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000153 return {};
154}
Manman Ren11f2a472016-08-18 17:42:15 +0000155
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000156std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
157 StringRef ModuleMapPath) {
Richard Smithd520a252015-07-21 18:07:47 +0000158 // If we don't have a module cache path or aren't supposed to use one, we
159 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000160 if (getModuleCachePath().empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000161 return {};
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000162
Richard Smith3938f0c2015-08-15 00:34:15 +0000163 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000164 llvm::sys::fs::make_absolute(Result);
165
166 if (HSOpts->DisableModuleHash) {
167 llvm::sys::path::append(Result, ModuleName + ".pcm");
168 } else {
169 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000170 // ideally be globally unique to this particular module. Name collisions
171 // in the hash are safe (because any translation unit can only import one
172 // module with each name), but result in a loss of caching.
173 //
174 // To avoid false-negatives, we form as canonical a path as we can, and map
175 // to lower-case in case we're on a case-insensitive file system.
Richard Smith3f57cff2017-03-09 00:58:22 +0000176 std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
177 if (Parent.empty())
178 Parent = ".";
Harlan Haskins8d323d12019-08-01 21:31:56 +0000179 auto Dir = FileMgr.getDirectory(Parent);
Richard Smith54cc3c22014-12-11 20:50:24 +0000180 if (!Dir)
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000181 return {};
Harlan Haskins8d323d12019-08-01 21:31:56 +0000182 auto DirName = FileMgr.getCanonicalName(*Dir);
Richard Smith54cc3c22014-12-11 20:50:24 +0000183 auto FileName = llvm::sys::path::filename(ModuleMapPath);
184
185 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000186 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000187
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000188 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000189 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000190 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000191 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000192 return Result.str().str();
193}
194
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000195Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch,
196 bool AllowExtraModuleMapSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000197 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000198 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000199 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000200 return Module;
Graydon Hoare4d867642016-12-21 00:24:39 +0000201
202 StringRef SearchName = ModuleName;
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000203 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000204
205 // The facility for "private modules" -- adjacent, optional module maps named
206 // module.private.modulemap that are supposed to define private submodules --
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000207 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
208 //
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000209 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000210 // should also rename to Foo_Private. Representing private as submodules
211 // could force building unwanted dependencies into the parent module and cause
212 // dependency cycles.
213 if (!Module && SearchName.consume_back("_Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000214 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000215 if (!Module && SearchName.consume_back("Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000216 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000217 return Module;
218}
219
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000220Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
221 bool AllowExtraModuleMapSearch) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000222 Module *Module = nullptr;
223
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000224 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000225 // maps, searching for a module map that describes this module.
226 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
227 if (SearchDirs[Idx].isFramework()) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000228 // Search for or infer a module map for a framework. Here we use
229 // SearchName rather than ModuleName, to permit finding private modules
230 // named FooPrivate in buggy frameworks named Foo.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000231 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000232 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
Graydon Hoare4d867642016-12-21 00:24:39 +0000233 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
Harlan Haskins8d323d12019-08-01 21:31:56 +0000234 if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000235 bool IsSystem
236 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
Harlan Haskins8d323d12019-08-01 21:31:56 +0000237 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000238 if (Module)
239 break;
240 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000241 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000242
Douglas Gregor279a6c32012-01-29 17:08:11 +0000243 // FIXME: Figure out how header maps and module maps will work together.
Fangrui Song6907ce22018-07-30 19:24:48 +0000244
Douglas Gregor279a6c32012-01-29 17:08:11 +0000245 // Only deal with normal search directories.
246 if (!SearchDirs[Idx].isNormalDir())
247 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000248
249 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000250 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000251 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
252 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000253 // We just loaded a module map file; check whether the module is
254 // available now.
255 Module = ModMap.findModule(ModuleName);
256 if (Module)
257 break;
258 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000259
Douglas Gregor279a6c32012-01-29 17:08:11 +0000260 // Search for a module map in a subdirectory with the same name as the
261 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000262 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000263 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
264 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000265 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
266 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000267 // If we just loaded a module map file, look for the module again.
268 Module = ModMap.findModule(ModuleName);
269 if (Module)
270 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000271 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000272
273 // If we've already performed the exhaustive search for module maps in this
274 // search directory, don't do it again.
275 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
276 continue;
277
278 // Load all module maps in the immediate subdirectories of this search
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000279 // directory if ModuleName was from @import.
280 if (AllowExtraModuleMapSearch)
281 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor0339a642013-03-21 01:08:50 +0000282
283 // Look again for the module.
284 Module = ModMap.findModule(ModuleName);
285 if (Module)
286 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000287 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000288
Douglas Gregor279a6c32012-01-29 17:08:11 +0000289 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000290}
291
Chris Lattnerf62f7582007-12-17 07:52:39 +0000292//===----------------------------------------------------------------------===//
293// File lookup within a DirectoryLookup scope
294//===----------------------------------------------------------------------===//
295
Chris Lattner8d720d02007-12-17 17:57:27 +0000296/// getName - Return the directory or filename corresponding to this lookup
297/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000298StringRef DirectoryLookup::getName() const {
Alex Lorenz0377ca62019-08-31 01:26:04 +0000299 // FIXME: Use the name from \c DirectoryEntryRef.
Chris Lattner8d720d02007-12-17 17:57:27 +0000300 if (isNormalDir())
301 return getDir()->getName();
302 if (isFramework())
303 return getFrameworkDir()->getName();
304 assert(isHeaderMap() && "Unknown DirectoryLookup");
305 return getHeaderMap()->getFileName();
306}
307
Alex Lorenz4dc55732019-08-22 18:15:50 +0000308Optional<FileEntryRef> HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000309 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
310 bool IsSystemHeaderDir, Module *RequestingModule,
311 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000312 // If we have a module map that might map this header, load it and
313 // check whether we'll have a suggestion for a module.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000314 auto File = getFileMgr().getFileRef(FileName, /*OpenFile=*/true);
Nico Weberbabdfde2019-08-08 17:58:32 +0000315 if (!File) {
316 // For rare, surprising errors (e.g. "out of file handles"), diag the EC
317 // message.
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000318 std::error_code EC = llvm::errorToErrorCode(File.takeError());
Alexey Bataev4a0328c2019-08-13 19:32:36 +0000319 if (EC != llvm::errc::no_such_file_or_directory &&
320 EC != llvm::errc::invalid_argument &&
321 EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
Reid Kleckner1d63b022019-08-08 21:35:03 +0000322 Diags.Report(IncludeLoc, diag::err_cannot_open_file)
323 << FileName << EC.message();
Nico Weberbabdfde2019-08-08 17:58:32 +0000324 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000325 return None;
Nico Weberbabdfde2019-08-08 17:58:32 +0000326 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000327
Richard Smith3d5b48c2015-10-16 21:42:56 +0000328 // If there is a module that corresponds to this header, suggest it.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000329 if (!findUsableModuleForHeader(
330 &File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(),
331 RequestingModule, SuggestedModule, IsSystemHeaderDir))
332 return None;
Richard Smith8c71eba2014-03-05 20:51:45 +0000333
Harlan Haskins8d323d12019-08-01 21:31:56 +0000334 return *File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000335}
Chris Lattner8d720d02007-12-17 17:57:27 +0000336
Chris Lattnerf62f7582007-12-17 07:52:39 +0000337/// LookupFile - Lookup the specified file in this search path, returning it
338/// if it exists or returning null if not.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000339Optional<FileEntryRef> DirectoryLookup::LookupFile(
340 StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
341 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
342 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
343 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
344 bool &HasBeenMapped, SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000345 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000346 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000347
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000348 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000349 if (isNormalDir()) {
350 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000351 TmpDir = getDir()->getName();
352 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000353 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000354 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000355 SearchPath->clear();
356 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
357 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000358 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000359 RelativePath->clear();
360 RelativePath->append(Filename.begin(), Filename.end());
361 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000362
Taewook Ohf42103c2016-06-13 20:40:21 +0000363 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000364 isSystemHeaderDirectory(),
365 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000366 }
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattner712e3872007-12-17 08:13:48 +0000368 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000369 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000370 RequestingModule, SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000371 InUserSpecifiedSystemFramework, IsFrameworkFound);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Chris Lattner44bd21b2007-12-17 08:17:39 +0000373 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000374 const HeaderMap *HM = getHeaderMap();
375 SmallString<1024> Path;
376 StringRef Dest = HM->lookupFilename(Filename, Path);
377 if (Dest.empty())
Alex Lorenz4dc55732019-08-22 18:15:50 +0000378 return None;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000379
Alex Lorenz4dc55732019-08-22 18:15:50 +0000380 auto FixupSearchPath = [&]() {
Craig Topperd2d442c2014-05-17 23:10:59 +0000381 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000382 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000383 SearchPath->clear();
384 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
385 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000386 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000387 RelativePath->clear();
388 RelativePath->append(Filename.begin(), Filename.end());
389 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000390 };
391
392 // Check if the headermap maps the filename to a framework include
393 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
394 // framework include.
395 if (llvm::sys::path::is_relative(Dest)) {
396 MappedName.clear();
397 MappedName.append(Dest.begin(), Dest.end());
398 Filename = StringRef(MappedName.begin(), MappedName.size());
399 HasBeenMapped = true;
400 Optional<FileEntryRef> Result = HM->LookupFile(Filename, HS.getFileMgr());
401 if (Result) {
402 FixupSearchPath();
403 return *Result;
404 }
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000405 } else if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest)) {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000406 FixupSearchPath();
407 return *Res;
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000408 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000409
410 return None;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000411}
412
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000413/// Given a framework directory, find the top-most framework directory.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000414///
415/// \param FileMgr The file manager to use for directory lookups.
416/// \param DirName The name of the framework directory.
417/// \param SubmodulePath Will be populated with the submodule path from the
418/// returned top-level module to the originally named framework.
419static const DirectoryEntry *
420getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
421 SmallVectorImpl<std::string> &SubmodulePath) {
422 assert(llvm::sys::path::extension(DirName) == ".framework" &&
423 "Not a framework directory");
424
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000425 // Note: as an egregious but useful hack we use the real path here, because
426 // frameworks moving between top-level frameworks to embedded frameworks tend
427 // to be symlinked, and we base the logical structure of modules on the
428 // physical layout. In particular, we need to deal with crazy includes like
429 //
430 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
431 //
432 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
433 // which one should access with, e.g.,
434 //
435 // #include <Bar/Wibble.h>
436 //
437 // Similar issues occur when a top-level framework has moved into an
438 // embedded framework.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000439 const DirectoryEntry *TopFrameworkDir = nullptr;
440 if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName))
441 TopFrameworkDir = *TopFrameworkDirOrErr;
442
443 if (TopFrameworkDir)
444 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000445 do {
446 // Get the parent directory name.
447 DirName = llvm::sys::path::parent_path(DirName);
448 if (DirName.empty())
449 break;
450
451 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000452 auto Dir = FileMgr.getDirectory(DirName);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000453 if (!Dir)
454 break;
455
456 // If this is a framework directory, then we're a subframework of this
457 // framework.
458 if (llvm::sys::path::extension(DirName) == ".framework") {
459 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
Harlan Haskins8d323d12019-08-01 21:31:56 +0000460 TopFrameworkDir = *Dir;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000461 }
462 } while (true);
463
464 return TopFrameworkDir;
465}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000466
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000467static bool needModuleLookup(Module *RequestingModule,
468 bool HasSuggestedModule) {
469 return HasSuggestedModule ||
470 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
471}
472
Chris Lattner712e3872007-12-17 08:13:48 +0000473/// DoFrameworkLookup - Do a lookup of the specified file in the current
474/// DirectoryLookup, which is a framework directory.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000475Optional<FileEntryRef> DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000476 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
477 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000478 ModuleMap::KnownHeader *SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000479 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000480 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000482 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000483 size_t SlashPos = Filename.find('/');
Alex Lorenz4dc55732019-08-22 18:15:50 +0000484 if (SlashPos == StringRef::npos)
485 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000486
Chris Lattner712e3872007-12-17 08:13:48 +0000487 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000488 // HeaderSearch. Possible answers are yes/no and unknown.
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000489 FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000490 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000491
Chris Lattner712e3872007-12-17 08:13:48 +0000492 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000493 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Alex Lorenz4dc55732019-08-22 18:15:50 +0000494 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattner712e3872007-12-17 08:13:48 +0000496 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000497
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000498 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000499 SmallString<1024> FrameworkName;
Alex Lorenz0377ca62019-08-31 01:26:04 +0000500 FrameworkName += getFrameworkDirRef()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000501 if (FrameworkName.empty() || FrameworkName.back() != '/')
502 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000504 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000505 StringRef ModuleName(Filename.begin(), SlashPos);
506 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000508 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
509 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000510
Daniel Dunbar17138612012-04-05 17:09:40 +0000511 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000512 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000513 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattner5ed76da2006-10-22 07:24:13 +0000515 // If the framework dir doesn't exist, we fail.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000516 auto Dir = FileMgr.getDirectory(FrameworkName);
Alex Lorenz4dc55732019-08-22 18:15:50 +0000517 if (!Dir)
518 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattner5ed76da2006-10-22 07:24:13 +0000520 // Otherwise, if it does, remember that this is the right direntry for this
521 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000522 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000523
524 // If this is a user search directory, check if the framework has been
525 // user-specified as a system framework.
526 if (getDirCharacteristic() == SrcMgr::C_User) {
527 SmallString<1024> SystemFrameworkMarker(FrameworkName);
528 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000529 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000530 CacheEntry.IsUserSpecifiedSystemFramework = true;
531 }
532 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000533 }
Mike Stump11289f42009-09-09 15:08:12 +0000534
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000535 // Set out flags.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000536 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000537 IsFrameworkFound = CacheEntry.Directory;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000538
Craig Topperd2d442c2014-05-17 23:10:59 +0000539 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000540 RelativePath->clear();
541 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
542 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000543
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000544 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000545 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000547 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000548
Craig Topperd2d442c2014-05-17 23:10:59 +0000549 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000550 SearchPath->clear();
551 // Without trailing '/'.
552 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
553 }
554
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000555 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Harlan Haskins8d323d12019-08-01 21:31:56 +0000556
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000557 auto File =
558 FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
Alex Lorenz4dc55732019-08-22 18:15:50 +0000559 if (!File) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000560 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
561 const char *Private = "Private";
562 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
563 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000564 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000565 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
566 Private+strlen(Private));
567
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +0000568 File = FileMgr.getOptionalFileRef(FrameworkName,
569 /*OpenFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000570 }
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000572 // If we found the header and are allowed to suggest a module, do so now.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000573 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000574 // Find the framework in which this header occurs.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000575 StringRef FrameworkPath = File->getFileEntry().getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000576 bool FoundFramework = false;
577 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000578 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000579 auto Dir = FileMgr.getDirectory(FrameworkPath);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000580 if (!Dir)
581 break;
582
583 // If this is a framework directory, then we're a subframework of this
584 // framework.
585 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
586 FoundFramework = true;
587 break;
588 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000589
590 // Get the parent directory name.
591 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
592 if (FrameworkPath.empty())
593 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000594 } while (true);
595
Richard Smith3d5b48c2015-10-16 21:42:56 +0000596 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000597 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000598 if (!HS.findUsableModuleForFrameworkHeader(
Alex Lorenz4dc55732019-08-22 18:15:50 +0000599 &File->getFileEntry(), FrameworkPath, RequestingModule,
600 SuggestedModule, IsSystem))
601 return None;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000602 } else {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000603 if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(),
604 RequestingModule, SuggestedModule,
605 IsSystem))
606 return None;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000607 }
608 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000609 if (File)
610 return *File;
611 return None;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000612}
613
Douglas Gregor89929282012-01-30 06:01:29 +0000614void HeaderSearch::setTarget(const TargetInfo &Target) {
615 ModMap.setTarget(Target);
616}
617
Chris Lattner712e3872007-12-17 08:13:48 +0000618//===----------------------------------------------------------------------===//
619// Header File Location.
620//===----------------------------------------------------------------------===//
621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000622/// Return true with a diagnostic if the file that MSVC would have found
Reid Klecknera97d4c02014-02-18 23:49:24 +0000623/// fails to match the one that Clang would have found with MSVC header search
624/// disabled.
625static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
626 const FileEntry *MSFE, const FileEntry *FE,
627 SourceLocation IncludeLoc) {
628 if (MSFE && FE != MSFE) {
629 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
630 return true;
631 }
632 return false;
633}
Chris Lattner712e3872007-12-17 08:13:48 +0000634
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000635static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
636 assert(!Str.empty());
637 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
638 std::copy(Str.begin(), Str.end(), CopyStr);
639 CopyStr[Str.size()] = '\0';
640 return CopyStr;
641}
642
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000643static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000644 SmallVectorImpl<char> &FrameworkName) {
645 using namespace llvm::sys;
646 path::const_iterator I = path::begin(Path);
647 path::const_iterator E = path::end(Path);
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000648 IsPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000649
650 // Detect different types of framework style paths:
651 //
652 // ...Foo.framework/{Headers,PrivateHeaders}
653 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
654 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
655 // ...<other variations with 'Versions' like in the above path>
656 //
657 // and some other variations among these lines.
658 int FoundComp = 0;
659 while (I != E) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000660 if (*I == "Headers")
661 ++FoundComp;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000662 if (I->endswith(".framework")) {
663 FrameworkName.append(I->begin(), I->end());
664 ++FoundComp;
665 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000666 if (*I == "PrivateHeaders") {
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000667 ++FoundComp;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000668 IsPrivateHeader = true;
669 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000670 ++I;
671 }
672
Erik Pilkingtonabacc252018-09-20 19:00:03 +0000673 return !FrameworkName.empty() && FoundComp >= 2;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000674}
675
676static void
677diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
678 StringRef Includer, StringRef IncludeFilename,
679 const FileEntry *IncludeFE, bool isAngled = false,
680 bool FoundByHeaderMap = false) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000681 bool IsIncluderPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000682 SmallString<128> FromFramework, ToFramework;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000683 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework))
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000684 return;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000685 bool IsIncludeePrivateHeader = false;
686 bool IsIncludeeInFramework = isFrameworkStylePath(
687 IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000688
689 if (!isAngled && !FoundByHeaderMap) {
690 SmallString<128> NewInclude("<");
691 if (IsIncludeeInFramework) {
692 NewInclude += StringRef(ToFramework).drop_back(10); // drop .framework
693 NewInclude += "/";
694 }
695 NewInclude += IncludeFilename;
696 NewInclude += ">";
697 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
698 << IncludeFilename
699 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
700 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000701
702 // Headers in Foo.framework/Headers should not include headers
703 // from Foo.framework/PrivateHeaders, since this violates public/private
704 // API boundaries and can cause modular dependency cycles.
705 if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
706 IsIncludeePrivateHeader && FromFramework == ToFramework)
707 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
708 << IncludeFilename;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000709}
710
James Dennettc07ab2c2012-06-20 00:56:32 +0000711/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000712/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000713/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
714/// non-empty, indicates where the \#including file(s) are, in case a relative
715/// search is needed. Microsoft mode will pass all \#including files.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000716Optional<FileEntryRef> HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000717 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
718 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000719 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
720 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000721 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000722 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
723 bool BuildSystemModule) {
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000724 if (IsMapped)
725 *IsMapped = false;
726
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000727 if (IsFrameworkFound)
728 *IsFrameworkFound = false;
729
Douglas Gregor97eec242011-09-15 22:00:41 +0000730 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000731 *SuggestedModule = ModuleMap::KnownHeader();
Fangrui Song6907ce22018-07-30 19:24:48 +0000732
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000733 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000734 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000735 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000736
737 // If this was an #include_next "/absolute/file", fail.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000738 if (FromDir)
739 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000740
Craig Topperd2d442c2014-05-17 23:10:59 +0000741 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000742 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000743 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000744 RelativePath->clear();
745 RelativePath->append(Filename.begin(), Filename.end());
746 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000747 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000748 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000749 /*IsSystemHeaderDir*/false,
750 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000751 }
Mike Stump11289f42009-09-09 15:08:12 +0000752
Reid Klecknera97d4c02014-02-18 23:49:24 +0000753 // This is the header that MSVC's header search would have found.
Richard Smith8c71eba2014-03-05 20:51:45 +0000754 ModuleMap::KnownHeader MSSuggestedModule;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000755 const FileEntry *MSFE_FE = nullptr;
756 StringRef MSFE_Name;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000757
Douglas Gregor9f93e382011-07-28 04:45:53 +0000758 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000759 // directory. This cannot be based on CurDir, because each includer could be
760 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
761 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000762 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000763 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000764 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000765 bool First = true;
766 for (const auto &IncluderAndDir : Includers) {
767 const FileEntry *Includer = IncluderAndDir.first;
768
Will Wilson0fafd342013-12-27 19:46:16 +0000769 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000770 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000771 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000772 TmpDir.push_back('/');
773 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000774
Richard Smith6f548ec2014-03-06 18:08:08 +0000775 // FIXME: We don't cache the result of getFileInfo across the call to
776 // getFileAndSuggestModule, because it's a reference to an element of
777 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000778 //
Manman Rene4a5d372016-05-17 02:15:12 +0000779 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000780 // from a module build. We should treat this as a system header if we're
781 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000782 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000783 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
784 BuildSystemModule;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000785 if (Optional<FileEntryRef> FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000786 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000787 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000788 if (!Includer) {
789 assert(First && "only first includer can have no file");
790 return FE;
791 }
792
Will Wilson0fafd342013-12-27 19:46:16 +0000793 // Leave CurDir unset.
794 // This file is a system header or C++ unfriendly if the old file is.
795 //
796 // Note that we only use one of FromHFI/ToHFI at once, due to potential
797 // reallocation of the underlying vector potentially making the first
798 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000799 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000800 unsigned DirInfo = FromHFI.DirInfo;
801 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
802 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000803
Alex Lorenz4dc55732019-08-22 18:15:50 +0000804 HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry());
Will Wilson0fafd342013-12-27 19:46:16 +0000805 ToHFI.DirInfo = DirInfo;
806 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
807 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000808
Craig Topperd2d442c2014-05-17 23:10:59 +0000809 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000810 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000811 SearchPath->clear();
812 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
813 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000814 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000815 RelativePath->clear();
816 RelativePath->append(Filename.begin(), Filename.end());
817 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000818 if (First) {
819 diagnoseFrameworkInclude(Diags, IncludeLoc,
820 IncluderAndDir.second->getName(), Filename,
Alex Lorenz4dc55732019-08-22 18:15:50 +0000821 &FE->getFileEntry());
Reid Klecknera97d4c02014-02-18 23:49:24 +0000822 return FE;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000823 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000824
825 // Otherwise, we found the path via MSVC header search rules. If
826 // -Wmsvc-include is enabled, we have to keep searching to see if we
827 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000828 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000829 return FE;
830 } else {
Alex Lorenz4dc55732019-08-22 18:15:50 +0000831 MSFE_FE = &FE->getFileEntry();
832 MSFE_Name = FE->getName();
Richard Smith8c71eba2014-03-05 20:51:45 +0000833 if (SuggestedModule) {
834 MSSuggestedModule = *SuggestedModule;
835 *SuggestedModule = ModuleMap::KnownHeader();
836 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000837 break;
838 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000839 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000840 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000841 }
842 }
Mike Stump11289f42009-09-09 15:08:12 +0000843
Alex Lorenz4dc55732019-08-22 18:15:50 +0000844 Optional<FileEntryRef> MSFE(MSFE_FE ? FileEntryRef(MSFE_Name, *MSFE_FE)
845 : Optional<FileEntryRef>());
846
Craig Topperd2d442c2014-05-17 23:10:59 +0000847 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000848
849 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000850 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000852 // If this is a #include_next request, start searching after the directory the
853 // file was found in.
854 if (FromDir)
855 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000856
Chris Lattnerd4275422007-07-22 07:28:00 +0000857 // Cache all of the lookups performed by this method. Many headers are
858 // multiply included, and the "pragma once" optimization prevents them from
859 // being relex/pp'd, but they would still have to search through a
860 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000861 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000862
863 // If the entry has been previously looked up, the first value will be
864 // non-zero. If the value is equal to i (the start point of our search), then
865 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000866 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000867 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000868 i = CacheLookup.HitIdx;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000869 if (CacheLookup.MappedName) {
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000870 Filename = CacheLookup.MappedName;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000871 if (IsMapped)
872 *IsMapped = true;
873 }
Chris Lattnerd4275422007-07-22 07:28:00 +0000874 } else {
875 // Otherwise, this is the first query, or the previous query didn't match
876 // our search start. We will fill in our found location below, so prime the
877 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000878 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000879 }
Mike Stump11289f42009-09-09 15:08:12 +0000880
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000881 SmallString<64> MappedName;
882
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000883 // Check each directory in sequence to see if it contains this file.
884 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000885 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000886 bool HasBeenMapped = false;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000887 bool IsFrameworkFoundInDir = false;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000888 Optional<FileEntryRef> File = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000889 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000890 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
891 HasBeenMapped, MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000892 if (HasBeenMapped) {
893 CacheLookup.MappedName =
894 copyString(Filename, LookupFileCache.getAllocator());
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000895 if (IsMapped)
896 *IsMapped = true;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000897 }
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000898 if (IsFrameworkFound)
Volodymyr Sapsaie32ff092019-05-27 19:15:30 +0000899 // Because we keep a filename remapped for subsequent search directory
900 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
901 // just for remapping in a current search directory.
902 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
Alex Lorenz4dc55732019-08-22 18:15:50 +0000903 if (!File)
904 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattner712e3872007-12-17 08:13:48 +0000906 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000907
Chris Lattner712e3872007-12-17 08:13:48 +0000908 // This file is a system header or C++ unfriendly if the dir is.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000909 HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry());
Douglas Gregor9f93e382011-07-28 04:45:53 +0000910 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000911
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000912 // If the directory characteristic is User but this framework was
913 // user-specified to be treated as a system framework, promote the
914 // characteristic.
915 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
916 HFI.DirInfo = SrcMgr::C_System;
917
Richard Smith8acadcb2012-06-13 20:27:03 +0000918 // If the filename matches a known system header prefix, override
919 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000920 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
921 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
922 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000923 : SrcMgr::C_User;
924 break;
925 }
926 }
927
Douglas Gregor9f93e382011-07-28 04:45:53 +0000928 // If this file is found in a header map and uses the framework style of
929 // includes, then this header is part of a framework we're building.
930 if (CurDir->isIndexHeaderMap()) {
931 size_t SlashPos = Filename.find('/');
932 if (SlashPos != StringRef::npos) {
933 HFI.IndexHeaderMapHeader = 1;
Fangrui Song6907ce22018-07-30 19:24:48 +0000934 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
Douglas Gregor9f93e382011-07-28 04:45:53 +0000935 SlashPos));
936 }
937 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000938
Alex Lorenz4dc55732019-08-22 18:15:50 +0000939 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
940 &File->getFileEntry(), IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000941 if (SuggestedModule)
942 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000943 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000944 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000945
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000946 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
947 if (!Includers.empty())
Alex Lorenz4dc55732019-08-22 18:15:50 +0000948 diagnoseFrameworkInclude(
949 Diags, IncludeLoc, Includers.front().second->getName(), Filename,
950 &File->getFileEntry(), isAngled, FoundByHeaderMap);
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000951
Chris Lattner712e3872007-12-17 08:13:48 +0000952 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000953 CacheLookup.HitIdx = i;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000954 return File;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000955 }
Mike Stump11289f42009-09-09 15:08:12 +0000956
Douglas Gregord8575e12011-07-30 06:28:34 +0000957 // If we are including a file with a quoted include "foo.h" from inside
958 // a header in a framework that is currently being built, and we couldn't
959 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
960 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000961 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000962 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000963 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000964 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000965 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000966 ScratchFilename += IncludingHFI.Framework;
967 ScratchFilename += '/';
968 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000969
Alex Lorenz4dc55732019-08-22 18:15:50 +0000970 Optional<FileEntryRef> File = LookupFile(
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000971 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
972 Includers.front(), SearchPath, RelativePath, RequestingModule,
973 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000974
Alex Lorenz4dc55732019-08-22 18:15:50 +0000975 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
976 File ? &File->getFileEntry() : nullptr,
977 IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000978 if (SuggestedModule)
979 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000980 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000981 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000982
David Blaikie3c8c46e2014-11-19 05:48:40 +0000983 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000984 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000985 // FIXME: SuggestedModule.
Alex Lorenz4dc55732019-08-22 18:15:50 +0000986 return File;
Douglas Gregord8575e12011-07-30 06:28:34 +0000987 }
988 }
989
Alex Lorenz4dc55732019-08-22 18:15:50 +0000990 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
991 nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000992 if (SuggestedModule)
993 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000994 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000995 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000996
Chris Lattnerd4275422007-07-22 07:28:00 +0000997 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000998 CacheLookup.HitIdx = SearchDirs.size();
Alex Lorenz4dc55732019-08-22 18:15:50 +0000999 return None;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001000}
1001
Chris Lattner63dd32b2006-10-20 04:42:40 +00001002/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +00001003/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +00001004/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1005/// is a subframework within Carbon.framework. If so, return the FileEntry
1006/// for the designated file, otherwise return null.
Alex Lorenz4dc55732019-08-22 18:15:50 +00001007Optional<FileEntryRef> HeaderSearch::LookupSubframeworkHeader(
1008 StringRef Filename, const FileEntry *ContextFileEnt,
1009 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1010 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +00001011 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattner63dd32b2006-10-20 04:42:40 +00001013 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +00001014 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001015 size_t SlashPos = Filename.find('/');
Alex Lorenz4dc55732019-08-22 18:15:50 +00001016 if (SlashPos == StringRef::npos)
1017 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattner63dd32b2006-10-20 04:42:40 +00001019 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001020 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001021
Chris Lattner63dd32b2006-10-20 04:42:40 +00001022 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +00001023 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001024 auto FrameworkPos = ContextName.find(".framework");
1025 if (FrameworkPos == StringRef::npos ||
1026 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1027 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Alex Lorenz4dc55732019-08-22 18:15:50 +00001028 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001029
Mehdi Amini004b9c72016-10-10 22:52:47 +00001030 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1031 FrameworkPos +
1032 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +00001033
Chris Lattner63dd32b2006-10-20 04:42:40 +00001034 // Append Frameworks/HIToolbox.framework/
1035 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001036 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +00001037 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +00001038
David Blaikie13156b62014-11-19 03:06:06 +00001039 auto &CacheLookup =
1040 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1041 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chris Lattner5ed76da2006-10-22 07:24:13 +00001043 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +00001044 if (CacheLookup.second.Directory &&
1045 CacheLookup.first().size() == FrameworkName.size() &&
1046 memcmp(CacheLookup.first().data(), &FrameworkName[0],
1047 CacheLookup.first().size()) != 0)
Alex Lorenz4dc55732019-08-22 18:15:50 +00001048 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001049
Chris Lattner5ed76da2006-10-22 07:24:13 +00001050 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +00001051 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +00001052 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +00001053
Chris Lattner5ed76da2006-10-22 07:24:13 +00001054 // If the framework dir doesn't exist, we fail.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001055 auto Dir = FileMgr.getDirectory(FrameworkName);
Alex Lorenz4dc55732019-08-22 18:15:50 +00001056 if (!Dir)
1057 return None;
Mike Stump11289f42009-09-09 15:08:12 +00001058
Chris Lattner5ed76da2006-10-22 07:24:13 +00001059 // Otherwise, if it does, remember that this is the right direntry for this
1060 // framework.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001061 CacheLookup.second.Directory = *Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +00001062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner577377e2006-10-20 04:55:45 +00001064
Craig Topperd2d442c2014-05-17 23:10:59 +00001065 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001066 RelativePath->clear();
1067 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1068 }
1069
Chris Lattner63dd32b2006-10-20 04:42:40 +00001070 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001071 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +00001072 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001073 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001074 SearchPath->clear();
1075 // Without trailing '/'.
1076 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1077 }
1078
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001079 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +00001080 auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
Alex Lorenz4dc55732019-08-22 18:15:50 +00001081 if (!File) {
Chris Lattner63dd32b2006-10-20 04:42:40 +00001082 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +00001083 HeadersFilename = FrameworkName;
1084 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001085 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001086 SearchPath->clear();
1087 // Without trailing '/'.
1088 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1089 }
1090
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001091 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Duncan P. N. Exon Smith9ef6c492019-08-26 18:29:51 +00001092 File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
Alex Lorenz4dc55732019-08-22 18:15:50 +00001093
1094 if (!File)
1095 return None;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001096 }
Mike Stump11289f42009-09-09 15:08:12 +00001097
Chris Lattner577377e2006-10-20 04:55:45 +00001098 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +00001099 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +00001100 // Note that the temporary 'DirInfo' is required here, as either call to
1101 // getFileInfo could resize the vector and we don't want to rely on order
1102 // of evaluation.
1103 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
Alex Lorenz4dc55732019-08-22 18:15:50 +00001104 getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001105
Richard Smith3d5b48c2015-10-16 21:42:56 +00001106 FrameworkName.pop_back(); // remove the trailing '/'
Alex Lorenz4dc55732019-08-22 18:15:50 +00001107 if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName,
1108 RequestingModule, SuggestedModule,
1109 /*IsSystem*/ false))
1110 return None;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001111
Alex Lorenz4dc55732019-08-22 18:15:50 +00001112 return *File;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001113}
1114
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001115//===----------------------------------------------------------------------===//
1116// File Info Management.
1117//===----------------------------------------------------------------------===//
1118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001119/// Merge the header file info provided by \p OtherHFI into the current
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001120/// header file info (\p HFI)
Fangrui Song6907ce22018-07-30 19:24:48 +00001121static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001122 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +00001123 assert(OtherHFI.External && "expected to merge external HFI");
1124
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001125 HFI.isImport |= OtherHFI.isImport;
1126 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001127 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001128 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +00001129
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001130 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1131 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1132 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1133 }
Richard Smithd8879c82015-08-24 21:59:32 +00001134
1135 HFI.DirInfo = OtherHFI.DirInfo;
1136 HFI.External = (!HFI.IsValid || HFI.External);
1137 HFI.IsValid = true;
1138 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001139
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001140 if (HFI.Framework.empty())
1141 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001142}
Fangrui Song6907ce22018-07-30 19:24:48 +00001143
Steve Naroff3fa455a2009-04-24 20:03:17 +00001144/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001145/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001146HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001147 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +00001148 FileInfo.resize(FE->getUID() + 1);
1149
Richard Smithd8879c82015-08-24 21:59:32 +00001150 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +00001151 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001152 if (ExternalSource && !HFI->Resolved) {
1153 HFI->Resolved = true;
1154 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1155
1156 HFI = &FileInfo[FE->getUID()];
1157 if (ExternalHFI.External)
1158 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +00001159 }
1160
Richard Smithd8879c82015-08-24 21:59:32 +00001161 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +00001162 // We have local information about this header file, so it's no longer
1163 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001164 HFI->External = false;
1165 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001166}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001167
Richard Smith386bb072015-08-18 23:42:23 +00001168const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001169HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1170 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001171 // If we have an external source, ensure we have the latest information.
1172 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001173 HeaderFileInfo *HFI;
1174 if (ExternalSource) {
1175 if (FE->getUID() >= FileInfo.size()) {
1176 if (!WantExternal)
1177 return nullptr;
1178 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001179 }
Richard Smithd8879c82015-08-24 21:59:32 +00001180
1181 HFI = &FileInfo[FE->getUID()];
1182 if (!WantExternal && (!HFI->IsValid || HFI->External))
1183 return nullptr;
1184 if (!HFI->Resolved) {
1185 HFI->Resolved = true;
1186 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1187
1188 HFI = &FileInfo[FE->getUID()];
1189 if (ExternalHFI.External)
1190 mergeHeaderFileInfo(*HFI, ExternalHFI);
1191 }
1192 } else if (FE->getUID() >= FileInfo.size()) {
1193 return nullptr;
1194 } else {
1195 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001196 }
Richard Smith386bb072015-08-18 23:42:23 +00001197
Richard Smithd8879c82015-08-24 21:59:32 +00001198 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001199 return nullptr;
1200
Richard Smithd8879c82015-08-24 21:59:32 +00001201 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001202}
1203
Douglas Gregor37aa4932011-05-04 00:14:37 +00001204bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1205 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001206 if (auto *HFI = getExistingFileInfo(File))
1207 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1208 HFI->ControllingMacroID;
1209 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001210}
1211
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001212void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001213 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001214 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001215 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1216
1217 // Don't mark the file info as non-external if there's nothing to change.
1218 if (!isCompilingModuleHeader) {
1219 if (!isModularHeader)
1220 return;
1221 auto *HFI = getExistingFileInfo(FE);
1222 if (HFI && HFI->isModuleHeader)
1223 return;
1224 }
1225
Richard Smith386bb072015-08-18 23:42:23 +00001226 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001227 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001228 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001229}
1230
Richard Smith20e883e2015-04-29 23:20:19 +00001231bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001232 const FileEntry *File, bool isImport,
1233 bool ModulesEnabled, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001234 ++NumIncluded; // Count # of attempted #includes.
1235
1236 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001237 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001238
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001239 // FIXME: this is a workaround for the lack of proper modules-aware support
1240 // for #import / #pragma once
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001241 auto TryEnterImported = [&]() -> bool {
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001242 if (!ModulesEnabled)
1243 return false;
Richard Smith040e1262017-06-02 01:55:39 +00001244 // Ensure FileInfo bits are up to date.
1245 ModMap.resolveHeaderDirectives(File);
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001246 // Modules with builtins are special; multiple modules use builtins as
1247 // modular headers, example:
1248 //
1249 // module stddef { header "stddef.h" export * }
1250 //
1251 // After module map parsing, this expands to:
1252 //
1253 // module stddef {
1254 // header "/path_to_builtin_dirs/stddef.h"
1255 // textual "stddef.h"
1256 // }
1257 //
1258 // It's common that libc++ and system modules will both define such
1259 // submodules. Make sure cached results for a builtin header won't
1260 // prevent other builtin modules to potentially enter the builtin header.
1261 // Note that builtins are header guarded and the decision to actually
1262 // enter them is postponed to the controlling macros logic below.
1263 bool TryEnterHdr = false;
1264 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1265 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1266 ModuleMap::isBuiltinHeader(
1267 llvm::sys::path::filename(File->getName()));
1268
1269 // Textual headers can be #imported from different modules. Since ObjC
1270 // headers find in the wild might rely only on #import and do not contain
1271 // controlling macros, be conservative and only try to enter textual headers
1272 // if such macro is present.
Bruno Cardoso Lopes4164dd92017-08-12 01:38:26 +00001273 if (!FileInfo.isModuleHeader &&
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001274 FileInfo.getControllingMacro(ExternalLookup))
1275 TryEnterHdr = true;
1276 return TryEnterHdr;
1277 };
1278
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001279 // If this is a #import directive, check that we have not already imported
1280 // this header.
1281 if (isImport) {
1282 // If this has already been imported, don't import it again.
1283 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001284
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001285 // Has this already been #import'ed or #include'd?
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001286 if (FileInfo.NumIncludes && !TryEnterImported())
1287 return false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001288 } else {
1289 // Otherwise, if this is a #include of a file that was previously #import'd
1290 // or if this is the second #include of a #pragma once file, ignore it.
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001291 if (FileInfo.isImport && !TryEnterImported())
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001292 return false;
1293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001295 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1296 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001297 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001298 = FileInfo.getControllingMacro(ExternalLookup)) {
1299 // If the header corresponds to a module, check whether the macro is already
1300 // defined in that module rather than checking in the current set of visible
1301 // modules.
1302 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1303 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001304 ++NumMultiIncludeFileOptzn;
1305 return false;
1306 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001307 }
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001309 // Increment the number of times this file has been included.
1310 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001312 return true;
1313}
1314
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001315size_t HeaderSearch::getTotalMemory() const {
1316 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001317 + llvm::capacity_in_bytes(FileInfo)
1318 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001319 + LookupFileCache.getAllocator().getTotalMemory()
1320 + FrameworkMap.getAllocator().getTotalMemory();
1321}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001322
1323StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001324 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001325}
Douglas Gregor718292f2011-11-11 19:10:28 +00001326
Fangrui Song6907ce22018-07-30 19:24:48 +00001327bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001328 const DirectoryEntry *Root,
1329 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001330 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001331 return false;
1332
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001333 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Fangrui Song6907ce22018-07-30 19:24:48 +00001334
Douglas Gregor718292f2011-11-11 19:10:28 +00001335 StringRef DirName = FileName;
1336 do {
1337 // Get the parent directory name.
1338 DirName = llvm::sys::path::parent_path(DirName);
1339 if (DirName.empty())
1340 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001341
Douglas Gregor718292f2011-11-11 19:10:28 +00001342 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001343 auto Dir = FileMgr.getDirectory(DirName);
Douglas Gregor718292f2011-11-11 19:10:28 +00001344 if (!Dir)
1345 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001346
Ben Langmuir984e1df2014-03-19 20:23:34 +00001347 // Try to load the module map file in this directory.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001348 switch (loadModuleMapFile(*Dir, IsSystem,
1349 llvm::sys::path::extension((*Dir)->getName()) ==
Richard Smith3c1a41a2014-12-02 00:08:08 +00001350 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001351 case LMM_NewlyLoaded:
1352 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001353 // Success. All of the directories we stepped through inherit this module
1354 // map file.
1355 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1356 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1357 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001358
1359 case LMM_NoDirectory:
1360 case LMM_InvalidModuleMap:
1361 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001362 }
1363
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001364 // If we hit the top of our search, we're done.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001365 if (*Dir == Root)
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001366 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001367
Douglas Gregor718292f2011-11-11 19:10:28 +00001368 // Keep track of all of the directories we checked, so we can mark them as
1369 // having module maps if we eventually do find a module map.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001370 FixUpDirectories.push_back(*Dir);
Douglas Gregor718292f2011-11-11 19:10:28 +00001371 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001372}
1373
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001374ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001375HeaderSearch::findModuleForHeader(const FileEntry *File,
1376 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001377 if (ExternalSource) {
1378 // Make sure the external source has handled header info about this file,
1379 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001380 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001381 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001382 return ModMap.findModuleForHeader(File, AllowTextual);
1383}
1384
1385static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1386 Module *RequestingModule,
1387 ModuleMap::KnownHeader *SuggestedModule) {
1388 ModuleMap::KnownHeader Module =
1389 HS.findModuleForHeader(File, /*AllowTextual*/true);
1390 if (SuggestedModule)
1391 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1392 ? ModuleMap::KnownHeader()
1393 : Module;
1394
1395 // If this module specifies [no_undeclared_includes], we cannot find any
1396 // file that's in a non-dependency module.
1397 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1398 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1399 if (!RequestingModule->directlyUses(Module.getModule())) {
1400 return false;
1401 }
1402 }
1403
1404 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001405}
1406
Richard Smith3d5b48c2015-10-16 21:42:56 +00001407bool HeaderSearch::findUsableModuleForHeader(
1408 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1409 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001410 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001411 // If there is a module that corresponds to this header, suggest it.
1412 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001413 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001414 }
1415 return true;
1416}
1417
1418bool HeaderSearch::findUsableModuleForFrameworkHeader(
1419 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1420 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1421 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001422 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001423 // Find the top-level framework based on this framework.
1424 SmallVector<std::string, 4> SubmodulePath;
1425 const DirectoryEntry *TopFrameworkDir
1426 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
Fangrui Song6907ce22018-07-30 19:24:48 +00001427
Richard Smith3d5b48c2015-10-16 21:42:56 +00001428 // Determine the name of the top-level framework.
1429 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1430
1431 // Load this framework module. If that succeeds, find the suggested module
1432 // for this header, if any.
1433 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1434
1435 // FIXME: This can find a module not part of ModuleName, which is
1436 // important so that we're consistent about whether this header
1437 // corresponds to a module. Possibly we should lock down framework modules
1438 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001439 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001440 }
1441 return true;
1442}
1443
Richard Smith9acb99e32014-12-10 03:09:48 +00001444static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001445 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001446 StringRef Filename = llvm::sys::path::filename(File->getName());
1447 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001448 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001449 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001450 else if (Filename == "module.modulemap")
1451 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1452 else
1453 return nullptr;
Harlan Haskins8d323d12019-08-01 21:31:56 +00001454 if (auto File = FileMgr.getFile(PrivateFilename))
1455 return *File;
1456 return nullptr;
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001457}
1458
Richard Smith8128f332017-05-05 22:18:51 +00001459bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +00001460 FileID ID, unsigned *Offset,
1461 StringRef OriginalModuleMapFile) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001462 // Find the directory for the module. For frameworks, that may require going
1463 // up from the 'Modules' directory.
1464 const DirectoryEntry *Dir = nullptr;
Harlan Haskins8d323d12019-08-01 21:31:56 +00001465 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1466 if (auto DirOrErr = FileMgr.getDirectory("."))
1467 Dir = *DirOrErr;
1468 } else {
Richard Smith8b706102017-05-31 20:56:55 +00001469 if (!OriginalModuleMapFile.empty()) {
1470 // We're building a preprocessed module map. Find or invent the directory
1471 // that it originally occupied.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001472 auto DirOrErr = FileMgr.getDirectory(
Richard Smith8b706102017-05-31 20:56:55 +00001473 llvm::sys::path::parent_path(OriginalModuleMapFile));
Harlan Haskins8d323d12019-08-01 21:31:56 +00001474 if (DirOrErr) {
1475 Dir = *DirOrErr;
1476 } else {
Richard Smith8b706102017-05-31 20:56:55 +00001477 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1478 Dir = FakeFile->getDir();
1479 }
1480 } else {
1481 Dir = File->getDir();
1482 }
1483
Richard Smith9acb99e32014-12-10 03:09:48 +00001484 StringRef DirName(Dir->getName());
1485 if (llvm::sys::path::filename(DirName) == "Modules") {
1486 DirName = llvm::sys::path::parent_path(DirName);
1487 if (DirName.endswith(".framework"))
Harlan Haskins8d323d12019-08-01 21:31:56 +00001488 if (auto DirOrErr = FileMgr.getDirectory(DirName))
1489 Dir = *DirOrErr;
Richard Smith9acb99e32014-12-10 03:09:48 +00001490 // FIXME: This assert can fail if there's a race between the above check
1491 // and the removal of the directory.
1492 assert(Dir && "parent must exist");
1493 }
1494 }
1495
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001496 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001497 case LMM_AlreadyLoaded:
1498 case LMM_NewlyLoaded:
1499 return false;
1500 case LMM_NoDirectory:
1501 case LMM_InvalidModuleMap:
1502 return true;
1503 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001504 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001505}
1506
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001507HeaderSearch::LoadModuleMapResult
1508HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1509 const DirectoryEntry *Dir, FileID ID,
1510 unsigned *Offset) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001511 assert(File && "expected FileEntry");
1512
Richard Smith9887d792014-10-17 01:42:53 +00001513 // Check whether we've already loaded this module map, and mark it as being
1514 // loaded in case we recursively try to load it from itself.
1515 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1516 if (!AddResult.second)
1517 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001518
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001519 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
Richard Smith9887d792014-10-17 01:42:53 +00001520 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001521 return LMM_InvalidModuleMap;
1522 }
1523
1524 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001525 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001526 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001527 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001528 return LMM_InvalidModuleMap;
1529 }
1530 }
1531
1532 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001533 return LMM_NewlyLoaded;
1534}
1535
1536const FileEntry *
1537HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001538 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001539 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001540 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1541 // module.map at the framework root is also accepted.
1542 SmallString<128> ModuleMapFileName(Dir->getName());
1543 if (IsFramework)
1544 llvm::sys::path::append(ModuleMapFileName, "Modules");
1545 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
Harlan Haskins8d323d12019-08-01 21:31:56 +00001546 if (auto F = FileMgr.getFile(ModuleMapFileName))
1547 return *F;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001548
1549 // Continue to allow module.map
1550 ModuleMapFileName = Dir->getName();
1551 llvm::sys::path::append(ModuleMapFileName, "module.map");
Harlan Haskins8d323d12019-08-01 21:31:56 +00001552 if (auto F = FileMgr.getFile(ModuleMapFileName))
1553 return *F;
1554 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001555}
1556
1557Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001558 const DirectoryEntry *Dir,
1559 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001560 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001561 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001562
Douglas Gregor56c64012011-11-17 01:41:17 +00001563 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001564 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001565 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001566 // Try to infer a module map from the framework directory.
1567 if (HSOpts->ImplicitModuleMaps)
1568 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001569 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001570
Douglas Gregor56c64012011-11-17 01:41:17 +00001571 case LMM_AlreadyLoaded:
1572 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001573 return nullptr;
1574
Douglas Gregor56c64012011-11-17 01:41:17 +00001575 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001576 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001577 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001578
Ben Langmuira5254002015-07-02 13:19:48 +00001579 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001580}
1581
Fangrui Song6907ce22018-07-30 19:24:48 +00001582HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001583HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1584 bool IsFramework) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001585 if (auto Dir = FileMgr.getDirectory(DirName))
1586 return loadModuleMapFile(*Dir, IsSystem, IsFramework);
Fangrui Song6907ce22018-07-30 19:24:48 +00001587
Douglas Gregor80b69042011-11-12 00:22:19 +00001588 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001589}
1590
Fangrui Song6907ce22018-07-30 19:24:48 +00001591HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001592HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1593 bool IsFramework) {
1594 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001595 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001596 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001597
Ben Langmuir984e1df2014-03-19 20:23:34 +00001598 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001599 LoadModuleMapResult Result =
1600 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001601 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1602 // E.g. Foo.framework/Modules/module.modulemap
1603 // ^Dir ^ModuleMapFile
1604 if (Result == LMM_NewlyLoaded)
1605 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001606 else if (Result == LMM_InvalidModuleMap)
1607 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001608 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001609 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001610 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001611}
Douglas Gregor718292f2011-11-11 19:10:28 +00001612
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001613void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001614 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001615
Richard Smith47972af2015-06-16 00:08:24 +00001616 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001617 // Load module maps for each of the header search directories.
1618 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1619 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1620 if (SearchDirs[Idx].isFramework()) {
1621 std::error_code EC;
1622 SmallString<128> DirNative;
1623 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1624 DirNative);
1625
1626 // Search each of the ".framework" directories to load them as modules.
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001627 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
Jonas Devliegherefc514902018-10-10 13:27:25 +00001628 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1629 DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001630 Dir != DirEnd && !EC; Dir.increment(EC)) {
Sam McCall0ae00562018-09-14 12:47:38 +00001631 if (llvm::sys::path::extension(Dir->path()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001632 continue;
1633
Harlan Haskins8d323d12019-08-01 21:31:56 +00001634 auto FrameworkDir =
Sam McCall0ae00562018-09-14 12:47:38 +00001635 FileMgr.getDirectory(Dir->path());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001636 if (!FrameworkDir)
1637 continue;
1638
1639 // Load this framework module.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001640 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
Sam McCall0ae00562018-09-14 12:47:38 +00001641 IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001642 }
1643 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001644 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001645
1646 // FIXME: Deal with header maps.
1647 if (SearchDirs[Idx].isHeaderMap())
1648 continue;
1649
1650 // Try to load a module map file for the search directory.
1651 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1652 /*IsFramework*/ false);
1653
1654 // Try to load module map files for immediate subdirectories of this
1655 // search directory.
1656 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001657 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001658 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001659
Douglas Gregor07f43572012-01-29 18:15:03 +00001660 // Populate the list of modules.
Fangrui Song6907ce22018-07-30 19:24:48 +00001661 for (ModuleMap::module_iterator M = ModMap.module_begin(),
Douglas Gregor07f43572012-01-29 18:15:03 +00001662 MEnd = ModMap.module_end();
1663 M != MEnd; ++M) {
1664 Modules.push_back(M->getValue());
1665 }
1666}
Douglas Gregor0339a642013-03-21 01:08:50 +00001667
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001668void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001669 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001670 return;
1671
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001672 // Load module maps for each of the header search directories.
1673 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001674 // We only care about normal header directories.
1675 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001676 continue;
1677 }
1678
1679 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001680 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001681 SearchDirs[Idx].isSystemHeaderDirectory(),
1682 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001683 }
1684}
1685
Douglas Gregor0339a642013-03-21 01:08:50 +00001686void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001687 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001688 "Should not be loading subdirectory module maps");
1689
Douglas Gregor0339a642013-03-21 01:08:50 +00001690 if (SearchDir.haveSearchedAllModuleMaps())
1691 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001692
1693 std::error_code EC;
Alex Lorenz7d76ef92018-11-14 01:08:03 +00001694 SmallString<128> Dir = SearchDir.getDir()->getName();
1695 FileMgr.makeAbsolutePath(Dir);
Douglas Gregor0339a642013-03-21 01:08:50 +00001696 SmallString<128> DirNative;
Alex Lorenz7d76ef92018-11-14 01:08:03 +00001697 llvm::sys::path::native(Dir, DirNative);
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001698 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
Jonas Devliegherefc514902018-10-10 13:27:25 +00001699 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001700 Dir != DirEnd && !EC; Dir.increment(EC)) {
Sam McCall0ae00562018-09-14 12:47:38 +00001701 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001702 if (IsFramework == SearchDir.isFramework())
Sam McCall0ae00562018-09-14 12:47:38 +00001703 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001704 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001705 }
1706
1707 SearchDir.setSearchedAllModuleMaps(true);
1708}
Richard Smith4eb83932016-04-27 21:57:05 +00001709
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001710std::string HeaderSearch::suggestPathToFileForDiagnostics(
1711 const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
Richard Smith4eb83932016-04-27 21:57:05 +00001712 // FIXME: We assume that the path name currently cached in the FileEntry is
Eric Liudffb1a82018-01-29 13:21:23 +00001713 // the most appropriate one for this analysis (and that it's spelled the
1714 // same way as the corresponding header search path).
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001715 return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1716 MainFile, IsSystem);
Eric Liudffb1a82018-01-29 13:21:23 +00001717}
1718
1719std::string HeaderSearch::suggestPathToFileForDiagnostics(
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001720 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1721 bool *IsSystem) {
Eric Liudffb1a82018-01-29 13:21:23 +00001722 using namespace llvm::sys;
Richard Smith4eb83932016-04-27 21:57:05 +00001723
1724 unsigned BestPrefixLength = 0;
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001725 // Checks whether Dir and File shares a common prefix, if they do and that's
1726 // the longest prefix we've seen so for it returns true and updates the
1727 // BestPrefixLength accordingly.
1728 auto CheckDir = [&](llvm::StringRef Dir) -> bool {
Eric Liudffb1a82018-01-29 13:21:23 +00001729 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
Kadir Cetinkaya936c67d2019-04-24 09:23:31 +00001730 if (!WorkingDir.empty() && !path::is_absolute(Dir))
Pavel Labath1ad53ca2019-01-16 09:55:32 +00001731 fs::make_absolute(WorkingDir, DirPath);
Kadir Cetinkaya936c67d2019-04-24 09:23:31 +00001732 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1733 Dir = DirPath;
Eric Liudffb1a82018-01-29 13:21:23 +00001734 for (auto NI = path::begin(File), NE = path::end(File),
1735 DI = path::begin(Dir), DE = path::end(Dir);
Richard Smith4eb83932016-04-27 21:57:05 +00001736 /*termination condition in loop*/; ++NI, ++DI) {
Eric Liudffb1a82018-01-29 13:21:23 +00001737 // '.' components in File are ignored.
Richard Smith4eb83932016-04-27 21:57:05 +00001738 while (NI != NE && *NI == ".")
1739 ++NI;
1740 if (NI == NE)
1741 break;
1742
1743 // '.' components in Dir are ignored.
1744 while (DI != DE && *DI == ".")
1745 ++DI;
1746 if (DI == DE) {
Eric Liudffb1a82018-01-29 13:21:23 +00001747 // Dir is a prefix of File, up to '.' components and choice of path
Richard Smith4eb83932016-04-27 21:57:05 +00001748 // separators.
Eric Liudffb1a82018-01-29 13:21:23 +00001749 unsigned PrefixLength = NI - path::begin(File);
Richard Smith4eb83932016-04-27 21:57:05 +00001750 if (PrefixLength > BestPrefixLength) {
1751 BestPrefixLength = PrefixLength;
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001752 return true;
Richard Smith4eb83932016-04-27 21:57:05 +00001753 }
1754 break;
1755 }
1756
Kadir Cetinkaya51f85b42019-06-06 18:49:16 +00001757 // Consider all path separators equal.
1758 if (NI->size() == 1 && DI->size() == 1 &&
1759 path::is_separator(NI->front()) && path::is_separator(DI->front()))
1760 continue;
1761
Richard Smith4eb83932016-04-27 21:57:05 +00001762 if (*NI != *DI)
1763 break;
1764 }
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001765 return false;
1766 };
1767
1768 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1769 // FIXME: Support this search within frameworks and header maps.
1770 if (!SearchDirs[I].isNormalDir())
1771 continue;
1772
1773 StringRef Dir = SearchDirs[I].getDir()->getName();
1774 if (CheckDir(Dir) && IsSystem)
1775 *IsSystem = BestPrefixLength ? I >= SystemDirIdx : false;
Richard Smith4eb83932016-04-27 21:57:05 +00001776 }
1777
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001778 // Try to shorten include path using TUs directory, if we couldn't find any
1779 // suitable prefix in include search paths.
1780 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
1781 *IsSystem = false;
1782
1783
Kadir Cetinkaya40f8f7f2019-04-24 08:45:03 +00001784 return path::convert_to_slash(File.drop_front(BestPrefixLength));
Richard Smith4eb83932016-04-27 21:57:05 +00001785}