blob: a1dbe4943451517aa6897723640fa54e2b05e33d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencer5f016e22007-07-11 17:01:13 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Lex/HeaderMap.h"
18#include "clang/Lex/HeaderSearchOptions.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070019#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Lex/Lexer.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070021#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/Hashing.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "llvm/ADT/SmallString.h"
Ted Kremenekeabea452011-07-27 18:41:18 +000024#include "llvm/Support/Capacity.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "llvm/Support/FileSystem.h"
26#include "llvm/Support/Path.h"
Daniel Jasperddd2dfc2013-09-24 09:14:14 +000027#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000028#include <cstdio>
Douglas Gregor3cc62772013-01-22 23:49:45 +000029#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoadeb7822013-01-26 16:29:36 +000030#include <limits.h>
Douglas Gregor3cc62772013-01-22 23:49:45 +000031#endif
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor8c5a7602009-04-25 23:30:02 +000034const IdentifierInfo *
35HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
36 if (ControllingMacro)
37 return ControllingMacro;
38
39 if (!ControllingMacroID || !External)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070040 return nullptr;
Douglas Gregor8c5a7602009-04-25 23:30:02 +000041
42 ControllingMacro = External->GetIdentifier(ControllingMacroID);
43 return ControllingMacro;
44}
45
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000046ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
47
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000048HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Manuel Klimekee0cd372013-10-24 07:51:24 +000049 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Stephen Hines651f13c2014-04-23 16:59:28 -070050 const LangOptions &LangOpts,
Douglas Gregordc58aa72012-01-30 06:01:29 +000051 const TargetInfo *Target)
Stephen Hines651f13c2014-04-23 16:59:28 -070052 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
53 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
Nico Weber74a5fd82011-05-24 04:31:14 +000054 AngledDirIdx = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000055 SystemDirIdx = 0;
56 NoCurDirSearch = false;
Mike Stump1eb44332009-09-09 15:08:12 +000057
Stephen Hines6bcf27b2014-05-29 04:14:42 -070058 ExternalLookup = nullptr;
59 ExternalSource = nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +000060 NumIncluded = 0;
61 NumMultiIncludeFileOptzn = 0;
62 NumFrameworkLookups = NumSubFrameworkLookups = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -070063
64 EnabledModules = LangOpts.Modules;
Reid Spencer5f016e22007-07-11 17:01:13 +000065}
66
Chris Lattner822da612007-12-17 06:36:45 +000067HeaderSearch::~HeaderSearch() {
68 // Delete headermaps.
69 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
70 delete HeaderMaps[i].second;
71}
Mike Stump1eb44332009-09-09 15:08:12 +000072
Reid Spencer5f016e22007-07-11 17:01:13 +000073void HeaderSearch::PrintStats() {
74 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
75 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
76 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
77 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
78 NumOnceOnlyFiles += FileInfo[i].isImport;
79 if (MaxNumIncludes < FileInfo[i].NumIncludes)
80 MaxNumIncludes = FileInfo[i].NumIncludes;
81 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
82 }
83 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
84 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
85 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump1eb44332009-09-09 15:08:12 +000086
Reid Spencer5f016e22007-07-11 17:01:13 +000087 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
88 fprintf(stderr, " %d #includes skipped due to"
89 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump1eb44332009-09-09 15:08:12 +000090
Reid Spencer5f016e22007-07-11 17:01:13 +000091 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
92 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
93}
94
Chris Lattner822da612007-12-17 06:36:45 +000095/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000096/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000097const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000098 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000099 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +0000100 if (!HeaderMaps.empty()) {
101 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +0000102 // Pointer equality comparison of FileEntries works because they are
103 // already uniqued by inode.
Mike Stump1eb44332009-09-09 15:08:12 +0000104 if (HeaderMaps[i].first == FE)
Chris Lattner822da612007-12-17 06:36:45 +0000105 return HeaderMaps[i].second;
106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Chris Lattner39b49bc2010-11-23 08:35:12 +0000108 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattner822da612007-12-17 06:36:45 +0000109 HeaderMaps.push_back(std::make_pair(FE, HM));
110 return HM;
111 }
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700113 return nullptr;
Chris Lattner822da612007-12-17 06:36:45 +0000114}
115
Douglas Gregore434ec72012-01-29 17:08:11 +0000116std::string HeaderSearch::getModuleFileName(Module *Module) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700117 return getModuleFileName(Module->Name, Module->ModuleMap->getName());
Douglas Gregore434ec72012-01-29 17:08:11 +0000118}
119
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700120std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
121 StringRef ModuleMapPath) {
Douglas Gregore434ec72012-01-29 17:08:11 +0000122 // If we don't have a module cache path, we can't do anything.
123 if (ModuleCachePath.empty())
124 return std::string();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700125
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000126 SmallString<256> Result(ModuleCachePath);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700127 llvm::sys::fs::make_absolute(Result);
128
129 if (HSOpts->DisableModuleHash) {
130 llvm::sys::path::append(Result, ModuleName + ".pcm");
131 } else {
132 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
133 // be globally unique to this particular module. To avoid false-negatives
134 // on case-insensitive filesystems, we use lower-case, which is safe because
135 // to cause a collision the modules must have the same name, which is an
136 // error if they are imported in the same translation.
137 SmallString<256> AbsModuleMapPath(ModuleMapPath);
138 llvm::sys::fs::make_absolute(AbsModuleMapPath);
139 llvm::APInt Code(64, llvm::hash_value(AbsModuleMapPath.str().lower()));
140 SmallString<128> HashStr;
141 Code.toStringUnsigned(HashStr, /*Radix*/36);
142 llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
143 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000144 return Result.str().str();
145}
146
147Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000148 // Look in the module map to determine if there is a module by this name.
Douglas Gregore434ec72012-01-29 17:08:11 +0000149 Module *Module = ModMap.findModule(ModuleName);
150 if (Module || !AllowSearch)
151 return Module;
152
Douglas Gregor7005b902013-01-10 01:43:00 +0000153 // Look through the various header search paths to load any available module
Douglas Gregore434ec72012-01-29 17:08:11 +0000154 // maps, searching for a module map that describes this module.
155 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
156 if (SearchDirs[Idx].isFramework()) {
157 // Search for or infer a module map for a framework.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000158 SmallString<128> FrameworkDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000159 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
160 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
161 if (const DirectoryEntry *FrameworkDir
162 = FileMgr.getDirectory(FrameworkDirName)) {
163 bool IsSystem
164 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
165 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregorcf70d782011-11-12 00:05:07 +0000166 if (Module)
167 break;
168 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000169 }
170
171 // FIXME: Figure out how header maps and module maps will work together.
172
173 // Only deal with normal search directories.
174 if (!SearchDirs[Idx].isNormalDir())
175 continue;
Douglas Gregor8f5d7d12013-06-21 16:28:10 +0000176
177 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregore434ec72012-01-29 17:08:11 +0000178 // Search for a module map file in this directory.
Stephen Hines651f13c2014-04-23 16:59:28 -0700179 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
180 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregore434ec72012-01-29 17:08:11 +0000181 // We just loaded a module map file; check whether the module is
182 // available now.
183 Module = ModMap.findModule(ModuleName);
184 if (Module)
185 break;
186 }
187
188 // Search for a module map in a subdirectory with the same name as the
189 // module.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000190 SmallString<128> NestedModuleMapDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000191 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
192 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Stephen Hines651f13c2014-04-23 16:59:28 -0700193 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
194 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregore434ec72012-01-29 17:08:11 +0000195 // If we just loaded a module map file, look for the module again.
196 Module = ModMap.findModule(ModuleName);
197 if (Module)
198 break;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000199 }
Douglas Gregorcdf28082013-03-21 01:08:50 +0000200
201 // If we've already performed the exhaustive search for module maps in this
202 // search directory, don't do it again.
203 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
204 continue;
205
206 // Load all module maps in the immediate subdirectories of this search
207 // directory.
208 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
209
210 // Look again for the module.
211 Module = ModMap.findModule(ModuleName);
212 if (Module)
213 break;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000214 }
Douglas Gregorcdf28082013-03-21 01:08:50 +0000215
Douglas Gregore434ec72012-01-29 17:08:11 +0000216 return Module;
Douglas Gregor9a6da692011-09-12 20:41:59 +0000217}
218
Chris Lattnerdf772332007-12-17 07:52:39 +0000219//===----------------------------------------------------------------------===//
220// File lookup within a DirectoryLookup scope
221//===----------------------------------------------------------------------===//
222
Chris Lattner3af66a92007-12-17 17:57:27 +0000223/// getName - Return the directory or filename corresponding to this lookup
224/// object.
225const char *DirectoryLookup::getName() const {
226 if (isNormalDir())
227 return getDir()->getName();
228 if (isFramework())
229 return getFrameworkDir()->getName();
230 assert(isHeaderMap() && "Unknown DirectoryLookup");
231 return getHeaderMap()->getFileName();
232}
233
Stephen Hines651f13c2014-04-23 16:59:28 -0700234static const FileEntry *
235getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
236 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
237 ModuleMap::KnownHeader *SuggestedModule) {
238 // If we have a module map that might map this header, load it and
239 // check whether we'll have a suggestion for a module.
240 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
241 if (SuggestedModule) {
242 const FileEntry *File = HS.getFileMgr().getFile(FileName,
243 /*OpenFile=*/false);
244 if (File) {
245 // If there is a module that corresponds to this header, suggest it.
246 *SuggestedModule = HS.findModuleForHeader(File);
247
248 // FIXME: This appears to be a no-op. We loaded the module map for this
249 // directory at the start of this function.
250 if (!SuggestedModule->getModule() &&
251 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
252 *SuggestedModule = HS.findModuleForHeader(File);
253 }
254
255 return File;
256 }
257
258 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
259}
Chris Lattner3af66a92007-12-17 17:57:27 +0000260
Chris Lattnerdf772332007-12-17 07:52:39 +0000261/// LookupFile - Lookup the specified file in this search path, returning it
262/// if it exists or returning null if not.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000263const FileEntry *DirectoryLookup::LookupFile(
Stephen Hines651f13c2014-04-23 16:59:28 -0700264 StringRef &Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000265 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000267 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000268 ModuleMap::KnownHeader *SuggestedModule,
Stephen Hines651f13c2014-04-23 16:59:28 -0700269 bool &InUserSpecifiedSystemFramework,
270 bool &HasBeenMapped,
271 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000272 InUserSpecifiedSystemFramework = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700273 HasBeenMapped = false;
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000274
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000275 SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000276 if (isNormalDir()) {
277 // Concatenate the requested file onto the directory.
Eli Friedmana6e023c2011-07-08 20:17:28 +0000278 TmpDir = getDir()->getName();
279 llvm::sys::path::append(TmpDir, Filename);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700280 if (SearchPath) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000281 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000282 SearchPath->clear();
283 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
284 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700285 if (RelativePath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000286 RelativePath->clear();
287 RelativePath->append(Filename.begin(), Filename.end());
288 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700289
290 return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
291 isSystemHeaderDirectory(),
292 SuggestedModule);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000293 }
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattnerafded5b2007-12-17 08:13:48 +0000295 if (isFramework())
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000296 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000297 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000299 assert(isHeaderMap() && "Unknown directory lookup");
Stephen Hines651f13c2014-04-23 16:59:28 -0700300 const HeaderMap *HM = getHeaderMap();
301 SmallString<1024> Path;
302 StringRef Dest = HM->lookupFilename(Filename, Path);
303 if (Dest.empty())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700304 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700305
306 const FileEntry *Result;
307
308 // Check if the headermap maps the filename to a framework include
309 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
310 // framework include.
311 if (llvm::sys::path::is_relative(Dest)) {
312 MappedName.clear();
313 MappedName.append(Dest.begin(), Dest.end());
314 Filename = StringRef(MappedName.begin(), MappedName.size());
315 HasBeenMapped = true;
316 Result = HM->LookupFile(Filename, HS.getFileMgr());
317
318 } else {
319 Result = HS.getFileMgr().getFile(Dest);
320 }
321
Manuel Klimek74124942011-04-26 21:50:03 +0000322 if (Result) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700323 if (SearchPath) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000324 StringRef SearchPathRef(getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000325 SearchPath->clear();
326 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
327 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700328 if (RelativePath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000329 RelativePath->clear();
330 RelativePath->append(Filename.begin(), Filename.end());
331 }
332 }
333 return Result;
Chris Lattnerdf772332007-12-17 07:52:39 +0000334}
335
Douglas Gregor7005b902013-01-10 01:43:00 +0000336/// \brief Given a framework directory, find the top-most framework directory.
337///
338/// \param FileMgr The file manager to use for directory lookups.
339/// \param DirName The name of the framework directory.
340/// \param SubmodulePath Will be populated with the submodule path from the
341/// returned top-level module to the originally named framework.
342static const DirectoryEntry *
343getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
344 SmallVectorImpl<std::string> &SubmodulePath) {
345 assert(llvm::sys::path::extension(DirName) == ".framework" &&
346 "Not a framework directory");
347
Douglas Gregor7005b902013-01-10 01:43:00 +0000348 // Note: as an egregious but useful hack we use the real path here, because
349 // frameworks moving between top-level frameworks to embedded frameworks tend
350 // to be symlinked, and we base the logical structure of modules on the
351 // physical layout. In particular, we need to deal with crazy includes like
352 //
353 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
354 //
355 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
356 // which one should access with, e.g.,
357 //
358 // #include <Bar/Wibble.h>
359 //
360 // Similar issues occur when a top-level framework has moved into an
361 // embedded framework.
Douglas Gregor7005b902013-01-10 01:43:00 +0000362 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregor713b7c02013-01-26 00:55:12 +0000363 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor7005b902013-01-10 01:43:00 +0000364 do {
365 // Get the parent directory name.
366 DirName = llvm::sys::path::parent_path(DirName);
367 if (DirName.empty())
368 break;
369
370 // Determine whether this directory exists.
371 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
372 if (!Dir)
373 break;
374
375 // If this is a framework directory, then we're a subframework of this
376 // framework.
377 if (llvm::sys::path::extension(DirName) == ".framework") {
378 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
379 TopFrameworkDir = Dir;
380 }
381 } while (true);
382
383 return TopFrameworkDir;
384}
Chris Lattnerdf772332007-12-17 07:52:39 +0000385
Chris Lattnerafded5b2007-12-17 08:13:48 +0000386/// DoFrameworkLookup - Do a lookup of the specified file in the current
387/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000388const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000389 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000390 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000391 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000392 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000393 ModuleMap::KnownHeader *SuggestedModule,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000394 bool &InUserSpecifiedSystemFramework) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000395{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000396 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000399 size_t SlashPos = Filename.find('/');
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700400 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattnerafded5b2007-12-17 08:13:48 +0000402 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000403 // HeaderSearch. Possible answers are yes/no and unknown.
404 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnera1394812010-01-10 01:35:12 +0000405 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattnerafded5b2007-12-17 08:13:48 +0000407 // If it is known and in some other directory, fail.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000408 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700409 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattnerafded5b2007-12-17 08:13:48 +0000411 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000414 SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000415 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 if (FrameworkName.empty() || FrameworkName.back() != '/')
417 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000420 StringRef ModuleName(Filename.begin(), SlashPos);
421 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
424 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000426 // If the cache entry was unresolved, populate it now.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700427 if (!CacheEntry.Directory) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000428 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 // If the framework dir doesn't exist, we fail.
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000431 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700432 if (!Dir) return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 // Otherwise, if it does, remember that this is the right direntry for this
435 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000436 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000437
438 // If this is a user search directory, check if the framework has been
439 // user-specified as a system framework.
440 if (getDirCharacteristic() == SrcMgr::C_User) {
441 SmallString<1024> SystemFrameworkMarker(FrameworkName);
442 SystemFrameworkMarker += ".system_framework";
443 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
444 CacheEntry.IsUserSpecifiedSystemFramework = true;
445 }
446 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 }
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000449 // Set the 'user-specified system framework' flag.
450 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
451
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700452 if (RelativePath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000453 RelativePath->clear();
454 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
455 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
458 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000461
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700462 if (SearchPath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000463 SearchPath->clear();
464 // Without trailing '/'.
465 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
466 }
467
Chris Lattnera1394812010-01-10 01:35:12 +0000468 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor7005b902013-01-10 01:43:00 +0000469 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
470 /*openFile=*/!SuggestedModule);
471 if (!FE) {
472 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
473 const char *Private = "Private";
474 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
475 Private+strlen(Private));
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700476 if (SearchPath)
Douglas Gregor7005b902013-01-10 01:43:00 +0000477 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
478 Private+strlen(Private));
479
480 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000481 }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregor7005b902013-01-10 01:43:00 +0000483 // If we found the header and are allowed to suggest a module, do so now.
484 if (FE && SuggestedModule) {
485 // Find the framework in which this header occurs.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700486 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor7005b902013-01-10 01:43:00 +0000487 bool FoundFramework = false;
488 do {
Douglas Gregor7005b902013-01-10 01:43:00 +0000489 // Determine whether this directory exists.
490 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
491 if (!Dir)
492 break;
493
494 // If this is a framework directory, then we're a subframework of this
495 // framework.
496 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
497 FoundFramework = true;
498 break;
499 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700500
501 // Get the parent directory name.
502 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
503 if (FrameworkPath.empty())
504 break;
Douglas Gregor7005b902013-01-10 01:43:00 +0000505 } while (true);
506
507 if (FoundFramework) {
508 // Find the top-level framework based on this framework.
509 SmallVector<std::string, 4> SubmodulePath;
510 const DirectoryEntry *TopFrameworkDir
511 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
512
513 // Determine the name of the top-level framework.
514 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
515
516 // Load this framework module. If that succeeds, find the suggested module
517 // for this header, if any.
518 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
519 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
520 *SuggestedModule = HS.findModuleForHeader(FE);
521 }
522 } else {
523 *SuggestedModule = HS.findModuleForHeader(FE);
524 }
525 }
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000526 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000527}
528
Douglas Gregordc58aa72012-01-30 06:01:29 +0000529void HeaderSearch::setTarget(const TargetInfo &Target) {
530 ModMap.setTarget(Target);
531}
532
Chris Lattnerdf772332007-12-17 07:52:39 +0000533
Chris Lattnerafded5b2007-12-17 08:13:48 +0000534//===----------------------------------------------------------------------===//
535// Header File Location.
536//===----------------------------------------------------------------------===//
537
Stephen Hines651f13c2014-04-23 16:59:28 -0700538/// \brief Return true with a diagnostic if the file that MSVC would have found
539/// fails to match the one that Clang would have found with MSVC header search
540/// disabled.
541static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
542 const FileEntry *MSFE, const FileEntry *FE,
543 SourceLocation IncludeLoc) {
544 if (MSFE && FE != MSFE) {
545 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
546 return true;
547 }
548 return false;
549}
550
551static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
552 assert(!Str.empty());
553 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
554 std::copy(Str.begin(), Str.end(), CopyStr);
555 CopyStr[Str.size()] = '\0';
556 return CopyStr;
557}
Chris Lattnerafded5b2007-12-17 08:13:48 +0000558
James Dennett853519c2012-06-20 00:56:32 +0000559/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Reid Spencer5f016e22007-07-11 17:01:13 +0000560/// return null on failure. isAngled indicates whether the file reference is
Stephen Hines651f13c2014-04-23 16:59:28 -0700561/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
562/// non-empty, indicates where the \#including file(s) are, in case a relative
563/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000564const FileEntry *HeaderSearch::LookupFile(
Stephen Hines651f13c2014-04-23 16:59:28 -0700565 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
566 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
567 ArrayRef<const FileEntry *> Includers, SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000568 SmallVectorImpl<char> *RelativePath,
Stephen Hines651f13c2014-04-23 16:59:28 -0700569 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
Daniel Jasperc6417092013-10-22 08:09:47 +0000570 if (!HSOpts->ModuleMapFiles.empty()) {
571 // Preload all explicitly specified module map files. This enables modules
572 // map files lying in a directory structure separate from the header files
573 // that they describe. These cannot be loaded lazily upon encountering a
Stephen Hines651f13c2014-04-23 16:59:28 -0700574 // header file, as there is no other known mapping from a header file to its
Daniel Jasperc6417092013-10-22 08:09:47 +0000575 // module map file.
576 for (llvm::SetVector<std::string>::iterator
577 I = HSOpts->ModuleMapFiles.begin(),
578 E = HSOpts->ModuleMapFiles.end();
579 I != E; ++I) {
580 const FileEntry *File = FileMgr.getFile(*I);
581 if (!File)
582 continue;
583 loadModuleMapFile(File, /*IsSystem=*/false);
584 }
585 HSOpts->ModuleMapFiles.clear();
586 }
587
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000588 if (SuggestedModule)
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000589 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000592 if (llvm::sys::path::is_absolute(Filename)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700593 CurDir = nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000594
595 // If this was an #include_next "/absolute/file", fail.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700596 if (FromDir) return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700598 if (SearchPath)
Manuel Klimek74124942011-04-26 21:50:03 +0000599 SearchPath->clear();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700600 if (RelativePath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000601 RelativePath->clear();
602 RelativePath->append(Filename.begin(), Filename.end());
603 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000605 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Stephen Hines651f13c2014-04-23 16:59:28 -0700608 // This is the header that MSVC's header search would have found.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700609 const FileEntry *MSFE = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700610 ModuleMap::KnownHeader MSSuggestedModule;
611
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000612 // Unless disabled, check to see if the file is in the #includer's
Stephen Hines651f13c2014-04-23 16:59:28 -0700613 // directory. This cannot be based on CurDir, because each includer could be
614 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
615 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerdf772332007-12-17 07:52:39 +0000616 // This search is not done for <> headers.
Stephen Hines651f13c2014-04-23 16:59:28 -0700617 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000618 SmallString<1024> TmpDir;
Stephen Hines651f13c2014-04-23 16:59:28 -0700619 for (ArrayRef<const FileEntry *>::iterator I = Includers.begin(),
620 E = Includers.end();
621 I != E; ++I) {
622 const FileEntry *Includer = *I;
623 // Concatenate the requested file onto the directory.
624 // FIXME: Portability. Filename concatenation should be in sys::Path.
625 TmpDir = Includer->getDir()->getName();
626 TmpDir.push_back('/');
627 TmpDir.append(Filename.begin(), Filename.end());
Douglas Gregor21efbb62012-08-13 15:47:39 +0000628
Stephen Hines651f13c2014-04-23 16:59:28 -0700629 // FIXME: We don't cache the result of getFileInfo across the call to
630 // getFileAndSuggestModule, because it's a reference to an element of
631 // a container that could be reallocated across this call.
632 bool IncluderIsSystemHeader =
633 getFileInfo(Includer).DirInfo != SrcMgr::C_User;
634 if (const FileEntry *FE =
635 getFileAndSuggestModule(*this, TmpDir.str(), Includer->getDir(),
636 IncluderIsSystemHeader,
637 SuggestedModule)) {
638 // Leave CurDir unset.
639 // This file is a system header or C++ unfriendly if the old file is.
640 //
641 // Note that we only use one of FromHFI/ToHFI at once, due to potential
642 // reallocation of the underlying vector potentially making the first
643 // reference binding dangling.
644 HeaderFileInfo &FromHFI = getFileInfo(Includer);
645 unsigned DirInfo = FromHFI.DirInfo;
646 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
647 StringRef Framework = FromHFI.Framework;
Douglas Gregor21efbb62012-08-13 15:47:39 +0000648
Stephen Hines651f13c2014-04-23 16:59:28 -0700649 HeaderFileInfo &ToHFI = getFileInfo(FE);
650 ToHFI.DirInfo = DirInfo;
651 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
652 ToHFI.Framework = Framework;
653
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700654 if (SearchPath) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700655 StringRef SearchPathRef(Includer->getDir()->getName());
656 SearchPath->clear();
657 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
658 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700659 if (RelativePath) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700660 RelativePath->clear();
661 RelativePath->append(Filename.begin(), Filename.end());
662 }
663 if (I == Includers.begin())
664 return FE;
665
666 // Otherwise, we found the path via MSVC header search rules. If
667 // -Wmsvc-include is enabled, we have to keep searching to see if we
668 // would've found this header in -I or -isystem directories.
669 if (Diags.getDiagnosticLevel(diag::ext_pp_include_search_ms,
670 IncludeLoc) ==
671 DiagnosticsEngine::Ignored) {
672 return FE;
673 } else {
674 MSFE = FE;
675 if (SuggestedModule) {
676 MSSuggestedModule = *SuggestedModule;
677 *SuggestedModule = ModuleMap::KnownHeader();
678 }
679 break;
680 }
Manuel Klimek74124942011-04-26 21:50:03 +0000681 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 }
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700685 CurDir = nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000686
687 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000688 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 // If this is a #include_next request, start searching after the directory the
691 // file was found in.
692 if (FromDir)
693 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner9960ae82007-07-22 07:28:00 +0000695 // Cache all of the lookups performed by this method. Many headers are
696 // multiply included, and the "pragma once" optimization prevents them from
697 // being relex/pp'd, but they would still have to search through a
698 // (potentially huge) series of SearchDirs to find it.
Stephen Hines651f13c2014-04-23 16:59:28 -0700699 LookupFileCacheInfo &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000700 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000701
702 // If the entry has been previously looked up, the first value will be
703 // non-zero. If the value is equal to i (the start point of our search), then
704 // this is a matching hit.
Stephen Hines651f13c2014-04-23 16:59:28 -0700705 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000706 // Skip querying potentially lots of directories for this lookup.
Stephen Hines651f13c2014-04-23 16:59:28 -0700707 i = CacheLookup.HitIdx;
708 if (CacheLookup.MappedName)
709 Filename = CacheLookup.MappedName;
Chris Lattner9960ae82007-07-22 07:28:00 +0000710 } else {
711 // Otherwise, this is the first query, or the previous query didn't match
712 // our search start. We will fill in our found location below, so prime the
713 // start point value.
Stephen Hines651f13c2014-04-23 16:59:28 -0700714 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattner9960ae82007-07-22 07:28:00 +0000715 }
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Stephen Hines651f13c2014-04-23 16:59:28 -0700717 SmallString<64> MappedName;
718
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 // Check each directory in sequence to see if it contains this file.
720 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000721 bool InUserSpecifiedSystemFramework = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700722 bool HasBeenMapped = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000723 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000724 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Stephen Hines651f13c2014-04-23 16:59:28 -0700725 SuggestedModule, InUserSpecifiedSystemFramework,
726 HasBeenMapped, MappedName);
727 if (HasBeenMapped) {
728 CacheLookup.MappedName =
729 copyString(Filename, LookupFileCache.getAllocator());
730 }
Chris Lattnerafded5b2007-12-17 08:13:48 +0000731 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattnerafded5b2007-12-17 08:13:48 +0000733 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerafded5b2007-12-17 08:13:48 +0000735 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000736 HeaderFileInfo &HFI = getFileInfo(FE);
737 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000739 // If the directory characteristic is User but this framework was
740 // user-specified to be treated as a system framework, promote the
741 // characteristic.
742 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
743 HFI.DirInfo = SrcMgr::C_System;
744
Richard Smithf122a132012-06-13 20:27:03 +0000745 // If the filename matches a known system header prefix, override
746 // whether the file is a system header.
Richard Trieu4ef2f6a2012-06-13 20:52:36 +0000747 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
748 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
749 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smithf122a132012-06-13 20:27:03 +0000750 : SrcMgr::C_User;
751 break;
752 }
753 }
754
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000755 // If this file is found in a header map and uses the framework style of
756 // includes, then this header is part of a framework we're building.
757 if (CurDir->isIndexHeaderMap()) {
758 size_t SlashPos = Filename.find('/');
759 if (SlashPos != StringRef::npos) {
760 HFI.IndexHeaderMapHeader = 1;
761 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
762 SlashPos));
763 }
764 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700765
766 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
767 if (SuggestedModule)
768 *SuggestedModule = MSSuggestedModule;
769 return MSFE;
770 }
771
Chris Lattnerafded5b2007-12-17 08:13:48 +0000772 // Remember this location for the next lookup we do.
Stephen Hines651f13c2014-04-23 16:59:28 -0700773 CacheLookup.HitIdx = i;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000774 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000777 // If we are including a file with a quoted include "foo.h" from inside
778 // a header in a framework that is currently being built, and we couldn't
779 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
780 // "Foo" is the name of the framework in which the including header was found.
Stephen Hines651f13c2014-04-23 16:59:28 -0700781 if (!Includers.empty() && !isAngled &&
782 Filename.find('/') == StringRef::npos) {
783 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front());
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000784 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000785 SmallString<128> ScratchFilename;
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000786 ScratchFilename += IncludingHFI.Framework;
787 ScratchFilename += '/';
788 ScratchFilename += Filename;
Stephen Hines651f13c2014-04-23 16:59:28 -0700789
790 const FileEntry *FE = LookupFile(
791 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
792 Includers.front(), SearchPath, RelativePath, SuggestedModule);
793
794 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
795 if (SuggestedModule)
796 *SuggestedModule = MSSuggestedModule;
797 return MSFE;
798 }
799
800 LookupFileCacheInfo &CacheLookup
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000801 = LookupFileCache.GetOrCreateValue(Filename).getValue();
Stephen Hines651f13c2014-04-23 16:59:28 -0700802 CacheLookup.HitIdx
803 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().HitIdx;
804 // FIXME: SuggestedModule.
805 return FE;
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000806 }
807 }
808
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700809 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700810 if (SuggestedModule)
811 *SuggestedModule = MSSuggestedModule;
812 return MSFE;
813 }
814
Chris Lattner9960ae82007-07-22 07:28:00 +0000815 // Otherwise, didn't find it. Remember we didn't find this.
Stephen Hines651f13c2014-04-23 16:59:28 -0700816 CacheLookup.HitIdx = SearchDirs.size();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700817 return nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000818}
819
820/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennett853519c2012-06-20 00:56:32 +0000821/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Reid Spencer5f016e22007-07-11 17:01:13 +0000822/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
823/// is a subframework within Carbon.framework. If so, return the FileEntry
824/// for the designated file, otherwise return null.
825const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000826LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000827 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000828 SmallVectorImpl<char> *SearchPath,
Douglas Gregor1b58c742013-02-08 00:10:48 +0000829 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000830 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000831 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000834 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000835 size_t SlashPos = Filename.find('/');
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700836 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 // Look up the base framework name of the ContextFileEnt.
839 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000842 const unsigned DotFrameworkLen = 10;
843 const char *FrameworkPos = strstr(ContextName, ".framework");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700844 if (FrameworkPos == nullptr ||
Douglas Gregorefda0e82011-12-09 16:48:01 +0000845 (FrameworkPos[DotFrameworkLen] != '/' &&
846 FrameworkPos[DotFrameworkLen] != '\\'))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700847 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000849 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000850
851 // Append Frameworks/HIToolbox.framework/
852 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000853 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 FrameworkName += ".framework/";
855
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000856 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000857 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 // Some other location?
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000860 if (CacheLookup.getValue().Directory &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000861 CacheLookup.getKeyLength() == FrameworkName.size() &&
862 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
863 CacheLookup.getKeyLength()) != 0)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700864 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 // Cache subframework.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700867 if (!CacheLookup.getValue().Directory) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000871 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700872 if (!Dir) return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 // Otherwise, if it does, remember that this is the right direntry for this
875 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000876 CacheLookup.getValue().Directory = Dir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 }
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700879 const FileEntry *FE = nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000880
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700881 if (RelativePath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000882 RelativePath->clear();
883 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
884 }
885
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000887 SmallString<1024> HeadersFilename(FrameworkName);
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 HeadersFilename += "Headers/";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700889 if (SearchPath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000890 SearchPath->clear();
891 // Without trailing '/'.
892 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
893 }
894
Chris Lattnera1394812010-01-10 01:35:12 +0000895 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000896 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
899 HeadersFilename = FrameworkName;
900 HeadersFilename += "PrivateHeaders/";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700901 if (SearchPath) {
Manuel Klimek74124942011-04-26 21:50:03 +0000902 SearchPath->clear();
903 // Without trailing '/'.
904 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
905 }
906
Chris Lattnera1394812010-01-10 01:35:12 +0000907 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000908 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700909 return nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000913 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000914 // Note that the temporary 'DirInfo' is required here, as either call to
915 // getFileInfo could resize the vector and we don't want to rely on order
916 // of evaluation.
917 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
918 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregor1b58c742013-02-08 00:10:48 +0000919
920 // If we're supposed to suggest a module, look for one now.
921 if (SuggestedModule) {
922 // Find the top-level framework based on this framework.
923 FrameworkName.pop_back(); // remove the trailing '/'
924 SmallVector<std::string, 4> SubmodulePath;
925 const DirectoryEntry *TopFrameworkDir
926 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
927
928 // Determine the name of the top-level framework.
929 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
930
931 // Load this framework module. If that succeeds, find the suggested module
932 // for this header, if any.
933 bool IsSystem = false;
934 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
935 *SuggestedModule = findModuleForHeader(FE);
936 }
937 }
938
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 return FE;
940}
941
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000942/// \brief Helper static function to normalize a path for injection into
943/// a synthetic header.
944/*static*/ std::string
945HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
946 // Implicit include paths should be resolved relative to the current
947 // working directory first, and then use the regular header search
948 // mechanism. The proper way to handle this is to have the
949 // predefines buffer located at the current working directory, but
950 // it has no file entry. For now, workaround this by using an
951 // absolute path if we find the file here, and otherwise letting
952 // header search handle it.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000953 SmallString<128> Path(File);
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000954 llvm::sys::fs::make_absolute(Path);
955 bool exists;
956 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
957 Path = File;
958 else if (exists)
959 FileMgr.getFile(File);
960
961 return Lexer::Stringify(Path.str());
962}
963
Reid Spencer5f016e22007-07-11 17:01:13 +0000964//===----------------------------------------------------------------------===//
965// File Info Management.
966//===----------------------------------------------------------------------===//
967
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000968/// \brief Merge the header file info provided by \p OtherHFI into the current
969/// header file info (\p HFI)
970static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
971 const HeaderFileInfo &OtherHFI) {
972 HFI.isImport |= OtherHFI.isImport;
973 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +0000974 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000975 HFI.NumIncludes += OtherHFI.NumIncludes;
976
977 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
978 HFI.ControllingMacro = OtherHFI.ControllingMacro;
979 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
980 }
981
982 if (OtherHFI.External) {
983 HFI.DirInfo = OtherHFI.DirInfo;
984 HFI.External = OtherHFI.External;
985 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
986 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000987
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000988 if (HFI.Framework.empty())
989 HFI.Framework = OtherHFI.Framework;
990
991 HFI.Resolved = true;
992}
993
Steve Naroff83d63c72009-04-24 20:03:17 +0000994/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000995/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000996HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 if (FE->getUID() >= FileInfo.size())
998 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000999
1000 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +00001001 if (ExternalSource && !HFI.Resolved)
1002 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Stephen Hines651f13c2014-04-23 16:59:28 -07001003 HFI.IsValid = 1;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001004 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +00001005}
Reid Spencer5f016e22007-07-11 17:01:13 +00001006
Stephen Hines651f13c2014-04-23 16:59:28 -07001007bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
1008 if (FE->getUID() >= FileInfo.size())
1009 return false;
1010 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1011 if (HFI.IsValid) {
1012 Result = HFI;
1013 return true;
1014 }
1015 return false;
1016}
1017
Douglas Gregordd3e5542011-05-04 00:14:37 +00001018bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1019 // Check if we've ever seen this file as a header.
1020 if (File->getUID() >= FileInfo.size())
1021 return false;
1022
1023 // Resolve header file info from the external source, if needed.
1024 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +00001025 if (ExternalSource && !HFI.Resolved)
1026 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +00001027
Argyrios Kyrtzidis44dfff62012-12-10 20:08:37 +00001028 return HFI.isPragmaOnce || HFI.isImport ||
1029 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregordd3e5542011-05-04 00:14:37 +00001030}
1031
Argyrios Kyrtzidisd3220db2013-05-08 23:46:46 +00001032void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001033 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidisd3220db2013-05-08 23:46:46 +00001034 bool isCompilingModuleHeader) {
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001035 if (FE->getUID() >= FileInfo.size())
1036 FileInfo.resize(FE->getUID()+1);
1037
1038 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1039 HFI.isModuleHeader = true;
Argyrios Kyrtzidisd3220db2013-05-08 23:46:46 +00001040 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001041 HFI.setHeaderRole(Role);
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001042}
1043
Reid Spencer5f016e22007-07-11 17:01:13 +00001044bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1045 ++NumIncluded; // Count # of attempted #includes.
1046
1047 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +00001048 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 // If this is a #import directive, check that we have not already imported
1051 // this header.
1052 if (isImport) {
1053 // If this has already been imported, don't import it again.
1054 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 // Has this already been #import'ed or #include'd?
1057 if (FileInfo.NumIncludes) return false;
1058 } else {
1059 // Otherwise, if this is a #include of a file that was previously #import'd
1060 // or if this is the second #include of a #pragma once file, ignore it.
1061 if (FileInfo.isImport)
1062 return false;
1063 }
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1066 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +00001067 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +00001068 = FileInfo.getControllingMacro(ExternalLookup))
1069 if (ControllingMacro->hasMacroDefinition()) {
1070 ++NumMultiIncludeFileOptzn;
1071 return false;
1072 }
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 // Increment the number of times this file has been included.
1075 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 return true;
1078}
1079
Ted Kremenekd1194fb2011-07-26 23:46:11 +00001080size_t HeaderSearch::getTotalMemory() const {
1081 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +00001082 + llvm::capacity_in_bytes(FileInfo)
1083 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +00001084 + LookupFileCache.getAllocator().getTotalMemory()
1085 + FrameworkMap.getAllocator().getTotalMemory();
1086}
Douglas Gregor65e02fa2011-07-28 04:45:53 +00001087
1088StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1089 return FrameworkNames.GetOrCreateValue(Framework).getKey();
1090}
Douglas Gregora30cfe52011-11-11 19:10:28 +00001091
1092bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor8f5d7d12013-06-21 16:28:10 +00001093 const DirectoryEntry *Root,
1094 bool IsSystem) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001095 if (!enabledModules())
1096 return false;
1097
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001098 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregora30cfe52011-11-11 19:10:28 +00001099
1100 StringRef DirName = FileName;
1101 do {
1102 // Get the parent directory name.
1103 DirName = llvm::sys::path::parent_path(DirName);
1104 if (DirName.empty())
1105 return false;
Daniel Jasper1b8840c2013-09-24 09:27:13 +00001106
Douglas Gregora30cfe52011-11-11 19:10:28 +00001107 // Determine whether this directory exists.
1108 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1109 if (!Dir)
1110 return false;
Daniel Jasper1b8840c2013-09-24 09:27:13 +00001111
Stephen Hines651f13c2014-04-23 16:59:28 -07001112 // Try to load the module map file in this directory.
1113 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/false)) {
Douglas Gregor26697972011-11-12 00:22:19 +00001114 case LMM_NewlyLoaded:
1115 case LMM_AlreadyLoaded:
Daniel Jasper1b8840c2013-09-24 09:27:13 +00001116 // Success. All of the directories we stepped through inherit this module
1117 // map file.
1118 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1119 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1120 return true;
Daniel Jasperc6417092013-10-22 08:09:47 +00001121
1122 case LMM_NoDirectory:
1123 case LMM_InvalidModuleMap:
1124 break;
Daniel Jasper1b8840c2013-09-24 09:27:13 +00001125 }
1126
Douglas Gregorcf70d782011-11-12 00:05:07 +00001127 // If we hit the top of our search, we're done.
1128 if (Dir == Root)
1129 return false;
1130
Douglas Gregora30cfe52011-11-11 19:10:28 +00001131 // Keep track of all of the directories we checked, so we can mark them as
1132 // having module maps if we eventually do find a module map.
1133 FixUpDirectories.push_back(Dir);
1134 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +00001135}
1136
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001137ModuleMap::KnownHeader
1138HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001139 if (ExternalSource) {
1140 // Make sure the external source has handled header info about this file,
1141 // which includes whether the file is part of a module.
1142 (void)getFileInfo(File);
1143 }
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001144 return ModMap.findModuleForHeader(File);
Douglas Gregora30cfe52011-11-11 19:10:28 +00001145}
1146
Stephen Hines651f13c2014-04-23 16:59:28 -07001147static const FileEntry *getPrivateModuleMap(StringRef ModuleMapPath,
1148 const DirectoryEntry *Directory,
1149 FileManager &FileMgr) {
1150 StringRef Filename = llvm::sys::path::filename(ModuleMapPath);
1151 SmallString<128> PrivateFilename(Directory->getName());
1152 if (Filename == "module.map")
Douglas Gregor4813442c2011-12-07 21:25:07 +00001153 llvm::sys::path::append(PrivateFilename, "module_private.map");
Stephen Hines651f13c2014-04-23 16:59:28 -07001154 else if (Filename == "module.modulemap")
1155 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1156 else
1157 return nullptr;
1158 return FileMgr.getFile(PrivateFilename);
Douglas Gregordb1cde72011-11-16 00:09:06 +00001159}
1160
Stephen Hines651f13c2014-04-23 16:59:28 -07001161bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1162 switch (loadModuleMapFileImpl(File, IsSystem)) {
1163 case LMM_AlreadyLoaded:
1164 case LMM_NewlyLoaded:
1165 return false;
1166 case LMM_NoDirectory:
1167 case LMM_InvalidModuleMap:
1168 return true;
1169 }
1170 llvm_unreachable("Unknown load module map result");
1171}
1172
1173HeaderSearch::LoadModuleMapResult
1174HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem) {
1175 assert(File && "expected FileEntry");
1176
1177 const DirectoryEntry *Dir = File->getDir();
1178 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1179 if (KnownDir != DirectoryHasModuleMap.end())
1180 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1181
1182 if (ModMap.parseModuleMapFile(File, IsSystem)) {
1183 DirectoryHasModuleMap[Dir] = false;
1184 return LMM_InvalidModuleMap;
1185 }
1186
1187 // Try to load a corresponding private module map.
1188 if (const FileEntry *PMMFile =
1189 getPrivateModuleMap(File->getName(), Dir, FileMgr)) {
1190 if (ModMap.parseModuleMapFile(PMMFile, IsSystem)) {
1191 DirectoryHasModuleMap[Dir] = false;
1192 return LMM_InvalidModuleMap;
1193 }
1194 }
1195
1196 // This directory has a module map.
1197 DirectoryHasModuleMap[Dir] = true;
1198 return LMM_NewlyLoaded;
1199}
1200
1201const FileEntry *
1202HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1203 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1204 // module.map at the framework root is also accepted.
1205 SmallString<128> ModuleMapFileName(Dir->getName());
1206 if (IsFramework)
1207 llvm::sys::path::append(ModuleMapFileName, "Modules");
1208 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1209 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1210 return F;
1211
1212 // Continue to allow module.map
1213 ModuleMapFileName = Dir->getName();
1214 llvm::sys::path::append(ModuleMapFileName, "module.map");
1215 return FileMgr.getFile(ModuleMapFileName);
1216}
1217
1218Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregore434ec72012-01-29 17:08:11 +00001219 const DirectoryEntry *Dir,
1220 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001221 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001222 return Module;
1223
1224 // Try to load a module map file.
Stephen Hines651f13c2014-04-23 16:59:28 -07001225 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001226 case LMM_InvalidModuleMap:
1227 break;
1228
1229 case LMM_AlreadyLoaded:
1230 case LMM_NoDirectory:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001231 return nullptr;
1232
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001233 case LMM_NewlyLoaded:
1234 return ModMap.findModule(Name);
1235 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +00001236
Douglas Gregor82e52372012-11-06 19:39:40 +00001237
Stephen Hines651f13c2014-04-23 16:59:28 -07001238 // Try to infer a module map from the framework directory.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001239 return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001240}
1241
Douglas Gregordb1cde72011-11-16 00:09:06 +00001242
Douglas Gregor26697972011-11-12 00:22:19 +00001243HeaderSearch::LoadModuleMapResult
Stephen Hines651f13c2014-04-23 16:59:28 -07001244HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1245 bool IsFramework) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001246 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Stephen Hines651f13c2014-04-23 16:59:28 -07001247 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregorcf70d782011-11-12 00:05:07 +00001248
Douglas Gregor26697972011-11-12 00:22:19 +00001249 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001250}
1251
Douglas Gregor26697972011-11-12 00:22:19 +00001252HeaderSearch::LoadModuleMapResult
Stephen Hines651f13c2014-04-23 16:59:28 -07001253HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1254 bool IsFramework) {
1255 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregorcf70d782011-11-12 00:05:07 +00001256 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +00001257 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregor587986e2011-12-07 02:23:45 +00001258
Stephen Hines651f13c2014-04-23 16:59:28 -07001259 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1260 LoadModuleMapResult Result = loadModuleMapFileImpl(ModuleMapFile, IsSystem);
1261 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1262 // E.g. Foo.framework/Modules/module.modulemap
1263 // ^Dir ^ModuleMapFile
1264 if (Result == LMM_NewlyLoaded)
1265 DirectoryHasModuleMap[Dir] = true;
1266 return Result;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001267 }
Douglas Gregor26697972011-11-12 00:22:19 +00001268 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001269}
Douglas Gregora30cfe52011-11-11 19:10:28 +00001270
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001271void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001272 Modules.clear();
1273
1274 // Load module maps for each of the header search directories.
1275 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor8f5d7d12013-06-21 16:28:10 +00001276 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001277 if (SearchDirs[Idx].isFramework()) {
1278 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001279 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001280 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1281 DirNative);
1282
1283 // Search each of the ".framework" directories to load them as modules.
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001284 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1285 Dir != DirEnd && !EC; Dir.increment(EC)) {
1286 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1287 continue;
1288
1289 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1290 if (!FrameworkDir)
1291 continue;
1292
1293 // Load this framework module.
1294 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1295 IsSystem);
1296 }
1297 continue;
1298 }
1299
1300 // FIXME: Deal with header maps.
1301 if (SearchDirs[Idx].isHeaderMap())
1302 continue;
1303
1304 // Try to load a module map file for the search directory.
Stephen Hines651f13c2014-04-23 16:59:28 -07001305 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, /*IsFramework*/false);
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001306
1307 // Try to load module map files for immediate subdirectories of this search
1308 // directory.
Douglas Gregorcdf28082013-03-21 01:08:50 +00001309 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001310 }
1311
1312 // Populate the list of modules.
1313 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1314 MEnd = ModMap.module_end();
1315 M != MEnd; ++M) {
1316 Modules.push_back(M->getValue());
1317 }
1318}
Douglas Gregorcdf28082013-03-21 01:08:50 +00001319
Douglas Gregor30a16f12013-05-10 22:52:27 +00001320void HeaderSearch::loadTopLevelSystemModules() {
1321 // Load module maps for each of the header search directories.
1322 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor701bc8c2013-11-01 23:08:38 +00001323 // We only care about normal header directories.
1324 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor30a16f12013-05-10 22:52:27 +00001325 continue;
1326 }
1327
1328 // Try to load a module map file for the search directory.
Douglas Gregor8f5d7d12013-06-21 16:28:10 +00001329 loadModuleMapFile(SearchDirs[Idx].getDir(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001330 SearchDirs[Idx].isSystemHeaderDirectory(),
1331 SearchDirs[Idx].isFramework());
Douglas Gregor30a16f12013-05-10 22:52:27 +00001332 }
1333}
1334
Douglas Gregorcdf28082013-03-21 01:08:50 +00001335void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1336 if (SearchDir.haveSearchedAllModuleMaps())
1337 return;
1338
1339 llvm::error_code EC;
1340 SmallString<128> DirNative;
1341 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1342 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1343 Dir != DirEnd && !EC; Dir.increment(EC)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001344 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1345 SearchDir.isFramework());
Douglas Gregorcdf28082013-03-21 01:08:50 +00001346 }
1347
1348 SearchDir.setSearchedAllModuleMaps(true);
1349}