clang  14.0.0git
HeaderSearch.cpp
Go to the documentation of this file.
1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the DirectoryLookup and HeaderSearch interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Lex/HeaderSearch.h"
14 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/Module.h"
21 #include "clang/Lex/HeaderMap.h"
24 #include "clang/Lex/ModuleMap.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/Hashing.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/Capacity.h"
34 #include "llvm/Support/Errc.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/VirtualFileSystem.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstddef>
42 #include <cstdio>
43 #include <cstring>
44 #include <string>
45 #include <system_error>
46 #include <utility>
47 
48 using namespace clang;
49 
50 #define DEBUG_TYPE "file-search"
51 
52 ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");
54  NumMultiIncludeFileOptzn,
55  "Number of #includes skipped due to the multi-include optimization.");
56 ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");
57 ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,
58  "Number of subframework lookups.");
59 
60 const IdentifierInfo *
62  if (ControllingMacro) {
64  assert(External && "We must have an external source if we have a "
65  "controlling macro that is out of date.");
66  External->updateOutOfDateIdentifier(
67  *const_cast<IdentifierInfo *>(ControllingMacro));
68  }
69  return ControllingMacro;
70  }
71 
73  return nullptr;
74 
76  return ControllingMacro;
77 }
78 
80 
81 HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
82  SourceManager &SourceMgr, DiagnosticsEngine &Diags,
83  const LangOptions &LangOpts,
84  const TargetInfo *Target)
85  : HSOpts(std::move(HSOpts)), Diags(Diags),
86  FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
87  ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
88 
90  llvm::errs() << "\n*** HeaderSearch Stats:\n"
91  << FileInfo.size() << " files tracked.\n";
92  unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
93  for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
94  NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport);
95  if (MaxNumIncludes < FileInfo[i].NumIncludes)
96  MaxNumIncludes = FileInfo[i].NumIncludes;
97  NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
98  }
99  llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n"
100  << " " << NumSingleIncludedFiles << " included exactly once.\n"
101  << " " << MaxNumIncludes << " max times a file is included.\n";
102 
103  llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n"
104  << " " << NumMultiIncludeFileOptzn
105  << " #includes skipped due to the multi-include optimization.\n";
106 
107  llvm::errs() << NumFrameworkLookups << " framework lookups.\n"
108  << NumSubFrameworkLookups << " subframework lookups.\n";
109 }
110 
111 std::vector<bool> HeaderSearch::computeUserEntryUsage() const {
112  std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());
113  for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {
114  // Check whether this DirectoryLookup has been successfully used.
115  if (SearchDirsUsage[I]) {
116  auto UserEntryIdxIt = SearchDirToHSEntry.find(I);
117  // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
118  if (UserEntryIdxIt != SearchDirToHSEntry.end())
119  UserEntryUsage[UserEntryIdxIt->second] = true;
120  }
121  }
122  return UserEntryUsage;
123 }
124 
125 /// CreateHeaderMap - This method returns a HeaderMap for the specified
126 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
128  // We expect the number of headermaps to be small, and almost always empty.
129  // If it ever grows, use of a linear search should be re-evaluated.
130  if (!HeaderMaps.empty()) {
131  for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
132  // Pointer equality comparison of FileEntries works because they are
133  // already uniqued by inode.
134  if (HeaderMaps[i].first == FE)
135  return HeaderMaps[i].second.get();
136  }
137 
138  if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
139  HeaderMaps.emplace_back(FE, std::move(HM));
140  return HeaderMaps.back().second.get();
141  }
142 
143  return nullptr;
144 }
145 
146 /// Get filenames for all registered header maps.
148  SmallVectorImpl<std::string> &Names) const {
149  for (auto &HM : HeaderMaps)
150  Names.push_back(std::string(HM.first->getName()));
151 }
152 
154  const FileEntry *ModuleMap =
156  return getCachedModuleFileName(Module->Name, ModuleMap->getName());
157 }
158 
160  bool FileMapOnly) {
161  // First check the module name to pcm file map.
162  auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
163  if (i != HSOpts->PrebuiltModuleFiles.end())
164  return i->second;
165 
166  if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
167  return {};
168 
169  // Then go through each prebuilt module directory and try to find the pcm
170  // file.
171  for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
172  SmallString<256> Result(Dir);
173  llvm::sys::fs::make_absolute(Result);
174  llvm::sys::path::append(Result, ModuleName + ".pcm");
175  if (getFileMgr().getFile(Result.str()))
176  return std::string(Result);
177  }
178  return {};
179 }
180 
182  const FileEntry *ModuleMap =
184  StringRef ModuleName = Module->Name;
185  StringRef ModuleMapPath = ModuleMap->getName();
186  StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();
187  for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
188  SmallString<256> CachePath(Dir);
189  llvm::sys::fs::make_absolute(CachePath);
190  llvm::sys::path::append(CachePath, ModuleCacheHash);
191  std::string FileName =
192  getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);
193  if (!FileName.empty() && getFileMgr().getFile(FileName))
194  return FileName;
195  }
196  return {};
197 }
198 
200  StringRef ModuleMapPath) {
201  return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,
203 }
204 
205 std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,
206  StringRef ModuleMapPath,
207  StringRef CachePath) {
208  // If we don't have a module cache path or aren't supposed to use one, we
209  // can't do anything.
210  if (CachePath.empty())
211  return {};
212 
213  SmallString<256> Result(CachePath);
214  llvm::sys::fs::make_absolute(Result);
215 
216  if (HSOpts->DisableModuleHash) {
217  llvm::sys::path::append(Result, ModuleName + ".pcm");
218  } else {
219  // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
220  // ideally be globally unique to this particular module. Name collisions
221  // in the hash are safe (because any translation unit can only import one
222  // module with each name), but result in a loss of caching.
223  //
224  // To avoid false-negatives, we form as canonical a path as we can, and map
225  // to lower-case in case we're on a case-insensitive file system.
227  std::string(llvm::sys::path::parent_path(ModuleMapPath));
228  if (Parent.empty())
229  Parent = ".";
230  auto Dir = FileMgr.getDirectory(Parent);
231  if (!Dir)
232  return {};
233  auto DirName = FileMgr.getCanonicalName(*Dir);
234  auto FileName = llvm::sys::path::filename(ModuleMapPath);
235 
236  llvm::hash_code Hash =
237  llvm::hash_combine(DirName.lower(), FileName.lower());
238 
239  SmallString<128> HashStr;
240  llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
241  llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
242  }
243  return Result.str().str();
244 }
245 
246 Module *HeaderSearch::lookupModule(StringRef ModuleName,
247  SourceLocation ImportLoc, bool AllowSearch,
248  bool AllowExtraModuleMapSearch) {
249  // Look in the module map to determine if there is a module by this name.
250  Module *Module = ModMap.findModule(ModuleName);
251  if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
252  return Module;
253 
254  StringRef SearchName = ModuleName;
255  Module = lookupModule(ModuleName, SearchName, ImportLoc,
256  AllowExtraModuleMapSearch);
257 
258  // The facility for "private modules" -- adjacent, optional module maps named
259  // module.private.modulemap that are supposed to define private submodules --
260  // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
261  //
262  // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
263  // should also rename to Foo_Private. Representing private as submodules
264  // could force building unwanted dependencies into the parent module and cause
265  // dependency cycles.
266  if (!Module && SearchName.consume_back("_Private"))
267  Module = lookupModule(ModuleName, SearchName, ImportLoc,
268  AllowExtraModuleMapSearch);
269  if (!Module && SearchName.consume_back("Private"))
270  Module = lookupModule(ModuleName, SearchName, ImportLoc,
271  AllowExtraModuleMapSearch);
272  return Module;
273 }
274 
275 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
276  SourceLocation ImportLoc,
277  bool AllowExtraModuleMapSearch) {
278  Module *Module = nullptr;
279  unsigned Idx;
280 
281  // Look through the various header search paths to load any available module
282  // maps, searching for a module map that describes this module.
283  for (Idx = 0; Idx != SearchDirs.size(); ++Idx) {
284  if (SearchDirs[Idx].isFramework()) {
285  // Search for or infer a module map for a framework. Here we use
286  // SearchName rather than ModuleName, to permit finding private modules
287  // named FooPrivate in buggy frameworks named Foo.
288  SmallString<128> FrameworkDirName;
289  FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
290  llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
291  if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) {
292  bool IsSystem
293  = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
294  Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
295  if (Module)
296  break;
297  }
298  }
299 
300  // FIXME: Figure out how header maps and module maps will work together.
301 
302  // Only deal with normal search directories.
303  if (!SearchDirs[Idx].isNormalDir())
304  continue;
305 
306  bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
307  // Search for a module map file in this directory.
308  if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
309  /*IsFramework*/false) == LMM_NewlyLoaded) {
310  // We just loaded a module map file; check whether the module is
311  // available now.
312  Module = ModMap.findModule(ModuleName);
313  if (Module)
314  break;
315  }
316 
317  // Search for a module map in a subdirectory with the same name as the
318  // module.
319  SmallString<128> NestedModuleMapDirName;
320  NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
321  llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
322  if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
323  /*IsFramework*/false) == LMM_NewlyLoaded){
324  // If we just loaded a module map file, look for the module again.
325  Module = ModMap.findModule(ModuleName);
326  if (Module)
327  break;
328  }
329 
330  // If we've already performed the exhaustive search for module maps in this
331  // search directory, don't do it again.
332  if (SearchDirs[Idx].haveSearchedAllModuleMaps())
333  continue;
334 
335  // Load all module maps in the immediate subdirectories of this search
336  // directory if ModuleName was from @import.
337  if (AllowExtraModuleMapSearch)
338  loadSubdirectoryModuleMaps(SearchDirs[Idx]);
339 
340  // Look again for the module.
341  Module = ModMap.findModule(ModuleName);
342  if (Module)
343  break;
344  }
345 
346  if (Module)
347  noteLookupUsage(Idx, ImportLoc);
348 
349  return Module;
350 }
351 
352 //===----------------------------------------------------------------------===//
353 // File lookup within a DirectoryLookup scope
354 //===----------------------------------------------------------------------===//
355 
356 /// getName - Return the directory or filename corresponding to this lookup
357 /// object.
358 StringRef DirectoryLookup::getName() const {
359  // FIXME: Use the name from \c DirectoryEntryRef.
360  if (isNormalDir())
361  return getDir()->getName();
362  if (isFramework())
363  return getFrameworkDir()->getName();
364  assert(isHeaderMap() && "Unknown DirectoryLookup");
365  return getHeaderMap()->getFileName();
366 }
367 
368 Optional<FileEntryRef> HeaderSearch::getFileAndSuggestModule(
369  StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
370  bool IsSystemHeaderDir, Module *RequestingModule,
371  ModuleMap::KnownHeader *SuggestedModule) {
372  // If we have a module map that might map this header, load it and
373  // check whether we'll have a suggestion for a module.
374  auto File = getFileMgr().getFileRef(FileName, /*OpenFile=*/true);
375  if (!File) {
376  // For rare, surprising errors (e.g. "out of file handles"), diag the EC
377  // message.
378  std::error_code EC = llvm::errorToErrorCode(File.takeError());
379  if (EC != llvm::errc::no_such_file_or_directory &&
380  EC != llvm::errc::invalid_argument &&
381  EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
382  Diags.Report(IncludeLoc, diag::err_cannot_open_file)
383  << FileName << EC.message();
384  }
385  return None;
386  }
387 
388  // If there is a module that corresponds to this header, suggest it.
389  if (!findUsableModuleForHeader(
390  &File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(),
391  RequestingModule, SuggestedModule, IsSystemHeaderDir))
392  return None;
393 
394  return *File;
395 }
396 
397 /// LookupFile - Lookup the specified file in this search path, returning it
398 /// if it exists or returning null if not.
400  StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
401  SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
402  Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
403  bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
404  bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName) const {
405  InUserSpecifiedSystemFramework = false;
406  IsInHeaderMap = false;
407  MappedName.clear();
408 
409  SmallString<1024> TmpDir;
410  if (isNormalDir()) {
411  // Concatenate the requested file onto the directory.
412  TmpDir = getDir()->getName();
413  llvm::sys::path::append(TmpDir, Filename);
414  if (SearchPath) {
415  StringRef SearchPathRef(getDir()->getName());
416  SearchPath->clear();
417  SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
418  }
419  if (RelativePath) {
420  RelativePath->clear();
421  RelativePath->append(Filename.begin(), Filename.end());
422  }
423 
424  return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
426  RequestingModule, SuggestedModule);
427  }
428 
429  if (isFramework())
430  return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
431  RequestingModule, SuggestedModule,
432  InUserSpecifiedSystemFramework, IsFrameworkFound);
433 
434  assert(isHeaderMap() && "Unknown directory lookup");
435  const HeaderMap *HM = getHeaderMap();
436  SmallString<1024> Path;
437  StringRef Dest = HM->lookupFilename(Filename, Path);
438  if (Dest.empty())
439  return None;
440 
441  IsInHeaderMap = true;
442 
443  auto FixupSearchPath = [&]() {
444  if (SearchPath) {
445  StringRef SearchPathRef(getName());
446  SearchPath->clear();
447  SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
448  }
449  if (RelativePath) {
450  RelativePath->clear();
451  RelativePath->append(Filename.begin(), Filename.end());
452  }
453  };
454 
455  // Check if the headermap maps the filename to a framework include
456  // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
457  // framework include.
458  if (llvm::sys::path::is_relative(Dest)) {
459  MappedName.append(Dest.begin(), Dest.end());
460  Filename = StringRef(MappedName.begin(), MappedName.size());
461  Dest = HM->lookupFilename(Filename, Path);
462  }
463 
464  if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest)) {
465  FixupSearchPath();
466  return *Res;
467  }
468 
469  // Header maps need to be marked as used whenever the filename matches.
470  // The case where the target file **exists** is handled by callee of this
471  // function as part of the regular logic that applies to include search paths.
472  // The case where the target file **does not exist** is handled here:
473  HS.noteLookupUsage(*HS.searchDirIdx(*this), IncludeLoc);
474  return None;
475 }
476 
477 /// Given a framework directory, find the top-most framework directory.
478 ///
479 /// \param FileMgr The file manager to use for directory lookups.
480 /// \param DirName The name of the framework directory.
481 /// \param SubmodulePath Will be populated with the submodule path from the
482 /// returned top-level module to the originally named framework.
483 static const DirectoryEntry *
484 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
485  SmallVectorImpl<std::string> &SubmodulePath) {
486  assert(llvm::sys::path::extension(DirName) == ".framework" &&
487  "Not a framework directory");
488 
489  // Note: as an egregious but useful hack we use the real path here, because
490  // frameworks moving between top-level frameworks to embedded frameworks tend
491  // to be symlinked, and we base the logical structure of modules on the
492  // physical layout. In particular, we need to deal with crazy includes like
493  //
494  // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
495  //
496  // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
497  // which one should access with, e.g.,
498  //
499  // #include <Bar/Wibble.h>
500  //
501  // Similar issues occur when a top-level framework has moved into an
502  // embedded framework.
503  const DirectoryEntry *TopFrameworkDir = nullptr;
504  if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName))
505  TopFrameworkDir = *TopFrameworkDirOrErr;
506 
507  if (TopFrameworkDir)
508  DirName = FileMgr.getCanonicalName(TopFrameworkDir);
509  do {
510  // Get the parent directory name.
511  DirName = llvm::sys::path::parent_path(DirName);
512  if (DirName.empty())
513  break;
514 
515  // Determine whether this directory exists.
516  auto Dir = FileMgr.getDirectory(DirName);
517  if (!Dir)
518  break;
519 
520  // If this is a framework directory, then we're a subframework of this
521  // framework.
522  if (llvm::sys::path::extension(DirName) == ".framework") {
523  SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
524  TopFrameworkDir = *Dir;
525  }
526  } while (true);
527 
528  return TopFrameworkDir;
529 }
530 
531 static bool needModuleLookup(Module *RequestingModule,
532  bool HasSuggestedModule) {
533  return HasSuggestedModule ||
534  (RequestingModule && RequestingModule->NoUndeclaredIncludes);
535 }
536 
537 /// DoFrameworkLookup - Do a lookup of the specified file in the current
538 /// DirectoryLookup, which is a framework directory.
539 Optional<FileEntryRef> DirectoryLookup::DoFrameworkLookup(
540  StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
541  SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
542  ModuleMap::KnownHeader *SuggestedModule,
543  bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
544  FileManager &FileMgr = HS.getFileMgr();
545 
546  // Framework names must have a '/' in the filename.
547  size_t SlashPos = Filename.find('/');
548  if (SlashPos == StringRef::npos)
549  return None;
550 
551  // Find out if this is the home for the specified framework, by checking
552  // HeaderSearch. Possible answers are yes/no and unknown.
553  FrameworkCacheEntry &CacheEntry =
554  HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
555 
556  // If it is known and in some other directory, fail.
557  if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
558  return None;
559 
560  // Otherwise, construct the path to this framework dir.
561 
562  // FrameworkName = "/System/Library/Frameworks/"
563  SmallString<1024> FrameworkName;
564  FrameworkName += getFrameworkDirRef()->getName();
565  if (FrameworkName.empty() || FrameworkName.back() != '/')
566  FrameworkName.push_back('/');
567 
568  // FrameworkName = "/System/Library/Frameworks/Cocoa"
569  StringRef ModuleName(Filename.begin(), SlashPos);
570  FrameworkName += ModuleName;
571 
572  // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
573  FrameworkName += ".framework/";
574 
575  // If the cache entry was unresolved, populate it now.
576  if (!CacheEntry.Directory) {
577  ++NumFrameworkLookups;
578 
579  // If the framework dir doesn't exist, we fail.
580  auto Dir = FileMgr.getDirectory(FrameworkName);
581  if (!Dir)
582  return None;
583 
584  // Otherwise, if it does, remember that this is the right direntry for this
585  // framework.
586  CacheEntry.Directory = getFrameworkDir();
587 
588  // If this is a user search directory, check if the framework has been
589  // user-specified as a system framework.
591  SmallString<1024> SystemFrameworkMarker(FrameworkName);
592  SystemFrameworkMarker += ".system_framework";
593  if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
594  CacheEntry.IsUserSpecifiedSystemFramework = true;
595  }
596  }
597  }
598 
599  // Set out flags.
600  InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
601  IsFrameworkFound = CacheEntry.Directory;
602 
603  if (RelativePath) {
604  RelativePath->clear();
605  RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
606  }
607 
608  // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
609  unsigned OrigSize = FrameworkName.size();
610 
611  FrameworkName += "Headers/";
612 
613  if (SearchPath) {
614  SearchPath->clear();
615  // Without trailing '/'.
616  SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
617  }
618 
619  FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
620 
621  auto File =
622  FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
623  if (!File) {
624  // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
625  const char *Private = "Private";
626  FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
627  Private+strlen(Private));
628  if (SearchPath)
629  SearchPath->insert(SearchPath->begin()+OrigSize, Private,
630  Private+strlen(Private));
631 
632  File = FileMgr.getOptionalFileRef(FrameworkName,
633  /*OpenFile=*/!SuggestedModule);
634  }
635 
636  // If we found the header and are allowed to suggest a module, do so now.
637  if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
638  // Find the framework in which this header occurs.
639  StringRef FrameworkPath = File->getFileEntry().getDir()->getName();
640  bool FoundFramework = false;
641  do {
642  // Determine whether this directory exists.
643  auto Dir = FileMgr.getDirectory(FrameworkPath);
644  if (!Dir)
645  break;
646 
647  // If this is a framework directory, then we're a subframework of this
648  // framework.
649  if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
650  FoundFramework = true;
651  break;
652  }
653 
654  // Get the parent directory name.
655  FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
656  if (FrameworkPath.empty())
657  break;
658  } while (true);
659 
660  bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
661  if (FoundFramework) {
662  if (!HS.findUsableModuleForFrameworkHeader(
663  &File->getFileEntry(), FrameworkPath, RequestingModule,
664  SuggestedModule, IsSystem))
665  return None;
666  } else {
667  if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(),
668  RequestingModule, SuggestedModule,
669  IsSystem))
670  return None;
671  }
672  }
673  if (File)
674  return *File;
675  return None;
676 }
677 
678 void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
679  unsigned HitIdx, SourceLocation Loc) {
680  CacheLookup.HitIdx = HitIdx;
681  noteLookupUsage(HitIdx, Loc);
682 }
683 
684 void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {
685  SearchDirsUsage[HitIdx] = true;
686 
687  auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);
688  if (UserEntryIdxIt != SearchDirToHSEntry.end())
689  Diags.Report(Loc, diag::remark_pp_search_path_usage)
690  << HSOpts->UserEntries[UserEntryIdxIt->second].Path;
691 }
692 
693 void HeaderSearch::setTarget(const TargetInfo &Target) {
694  ModMap.setTarget(Target);
695 }
696 
697 //===----------------------------------------------------------------------===//
698 // Header File Location.
699 //===----------------------------------------------------------------------===//
700 
701 /// Return true with a diagnostic if the file that MSVC would have found
702 /// fails to match the one that Clang would have found with MSVC header search
703 /// disabled.
705  const FileEntry *MSFE, const FileEntry *FE,
706  SourceLocation IncludeLoc) {
707  if (MSFE && FE != MSFE) {
708  Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
709  return true;
710  }
711  return false;
712 }
713 
714 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
715  assert(!Str.empty());
716  char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
717  std::copy(Str.begin(), Str.end(), CopyStr);
718  CopyStr[Str.size()] = '\0';
719  return CopyStr;
720 }
721 
722 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
723  SmallVectorImpl<char> &FrameworkName) {
724  using namespace llvm::sys;
725  path::const_iterator I = path::begin(Path);
726  path::const_iterator E = path::end(Path);
727  IsPrivateHeader = false;
728 
729  // Detect different types of framework style paths:
730  //
731  // ...Foo.framework/{Headers,PrivateHeaders}
732  // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
733  // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
734  // ...<other variations with 'Versions' like in the above path>
735  //
736  // and some other variations among these lines.
737  int FoundComp = 0;
738  while (I != E) {
739  if (*I == "Headers")
740  ++FoundComp;
741  if (I->endswith(".framework")) {
742  FrameworkName.append(I->begin(), I->end());
743  ++FoundComp;
744  }
745  if (*I == "PrivateHeaders") {
746  ++FoundComp;
747  IsPrivateHeader = true;
748  }
749  ++I;
750  }
751 
752  return !FrameworkName.empty() && FoundComp >= 2;
753 }
754 
755 static void
757  StringRef Includer, StringRef IncludeFilename,
758  const FileEntry *IncludeFE, bool isAngled = false,
759  bool FoundByHeaderMap = false) {
760  bool IsIncluderPrivateHeader = false;
761  SmallString<128> FromFramework, ToFramework;
762  if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework))
763  return;
764  bool IsIncludeePrivateHeader = false;
765  bool IsIncludeeInFramework = isFrameworkStylePath(
766  IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
767 
768  if (!isAngled && !FoundByHeaderMap) {
769  SmallString<128> NewInclude("<");
770  if (IsIncludeeInFramework) {
771  NewInclude += ToFramework.str().drop_back(10); // drop .framework
772  NewInclude += "/";
773  }
774  NewInclude += IncludeFilename;
775  NewInclude += ">";
776  Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
777  << IncludeFilename
778  << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
779  }
780 
781  // Headers in Foo.framework/Headers should not include headers
782  // from Foo.framework/PrivateHeaders, since this violates public/private
783  // API boundaries and can cause modular dependency cycles.
784  if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
785  IsIncludeePrivateHeader && FromFramework == ToFramework)
786  Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
787  << IncludeFilename;
788 }
789 
790 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
791 /// return null on failure. isAngled indicates whether the file reference is
792 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
793 /// non-empty, indicates where the \#including file(s) are, in case a relative
794 /// search is needed. Microsoft mode will pass all \#including files.
796  StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
797  const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
798  ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
799  SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
800  Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
801  bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
802  bool BuildSystemModule) {
803  if (IsMapped)
804  *IsMapped = false;
805 
806  if (IsFrameworkFound)
807  *IsFrameworkFound = false;
808 
809  if (SuggestedModule)
810  *SuggestedModule = ModuleMap::KnownHeader();
811 
812  // If 'Filename' is absolute, check to see if it exists and no searching.
813  if (llvm::sys::path::is_absolute(Filename)) {
814  CurDir = nullptr;
815 
816  // If this was an #include_next "/absolute/file", fail.
817  if (FromDir)
818  return None;
819 
820  if (SearchPath)
821  SearchPath->clear();
822  if (RelativePath) {
823  RelativePath->clear();
824  RelativePath->append(Filename.begin(), Filename.end());
825  }
826  // Otherwise, just return the file.
827  return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
828  /*IsSystemHeaderDir*/false,
829  RequestingModule, SuggestedModule);
830  }
831 
832  // This is the header that MSVC's header search would have found.
833  ModuleMap::KnownHeader MSSuggestedModule;
835 
836  // Unless disabled, check to see if the file is in the #includer's
837  // directory. This cannot be based on CurDir, because each includer could be
838  // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
839  // include of "baz.h" should resolve to "whatever/foo/baz.h".
840  // This search is not done for <> headers.
841  if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
842  SmallString<1024> TmpDir;
843  bool First = true;
844  for (const auto &IncluderAndDir : Includers) {
845  const FileEntry *Includer = IncluderAndDir.first;
846 
847  // Concatenate the requested file onto the directory.
848  // FIXME: Portability. Filename concatenation should be in sys::Path.
849  TmpDir = IncluderAndDir.second->getName();
850  TmpDir.push_back('/');
851  TmpDir.append(Filename.begin(), Filename.end());
852 
853  // FIXME: We don't cache the result of getFileInfo across the call to
854  // getFileAndSuggestModule, because it's a reference to an element of
855  // a container that could be reallocated across this call.
856  //
857  // If we have no includer, that means we're processing a #include
858  // from a module build. We should treat this as a system header if we're
859  // building a [system] module.
860  bool IncluderIsSystemHeader =
861  Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
862  BuildSystemModule;
863  if (Optional<FileEntryRef> FE = getFileAndSuggestModule(
864  TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
865  RequestingModule, SuggestedModule)) {
866  if (!Includer) {
867  assert(First && "only first includer can have no file");
868  return FE;
869  }
870 
871  // Leave CurDir unset.
872  // This file is a system header or C++ unfriendly if the old file is.
873  //
874  // Note that we only use one of FromHFI/ToHFI at once, due to potential
875  // reallocation of the underlying vector potentially making the first
876  // reference binding dangling.
877  HeaderFileInfo &FromHFI = getFileInfo(Includer);
878  unsigned DirInfo = FromHFI.DirInfo;
879  bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
880  StringRef Framework = FromHFI.Framework;
881 
882  HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry());
883  ToHFI.DirInfo = DirInfo;
884  ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
885  ToHFI.Framework = Framework;
886 
887  if (SearchPath) {
888  StringRef SearchPathRef(IncluderAndDir.second->getName());
889  SearchPath->clear();
890  SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
891  }
892  if (RelativePath) {
893  RelativePath->clear();
894  RelativePath->append(Filename.begin(), Filename.end());
895  }
896  if (First) {
897  diagnoseFrameworkInclude(Diags, IncludeLoc,
898  IncluderAndDir.second->getName(), Filename,
899  &FE->getFileEntry());
900  return FE;
901  }
902 
903  // Otherwise, we found the path via MSVC header search rules. If
904  // -Wmsvc-include is enabled, we have to keep searching to see if we
905  // would've found this header in -I or -isystem directories.
906  if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
907  return FE;
908  } else {
909  MSFE = FE;
910  if (SuggestedModule) {
911  MSSuggestedModule = *SuggestedModule;
912  *SuggestedModule = ModuleMap::KnownHeader();
913  }
914  break;
915  }
916  }
917  First = false;
918  }
919  }
920 
921  CurDir = nullptr;
922 
923  // If this is a system #include, ignore the user #include locs.
924  unsigned i = isAngled ? AngledDirIdx : 0;
925 
926  // If this is a #include_next request, start searching after the directory the
927  // file was found in.
928  if (FromDir)
929  i = FromDir-&SearchDirs[0];
930 
931  // Cache all of the lookups performed by this method. Many headers are
932  // multiply included, and the "pragma once" optimization prevents them from
933  // being relex/pp'd, but they would still have to search through a
934  // (potentially huge) series of SearchDirs to find it.
935  LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
936 
937  // If the entry has been previously looked up, the first value will be
938  // non-zero. If the value is equal to i (the start point of our search), then
939  // this is a matching hit.
940  if (!SkipCache && CacheLookup.StartIdx == i+1) {
941  // Skip querying potentially lots of directories for this lookup.
942  i = CacheLookup.HitIdx;
943  if (CacheLookup.MappedName) {
944  Filename = CacheLookup.MappedName;
945  if (IsMapped)
946  *IsMapped = true;
947  }
948  } else {
949  // Otherwise, this is the first query, or the previous query didn't match
950  // our search start. We will fill in our found location below, so prime the
951  // start point value.
952  CacheLookup.reset(/*StartIdx=*/i+1);
953  }
954 
955  SmallString<64> MappedName;
956 
957  // Check each directory in sequence to see if it contains this file.
958  for (; i != SearchDirs.size(); ++i) {
959  bool InUserSpecifiedSystemFramework = false;
960  bool IsInHeaderMap = false;
961  bool IsFrameworkFoundInDir = false;
962  Optional<FileEntryRef> File = SearchDirs[i].LookupFile(
963  Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
964  SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
965  IsInHeaderMap, MappedName);
966  if (!MappedName.empty()) {
967  assert(IsInHeaderMap && "MappedName should come from a header map");
968  CacheLookup.MappedName =
969  copyString(MappedName, LookupFileCache.getAllocator());
970  }
971  if (IsMapped)
972  // A filename is mapped when a header map remapped it to a relative path
973  // used in subsequent header search or to an absolute path pointing to an
974  // existing file.
975  *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
976  if (IsFrameworkFound)
977  // Because we keep a filename remapped for subsequent search directory
978  // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
979  // just for remapping in a current search directory.
980  *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
981  if (!File)
982  continue;
983 
984  CurDir = &SearchDirs[i];
985 
986  // This file is a system header or C++ unfriendly if the dir is.
987  HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry());
988  HFI.DirInfo = CurDir->getDirCharacteristic();
989 
990  // If the directory characteristic is User but this framework was
991  // user-specified to be treated as a system framework, promote the
992  // characteristic.
993  if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
995 
996  // If the filename matches a known system header prefix, override
997  // whether the file is a system header.
998  for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
999  if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
1000  HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
1001  : SrcMgr::C_User;
1002  break;
1003  }
1004  }
1005 
1006  // If this file is found in a header map and uses the framework style of
1007  // includes, then this header is part of a framework we're building.
1008  if (CurDir->isHeaderMap() && isAngled) {
1009  size_t SlashPos = Filename.find('/');
1010  if (SlashPos != StringRef::npos)
1011  HFI.Framework =
1012  getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1013  if (CurDir->isIndexHeaderMap())
1014  HFI.IndexHeaderMapHeader = 1;
1015  }
1016 
1017  if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1018  &File->getFileEntry(), IncludeLoc)) {
1019  if (SuggestedModule)
1020  *SuggestedModule = MSSuggestedModule;
1021  return MSFE;
1022  }
1023 
1024  bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
1025  if (!Includers.empty())
1027  Diags, IncludeLoc, Includers.front().second->getName(), Filename,
1028  &File->getFileEntry(), isAngled, FoundByHeaderMap);
1029 
1030  // Remember this location for the next lookup we do.
1031  cacheLookupSuccess(CacheLookup, i, IncludeLoc);
1032  return File;
1033  }
1034 
1035  // If we are including a file with a quoted include "foo.h" from inside
1036  // a header in a framework that is currently being built, and we couldn't
1037  // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1038  // "Foo" is the name of the framework in which the including header was found.
1039  if (!Includers.empty() && Includers.front().first && !isAngled &&
1040  !Filename.contains('/')) {
1041  HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
1042  if (IncludingHFI.IndexHeaderMapHeader) {
1043  SmallString<128> ScratchFilename;
1044  ScratchFilename += IncludingHFI.Framework;
1045  ScratchFilename += '/';
1046  ScratchFilename += Filename;
1047 
1049  ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
1050  Includers.front(), SearchPath, RelativePath, RequestingModule,
1051  SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
1052 
1053  if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1054  File ? &File->getFileEntry() : nullptr,
1055  IncludeLoc)) {
1056  if (SuggestedModule)
1057  *SuggestedModule = MSSuggestedModule;
1058  return MSFE;
1059  }
1060 
1061  cacheLookupSuccess(LookupFileCache[Filename],
1062  LookupFileCache[ScratchFilename].HitIdx, IncludeLoc);
1063  // FIXME: SuggestedModule.
1064  return File;
1065  }
1066  }
1067 
1068  if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1069  nullptr, IncludeLoc)) {
1070  if (SuggestedModule)
1071  *SuggestedModule = MSSuggestedModule;
1072  return MSFE;
1073  }
1074 
1075  // Otherwise, didn't find it. Remember we didn't find this.
1076  CacheLookup.HitIdx = SearchDirs.size();
1077  return None;
1078 }
1079 
1080 /// LookupSubframeworkHeader - Look up a subframework for the specified
1081 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1082 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1083 /// is a subframework within Carbon.framework. If so, return the FileEntry
1084 /// for the designated file, otherwise return null.
1086  StringRef Filename, const FileEntry *ContextFileEnt,
1087  SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1088  Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
1089  assert(ContextFileEnt && "No context file?");
1090 
1091  // Framework names must have a '/' in the filename. Find it.
1092  // FIXME: Should we permit '\' on Windows?
1093  size_t SlashPos = Filename.find('/');
1094  if (SlashPos == StringRef::npos)
1095  return None;
1096 
1097  // Look up the base framework name of the ContextFileEnt.
1098  StringRef ContextName = ContextFileEnt->getName();
1099 
1100  // If the context info wasn't a framework, couldn't be a subframework.
1101  const unsigned DotFrameworkLen = 10;
1102  auto FrameworkPos = ContextName.find(".framework");
1103  if (FrameworkPos == StringRef::npos ||
1104  (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1105  ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1106  return None;
1107 
1108  SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1109  FrameworkPos +
1110  DotFrameworkLen + 1);
1111 
1112  // Append Frameworks/HIToolbox.framework/
1113  FrameworkName += "Frameworks/";
1114  FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1115  FrameworkName += ".framework/";
1116 
1117  auto &CacheLookup =
1118  *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1119  FrameworkCacheEntry())).first;
1120 
1121  // Some other location?
1122  if (CacheLookup.second.Directory &&
1123  CacheLookup.first().size() == FrameworkName.size() &&
1124  memcmp(CacheLookup.first().data(), &FrameworkName[0],
1125  CacheLookup.first().size()) != 0)
1126  return None;
1127 
1128  // Cache subframework.
1129  if (!CacheLookup.second.Directory) {
1130  ++NumSubFrameworkLookups;
1131 
1132  // If the framework dir doesn't exist, we fail.
1133  auto Dir = FileMgr.getDirectory(FrameworkName);
1134  if (!Dir)
1135  return None;
1136 
1137  // Otherwise, if it does, remember that this is the right direntry for this
1138  // framework.
1139  CacheLookup.second.Directory = *Dir;
1140  }
1141 
1142 
1143  if (RelativePath) {
1144  RelativePath->clear();
1145  RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1146  }
1147 
1148  // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1149  SmallString<1024> HeadersFilename(FrameworkName);
1150  HeadersFilename += "Headers/";
1151  if (SearchPath) {
1152  SearchPath->clear();
1153  // Without trailing '/'.
1154  SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1155  }
1156 
1157  HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1158  auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1159  if (!File) {
1160  // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1161  HeadersFilename = FrameworkName;
1162  HeadersFilename += "PrivateHeaders/";
1163  if (SearchPath) {
1164  SearchPath->clear();
1165  // Without trailing '/'.
1166  SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1167  }
1168 
1169  HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1170  File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1171 
1172  if (!File)
1173  return None;
1174  }
1175 
1176  // This file is a system header or C++ unfriendly if the old file is.
1177  //
1178  // Note that the temporary 'DirInfo' is required here, as either call to
1179  // getFileInfo could resize the vector and we don't want to rely on order
1180  // of evaluation.
1181  unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1182  getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
1183 
1184  FrameworkName.pop_back(); // remove the trailing '/'
1185  if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName,
1186  RequestingModule, SuggestedModule,
1187  /*IsSystem*/ false))
1188  return None;
1189 
1190  return *File;
1191 }
1192 
1193 //===----------------------------------------------------------------------===//
1194 // File Info Management.
1195 //===----------------------------------------------------------------------===//
1196 
1197 /// Merge the header file info provided by \p OtherHFI into the current
1198 /// header file info (\p HFI)
1200  const HeaderFileInfo &OtherHFI) {
1201  assert(OtherHFI.External && "expected to merge external HFI");
1202 
1203  HFI.isImport |= OtherHFI.isImport;
1204  HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1205  HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1206  HFI.NumIncludes += OtherHFI.NumIncludes;
1207 
1208  if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1209  HFI.ControllingMacro = OtherHFI.ControllingMacro;
1210  HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1211  }
1212 
1213  HFI.DirInfo = OtherHFI.DirInfo;
1214  HFI.External = (!HFI.IsValid || HFI.External);
1215  HFI.IsValid = true;
1217 
1218  if (HFI.Framework.empty())
1219  HFI.Framework = OtherHFI.Framework;
1220 }
1221 
1222 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1223 /// FileEntry.
1225  if (FE->getUID() >= FileInfo.size())
1226  FileInfo.resize(FE->getUID() + 1);
1227 
1228  HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1229  // FIXME: Use a generation count to check whether this is really up to date.
1230  if (ExternalSource && !HFI->Resolved) {
1231  auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1232  if (ExternalHFI.IsValid) {
1233  HFI->Resolved = true;
1234  if (ExternalHFI.External)
1235  mergeHeaderFileInfo(*HFI, ExternalHFI);
1236  }
1237  }
1238 
1239  HFI->IsValid = true;
1240  // We have local information about this header file, so it's no longer
1241  // strictly external.
1242  HFI->External = false;
1243  return *HFI;
1244 }
1245 
1246 const HeaderFileInfo *
1248  bool WantExternal) const {
1249  // If we have an external source, ensure we have the latest information.
1250  // FIXME: Use a generation count to check whether this is really up to date.
1251  HeaderFileInfo *HFI;
1252  if (ExternalSource) {
1253  if (FE->getUID() >= FileInfo.size()) {
1254  if (!WantExternal)
1255  return nullptr;
1256  FileInfo.resize(FE->getUID() + 1);
1257  }
1258 
1259  HFI = &FileInfo[FE->getUID()];
1260  if (!WantExternal && (!HFI->IsValid || HFI->External))
1261  return nullptr;
1262  if (!HFI->Resolved) {
1263  auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1264  if (ExternalHFI.IsValid) {
1265  HFI->Resolved = true;
1266  if (ExternalHFI.External)
1267  mergeHeaderFileInfo(*HFI, ExternalHFI);
1268  }
1269  }
1270  } else if (FE->getUID() >= FileInfo.size()) {
1271  return nullptr;
1272  } else {
1273  HFI = &FileInfo[FE->getUID()];
1274  }
1275 
1276  if (!HFI->IsValid || (HFI->External && !WantExternal))
1277  return nullptr;
1278 
1279  return HFI;
1280 }
1281 
1283  // Check if we've entered this file and found an include guard or #pragma
1284  // once. Note that we dor't check for #import, because that's not a property
1285  // of the file itself.
1286  if (auto *HFI = getExistingFileInfo(File))
1287  return HFI->isPragmaOnce || HFI->ControllingMacro ||
1288  HFI->ControllingMacroID;
1289  return false;
1290 }
1291 
1294  bool isCompilingModuleHeader) {
1295  bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1296 
1297  // Don't mark the file info as non-external if there's nothing to change.
1298  if (!isCompilingModuleHeader) {
1299  if (!isModularHeader)
1300  return;
1301  auto *HFI = getExistingFileInfo(FE);
1302  if (HFI && HFI->isModuleHeader)
1303  return;
1304  }
1305 
1306  auto &HFI = getFileInfo(FE);
1307  HFI.isModuleHeader |= isModularHeader;
1308  HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1309 }
1310 
1312  const FileEntry *File, bool isImport,
1313  bool ModulesEnabled, Module *M) {
1314  ++NumIncluded; // Count # of attempted #includes.
1315 
1316  // Get information about this file.
1317  HeaderFileInfo &FileInfo = getFileInfo(File);
1318 
1319  // FIXME: this is a workaround for the lack of proper modules-aware support
1320  // for #import / #pragma once
1321  auto TryEnterImported = [&]() -> bool {
1322  if (!ModulesEnabled)
1323  return false;
1324  // Ensure FileInfo bits are up to date.
1325  ModMap.resolveHeaderDirectives(File);
1326  // Modules with builtins are special; multiple modules use builtins as
1327  // modular headers, example:
1328  //
1329  // module stddef { header "stddef.h" export * }
1330  //
1331  // After module map parsing, this expands to:
1332  //
1333  // module stddef {
1334  // header "/path_to_builtin_dirs/stddef.h"
1335  // textual "stddef.h"
1336  // }
1337  //
1338  // It's common that libc++ and system modules will both define such
1339  // submodules. Make sure cached results for a builtin header won't
1340  // prevent other builtin modules from potentially entering the builtin
1341  // header. Note that builtins are header guarded and the decision to
1342  // actually enter them is postponed to the controlling macros logic below.
1343  bool TryEnterHdr = false;
1344  if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1345  TryEnterHdr = ModMap.isBuiltinHeader(File);
1346 
1347  // Textual headers can be #imported from different modules. Since ObjC
1348  // headers find in the wild might rely only on #import and do not contain
1349  // controlling macros, be conservative and only try to enter textual headers
1350  // if such macro is present.
1351  if (!FileInfo.isModuleHeader &&
1352  FileInfo.getControllingMacro(ExternalLookup))
1353  TryEnterHdr = true;
1354  return TryEnterHdr;
1355  };
1356 
1357  // If this is a #import directive, check that we have not already imported
1358  // this header.
1359  if (isImport) {
1360  // If this has already been imported, don't import it again.
1361  FileInfo.isImport = true;
1362 
1363  // Has this already been #import'ed or #include'd?
1364  if (FileInfo.NumIncludes && !TryEnterImported())
1365  return false;
1366  } else {
1367  // Otherwise, if this is a #include of a file that was previously #import'd
1368  // or if this is the second #include of a #pragma once file, ignore it.
1369  if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported())
1370  return false;
1371  }
1372 
1373  // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1374  // if the macro that guards it is defined, we know the #include has no effect.
1375  if (const IdentifierInfo *ControllingMacro
1376  = FileInfo.getControllingMacro(ExternalLookup)) {
1377  // If the header corresponds to a module, check whether the macro is already
1378  // defined in that module rather than checking in the current set of visible
1379  // modules.
1380  if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1381  : PP.isMacroDefined(ControllingMacro)) {
1382  ++NumMultiIncludeFileOptzn;
1383  return false;
1384  }
1385  }
1386 
1387  // Increment the number of times this file has been included.
1388  ++FileInfo.NumIncludes;
1389 
1390  return true;
1391 }
1392 
1394  return SearchDirs.capacity()
1395  + llvm::capacity_in_bytes(FileInfo)
1396  + llvm::capacity_in_bytes(HeaderMaps)
1397  + LookupFileCache.getAllocator().getTotalMemory()
1398  + FrameworkMap.getAllocator().getTotalMemory();
1399 }
1400 
1402  for (unsigned I = 0; I < SearchDirs.size(); ++I)
1403  if (&SearchDirs[I] == &DL)
1404  return I;
1405  return None;
1406 }
1407 
1408 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1409  return FrameworkNames.insert(Framework).first->first();
1410 }
1411 
1412 bool HeaderSearch::hasModuleMap(StringRef FileName,
1413  const DirectoryEntry *Root,
1414  bool IsSystem) {
1415  if (!HSOpts->ImplicitModuleMaps)
1416  return false;
1417 
1418  SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1419 
1420  StringRef DirName = FileName;
1421  do {
1422  // Get the parent directory name.
1423  DirName = llvm::sys::path::parent_path(DirName);
1424  if (DirName.empty())
1425  return false;
1426 
1427  // Determine whether this directory exists.
1428  auto Dir = FileMgr.getDirectory(DirName);
1429  if (!Dir)
1430  return false;
1431 
1432  // Try to load the module map file in this directory.
1433  switch (loadModuleMapFile(*Dir, IsSystem,
1434  llvm::sys::path::extension((*Dir)->getName()) ==
1435  ".framework")) {
1436  case LMM_NewlyLoaded:
1437  case LMM_AlreadyLoaded:
1438  // Success. All of the directories we stepped through inherit this module
1439  // map file.
1440  for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1441  DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1442  return true;
1443 
1444  case LMM_NoDirectory:
1445  case LMM_InvalidModuleMap:
1446  break;
1447  }
1448 
1449  // If we hit the top of our search, we're done.
1450  if (*Dir == Root)
1451  return false;
1452 
1453  // Keep track of all of the directories we checked, so we can mark them as
1454  // having module maps if we eventually do find a module map.
1455  FixUpDirectories.push_back(*Dir);
1456  } while (true);
1457 }
1458 
1461  bool AllowTextual) const {
1462  if (ExternalSource) {
1463  // Make sure the external source has handled header info about this file,
1464  // which includes whether the file is part of a module.
1465  (void)getExistingFileInfo(File);
1466  }
1467  return ModMap.findModuleForHeader(File, AllowTextual);
1468 }
1469 
1472  if (ExternalSource) {
1473  // Make sure the external source has handled header info about this file,
1474  // which includes whether the file is part of a module.
1475  (void)getExistingFileInfo(File);
1476  }
1477  return ModMap.findAllModulesForHeader(File);
1478 }
1479 
1480 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1481  Module *RequestingModule,
1482  ModuleMap::KnownHeader *SuggestedModule) {
1484  HS.findModuleForHeader(File, /*AllowTextual*/true);
1485 
1486  // If this module specifies [no_undeclared_includes], we cannot find any
1487  // file that's in a non-dependency module.
1488  if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1489  HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);
1490  if (!RequestingModule->directlyUses(Module.getModule())) {
1491  // Builtin headers are a special case. Multiple modules can use the same
1492  // builtin as a modular header (see also comment in
1493  // ShouldEnterIncludeFile()), so the builtin header may have been
1494  // "claimed" by an unrelated module. This shouldn't prevent us from
1495  // including the builtin header textually in this module.
1496  if (HS.getModuleMap().isBuiltinHeader(File)) {
1497  if (SuggestedModule)
1498  *SuggestedModule = ModuleMap::KnownHeader();
1499  return true;
1500  }
1501  return false;
1502  }
1503  }
1504 
1505  if (SuggestedModule)
1506  *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1508  : Module;
1509 
1510  return true;
1511 }
1512 
1513 bool HeaderSearch::findUsableModuleForHeader(
1514  const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1515  ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1516  if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1517  // If there is a module that corresponds to this header, suggest it.
1518  hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1519  return suggestModule(*this, File, RequestingModule, SuggestedModule);
1520  }
1521  return true;
1522 }
1523 
1524 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1525  const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1526  ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1527  // If we're supposed to suggest a module, look for one now.
1528  if (needModuleLookup(RequestingModule, SuggestedModule)) {
1529  // Find the top-level framework based on this framework.
1530  SmallVector<std::string, 4> SubmodulePath;
1531  const DirectoryEntry *TopFrameworkDir
1532  = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1533 
1534  // Determine the name of the top-level framework.
1535  StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1536 
1537  // Load this framework module. If that succeeds, find the suggested module
1538  // for this header, if any.
1539  loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1540 
1541  // FIXME: This can find a module not part of ModuleName, which is
1542  // important so that we're consistent about whether this header
1543  // corresponds to a module. Possibly we should lock down framework modules
1544  // so that this is not possible.
1545  return suggestModule(*this, File, RequestingModule, SuggestedModule);
1546  }
1547  return true;
1548 }
1549 
1550 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1551  FileManager &FileMgr) {
1552  StringRef Filename = llvm::sys::path::filename(File->getName());
1553  SmallString<128> PrivateFilename(File->getDir()->getName());
1554  if (Filename == "module.map")
1555  llvm::sys::path::append(PrivateFilename, "module_private.map");
1556  else if (Filename == "module.modulemap")
1557  llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1558  else
1559  return nullptr;
1560  if (auto File = FileMgr.getFile(PrivateFilename))
1561  return *File;
1562  return nullptr;
1563 }
1564 
1565 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
1566  FileID ID, unsigned *Offset,
1567  StringRef OriginalModuleMapFile) {
1568  // Find the directory for the module. For frameworks, that may require going
1569  // up from the 'Modules' directory.
1570  const DirectoryEntry *Dir = nullptr;
1571  if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1572  if (auto DirOrErr = FileMgr.getDirectory("."))
1573  Dir = *DirOrErr;
1574  } else {
1575  if (!OriginalModuleMapFile.empty()) {
1576  // We're building a preprocessed module map. Find or invent the directory
1577  // that it originally occupied.
1578  auto DirOrErr = FileMgr.getDirectory(
1579  llvm::sys::path::parent_path(OriginalModuleMapFile));
1580  if (DirOrErr) {
1581  Dir = *DirOrErr;
1582  } else {
1583  auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1584  Dir = FakeFile->getDir();
1585  }
1586  } else {
1587  Dir = File->getDir();
1588  }
1589 
1590  StringRef DirName(Dir->getName());
1591  if (llvm::sys::path::filename(DirName) == "Modules") {
1592  DirName = llvm::sys::path::parent_path(DirName);
1593  if (DirName.endswith(".framework"))
1594  if (auto DirOrErr = FileMgr.getDirectory(DirName))
1595  Dir = *DirOrErr;
1596  // FIXME: This assert can fail if there's a race between the above check
1597  // and the removal of the directory.
1598  assert(Dir && "parent must exist");
1599  }
1600  }
1601 
1602  switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
1603  case LMM_AlreadyLoaded:
1604  case LMM_NewlyLoaded:
1605  return false;
1606  case LMM_NoDirectory:
1607  case LMM_InvalidModuleMap:
1608  return true;
1609  }
1610  llvm_unreachable("Unknown load module map result");
1611 }
1612 
1613 HeaderSearch::LoadModuleMapResult
1614 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1615  const DirectoryEntry *Dir, FileID ID,
1616  unsigned *Offset) {
1617  assert(File && "expected FileEntry");
1618 
1619  // Check whether we've already loaded this module map, and mark it as being
1620  // loaded in case we recursively try to load it from itself.
1621  auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1622  if (!AddResult.second)
1623  return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1624 
1625  if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1626  LoadedModuleMaps[File] = false;
1627  return LMM_InvalidModuleMap;
1628  }
1629 
1630  // Try to load a corresponding private module map.
1631  if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1632  if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1633  LoadedModuleMaps[File] = false;
1634  return LMM_InvalidModuleMap;
1635  }
1636  }
1637 
1638  // This directory has a module map.
1639  return LMM_NewlyLoaded;
1640 }
1641 
1642 const FileEntry *
1643 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1644  if (!HSOpts->ImplicitModuleMaps)
1645  return nullptr;
1646  // For frameworks, the preferred spelling is Modules/module.modulemap, but
1647  // module.map at the framework root is also accepted.
1648  SmallString<128> ModuleMapFileName(Dir->getName());
1649  if (IsFramework)
1650  llvm::sys::path::append(ModuleMapFileName, "Modules");
1651  llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1652  if (auto F = FileMgr.getFile(ModuleMapFileName))
1653  return *F;
1654 
1655  // Continue to allow module.map
1656  ModuleMapFileName = Dir->getName();
1657  llvm::sys::path::append(ModuleMapFileName, "module.map");
1658  if (auto F = FileMgr.getFile(ModuleMapFileName))
1659  return *F;
1660 
1661  // For frameworks, allow to have a private module map with a preferred
1662  // spelling when a public module map is absent.
1663  if (IsFramework) {
1664  ModuleMapFileName = Dir->getName();
1665  llvm::sys::path::append(ModuleMapFileName, "Modules",
1666  "module.private.modulemap");
1667  if (auto F = FileMgr.getFile(ModuleMapFileName))
1668  return *F;
1669  }
1670  return nullptr;
1671 }
1672 
1673 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1674  const DirectoryEntry *Dir,
1675  bool IsSystem) {
1676  if (Module *Module = ModMap.findModule(Name))
1677  return Module;
1678 
1679  // Try to load a module map file.
1680  switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1681  case LMM_InvalidModuleMap:
1682  // Try to infer a module map from the framework directory.
1683  if (HSOpts->ImplicitModuleMaps)
1684  ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1685  break;
1686 
1687  case LMM_AlreadyLoaded:
1688  case LMM_NoDirectory:
1689  return nullptr;
1690 
1691  case LMM_NewlyLoaded:
1692  break;
1693  }
1694 
1695  return ModMap.findModule(Name);
1696 }
1697 
1698 HeaderSearch::LoadModuleMapResult
1699 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1700  bool IsFramework) {
1701  if (auto Dir = FileMgr.getDirectory(DirName))
1702  return loadModuleMapFile(*Dir, IsSystem, IsFramework);
1703 
1704  return LMM_NoDirectory;
1705 }
1706 
1707 HeaderSearch::LoadModuleMapResult
1708 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1709  bool IsFramework) {
1710  auto KnownDir = DirectoryHasModuleMap.find(Dir);
1711  if (KnownDir != DirectoryHasModuleMap.end())
1712  return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1713 
1714  if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1715  LoadModuleMapResult Result =
1716  loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1717  // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1718  // E.g. Foo.framework/Modules/module.modulemap
1719  // ^Dir ^ModuleMapFile
1720  if (Result == LMM_NewlyLoaded)
1721  DirectoryHasModuleMap[Dir] = true;
1722  else if (Result == LMM_InvalidModuleMap)
1723  DirectoryHasModuleMap[Dir] = false;
1724  return Result;
1725  }
1726  return LMM_InvalidModuleMap;
1727 }
1728 
1730  Modules.clear();
1731 
1732  if (HSOpts->ImplicitModuleMaps) {
1733  // Load module maps for each of the header search directories.
1734  for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1735  bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1736  if (SearchDirs[Idx].isFramework()) {
1737  std::error_code EC;
1738  SmallString<128> DirNative;
1739  llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1740  DirNative);
1741 
1742  // Search each of the ".framework" directories to load them as modules.
1743  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1744  for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1745  DirEnd;
1746  Dir != DirEnd && !EC; Dir.increment(EC)) {
1747  if (llvm::sys::path::extension(Dir->path()) != ".framework")
1748  continue;
1749 
1750  auto FrameworkDir =
1751  FileMgr.getDirectory(Dir->path());
1752  if (!FrameworkDir)
1753  continue;
1754 
1755  // Load this framework module.
1756  loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
1757  IsSystem);
1758  }
1759  continue;
1760  }
1761 
1762  // FIXME: Deal with header maps.
1763  if (SearchDirs[Idx].isHeaderMap())
1764  continue;
1765 
1766  // Try to load a module map file for the search directory.
1767  loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1768  /*IsFramework*/ false);
1769 
1770  // Try to load module map files for immediate subdirectories of this
1771  // search directory.
1772  loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1773  }
1774  }
1775 
1776  // Populate the list of modules.
1777  for (ModuleMap::module_iterator M = ModMap.module_begin(),
1778  MEnd = ModMap.module_end();
1779  M != MEnd; ++M) {
1780  Modules.push_back(M->getValue());
1781  }
1782 }
1783 
1785  if (!HSOpts->ImplicitModuleMaps)
1786  return;
1787 
1788  // Load module maps for each of the header search directories.
1789  for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1790  // We only care about normal header directories.
1791  if (!SearchDirs[Idx].isNormalDir()) {
1792  continue;
1793  }
1794 
1795  // Try to load a module map file for the search directory.
1796  loadModuleMapFile(SearchDirs[Idx].getDir(),
1797  SearchDirs[Idx].isSystemHeaderDirectory(),
1798  SearchDirs[Idx].isFramework());
1799  }
1800 }
1801 
1802 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1803  assert(HSOpts->ImplicitModuleMaps &&
1804  "Should not be loading subdirectory module maps");
1805 
1806  if (SearchDir.haveSearchedAllModuleMaps())
1807  return;
1808 
1809  std::error_code EC;
1810  SmallString<128> Dir = SearchDir.getDir()->getName();
1811  FileMgr.makeAbsolutePath(Dir);
1812  SmallString<128> DirNative;
1813  llvm::sys::path::native(Dir, DirNative);
1814  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1815  for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1816  Dir != DirEnd && !EC; Dir.increment(EC)) {
1817  bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1818  if (IsFramework == SearchDir.isFramework())
1819  loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1820  SearchDir.isFramework());
1821  }
1822 
1823  SearchDir.setSearchedAllModuleMaps(true);
1824 }
1825 
1827  const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
1828  // FIXME: We assume that the path name currently cached in the FileEntry is
1829  // the most appropriate one for this analysis (and that it's spelled the
1830  // same way as the corresponding header search path).
1831  return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1832  MainFile, IsSystem);
1833 }
1834 
1836  llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1837  bool *IsSystem) {
1838  using namespace llvm::sys;
1839 
1840  unsigned BestPrefixLength = 0;
1841  // Checks whether Dir and File shares a common prefix, if they do and that's
1842  // the longest prefix we've seen so for it returns true and updates the
1843  // BestPrefixLength accordingly.
1844  auto CheckDir = [&](llvm::StringRef Dir) -> bool {
1845  llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
1846  if (!WorkingDir.empty() && !path::is_absolute(Dir))
1847  fs::make_absolute(WorkingDir, DirPath);
1848  path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1849  Dir = DirPath;
1850  for (auto NI = path::begin(File), NE = path::end(File),
1851  DI = path::begin(Dir), DE = path::end(Dir);
1852  /*termination condition in loop*/; ++NI, ++DI) {
1853  // '.' components in File are ignored.
1854  while (NI != NE && *NI == ".")
1855  ++NI;
1856  if (NI == NE)
1857  break;
1858 
1859  // '.' components in Dir are ignored.
1860  while (DI != DE && *DI == ".")
1861  ++DI;
1862  if (DI == DE) {
1863  // Dir is a prefix of File, up to '.' components and choice of path
1864  // separators.
1865  unsigned PrefixLength = NI - path::begin(File);
1866  if (PrefixLength > BestPrefixLength) {
1867  BestPrefixLength = PrefixLength;
1868  return true;
1869  }
1870  break;
1871  }
1872 
1873  // Consider all path separators equal.
1874  if (NI->size() == 1 && DI->size() == 1 &&
1875  path::is_separator(NI->front()) && path::is_separator(DI->front()))
1876  continue;
1877 
1878  if (*NI != *DI)
1879  break;
1880  }
1881  return false;
1882  };
1883 
1884  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1885  // FIXME: Support this search within frameworks.
1886  if (!SearchDirs[I].isNormalDir())
1887  continue;
1888 
1889  StringRef Dir = SearchDirs[I].getDir()->getName();
1890  if (CheckDir(Dir) && IsSystem)
1891  *IsSystem = BestPrefixLength ? I >= SystemDirIdx : false;
1892  }
1893 
1894  // Try to shorten include path using TUs directory, if we couldn't find any
1895  // suitable prefix in include search paths.
1896  if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
1897  *IsSystem = false;
1898 
1899  // Try resolving resulting filename via reverse search in header maps,
1900  // key from header name is user prefered name for the include file.
1901  StringRef Filename = File.drop_front(BestPrefixLength);
1902  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1903  if (!SearchDirs[I].isHeaderMap())
1904  continue;
1905 
1906  StringRef SpelledFilename =
1907  SearchDirs[I].getHeaderMap()->reverseLookupFilename(Filename);
1908  if (!SpelledFilename.empty()) {
1909  Filename = SpelledFilename;
1910  break;
1911  }
1912  }
1913  return path::convert_to_slash(Filename);
1914 }
clang::HeaderSearch::isFileMultipleIncludeGuarded
bool isFileMultipleIncludeGuarded(const FileEntry *File)
Determine whether this file is intended to be safe from multiple inclusions, e.g.,...
Definition: HeaderSearch.cpp:1282
clang::FileManager::getOptionalFileRef
llvm::Optional< FileEntryRef > getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:232
clang::Module::directlyUses
bool directlyUses(const Module *Requested) const
Determine whether this module has declared its intention to directly use another module.
Definition: Module.cpp:270
clang::ExternalHeaderFileInfoSource::GetHeaderFileInfo
virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE)=0
Retrieve the header file information for the given file entry.
clang::DirectoryLookup::isNormalDir
bool isNormalDir() const
isNormalDir - Return true if this is a normal directory, not a header map.
Definition: DirectoryLookup.h:111
clang::HeaderFileInfo::IsValid
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:90
clang::ModuleMap::resolveUses
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1312
clang::HeaderSearch::getFileInfo
HeaderFileInfo & getFileInfo(const FileEntry *FE)
Return the HeaderFileInfo structure for the specified FileEntry, in preparation for updating it in so...
Definition: HeaderSearch.cpp:1224
clang::ExternalPreprocessorSource
Abstract interface for external sources of preprocessor information.
Definition: ExternalPreprocessorSource.h:26
clang::HeaderFileInfo::Framework
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:114
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::ModuleMap::KnownHeader
A header that is known to reside within a given module, whether it was included or excluded.
Definition: ModuleMap.h:155
clang::HeaderFileInfo::isPragmaOnce
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:58
clang::DeclaratorContext::File
@ File
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
ModuleMap.h
llvm::SmallVector
Definition: LLVM.h:38
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:909
clang::DirectoryEntry::getName
StringRef getName() const
Definition: DirectoryEntry.h:40
clang::HeaderSearch::hasModuleMap
bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root, bool IsSystem)
Determine whether there is a module map that may map the header with the given file name to a (sub)mo...
Definition: HeaderSearch.cpp:1412
clang::MultiVersionKind::Target
@ Target
clang::ModuleMap::module_begin
module_iterator module_begin() const
Definition: ModuleMap.h:699
clang::FileManager::getFileRef
llvm::Expected< FileEntryRef > getFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Definition: FileManager.cpp:204
clang::FrameworkCacheEntry::IsUserSpecifiedSystemFramework
bool IsUserSpecifiedSystemFramework
Whether this framework has been "user-specified" to be treated as if it were a system framework (even...
Definition: HeaderSearch.h:164
clang::HeaderSearch::computeUserEntryUsage
std::vector< bool > computeUserEntryUsage() const
Determine which HeaderSearchOptions::UserEntries have been successfully used so far and mark their in...
Definition: HeaderSearch.cpp:111
clang::HeaderSearch::LookupFrameworkCache
FrameworkCacheEntry & LookupFrameworkCache(StringRef FWName)
Look up the specified framework name in our framework cache.
Definition: HeaderSearch.h:443
Filename
StringRef Filename
Definition: Format.cpp:2333
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:191
clang::TargetInfo
Exposes information about the current target.
Definition: TargetInfo.h:189
clang::HeaderFileInfo::ControllingMacro
const IdentifierInfo * ControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
Definition: HeaderSearch.h:110
clang::ModuleMap::module_end
module_iterator module_end() const
Definition: ModuleMap.h:700
Module.h
clang::IdentifierInfo::isOutOfDate
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
Definition: IdentifierTable.h:414
clang::Module::Name
std::string Name
The name of this module.
Definition: Module.h:99
clang::HeaderFileInfo::External
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:68
clang::DirectoryLookup::isFramework
bool isFramework() const
isFramework - True if this is a framework directory.
Definition: DirectoryLookup.h:115
llvm::Optional< FileEntryRef >
clang::ComparisonCategoryType::First
@ First
SourceManager.h
clang::ModuleMap::module_iterator
llvm::StringMap< Module * >::const_iterator module_iterator
Definition: ModuleMap.h:697
clang::HeaderFileInfo::getControllingMacro
const IdentifierInfo * getControllingMacro(ExternalPreprocessorSource *External)
Retrieve the controlling macro for this header file, if any.
Definition: HeaderSearch.cpp:61
diagnoseFrameworkInclude
static void diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc, StringRef Includer, StringRef IncludeFilename, const FileEntry *IncludeFE, bool isAngled=false, bool FoundByHeaderMap=false)
Definition: HeaderSearch.cpp:756
DirectoryLookup.h
clang::DirectoryLookup::getFrameworkDirRef
Optional< DirectoryEntryRef > getFrameworkDirRef() const
Definition: DirectoryLookup.h:100
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
Preprocessor.h
clang::HeaderSearch
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:169
clang::DirectoryLookup::getFrameworkDir
const DirectoryEntry * getFrameworkDir() const
getFrameworkDir - Return the directory that this framework refers to.
Definition: DirectoryLookup.h:96
Offset
unsigned Offset
Definition: Format.cpp:2335
clang::HeaderSearch::getUniqueFrameworkName
StringRef getUniqueFrameworkName(StringRef Framework)
Retrieve a uniqued framework name.
Definition: HeaderSearch.cpp:1408
clang::ModuleMap::ModuleHeaderRole
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:128
clang::HeaderSearch::collectAllModules
void collectAllModules(SmallVectorImpl< Module * > &Modules)
Collect the set of all known, top-level modules.
Definition: HeaderSearch.cpp:1729
clang::Module::NoUndeclaredIncludes
unsigned NoUndeclaredIncludes
Whether files in this module can only include non-modular headers and headers from used modules.
Definition: Module.h:304
clang::DirectoryLookup::getDir
const DirectoryEntry * getDir() const
getDir - Return the directory that this entry refers to.
Definition: DirectoryLookup.h:90
clang::HeaderFileInfo::Resolved
unsigned Resolved
Whether this structure is considered to already have been "resolved", meaning that it was loaded from...
Definition: HeaderSearch.h:78
clang::HeaderSearch::ShouldEnterIncludeFile
bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File, bool isImport, bool ModulesEnabled, Module *M)
Mark the specified file as a target of a #include, #include_next, or #import directive.
Definition: HeaderSearch.cpp:1311
clang::Module
Describes a module or submodule.
Definition: Module.h:96
clang::HeaderMap::getFileName
StringRef getFileName() const
Return the filename of the headermap.
Definition: HeaderMap.cpp:109
HeaderSearchOptions.h
clang::HeaderMap::Create
static std::unique_ptr< HeaderMap > Create(const FileEntry *FE, FileManager &FM)
This attempts to load the specified file as a header map.
Definition: HeaderMap.cpp:50
clang::FileManager::getVirtualFileSystem
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:243
clang::DirectoryEntry
Cached information about one directory (either on disk or in the virtual file system).
Definition: DirectoryEntry.h:33
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::ModuleMap::findModule
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:791
clang::HeaderSearch::getFileMgr
FileManager & getFileMgr() const
Definition: HeaderSearch.h:284
getTopFrameworkDir
static const DirectoryEntry * getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, SmallVectorImpl< std::string > &SubmodulePath)
Given a framework directory, find the top-most framework directory.
Definition: HeaderSearch.cpp:484
clang::HeaderSearch::loadModuleMapFile
bool loadModuleMapFile(const FileEntry *File, bool IsSystem, FileID ID=FileID(), unsigned *Offset=nullptr, StringRef OriginalModuleMapFile=StringRef())
Read the contents of the given module map file.
Definition: HeaderSearch.cpp:1565
clang::HeaderSearch::getExistingFileInfo
const HeaderFileInfo * getExistingFileInfo(const FileEntry *FE, bool WantExternal=true) const
Return the HeaderFileInfo structure for the specified FileEntry, if it has ever been filled in.
Definition: HeaderSearch.cpp:1247
clang::HeaderFileInfo::IndexHeaderMapHeader
unsigned IndexHeaderMapHeader
Whether this is a header inside a framework that is currently being built.
Definition: HeaderSearch.h:87
clang::HeaderSearch::findAllModulesForHeader
ArrayRef< ModuleMap::KnownHeader > findAllModulesForHeader(const FileEntry *File) const
Retrieve all the modules corresponding to the given file.
Definition: HeaderSearch.cpp:1471
clang::DirectoryLookup
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
Definition: DirectoryLookup.h:30
Diagnostic.h
LexDiagnostic.h
clang::FrameworkCacheEntry::Directory
const DirectoryEntry * Directory
The directory entry which should be used for the cached framework.
Definition: HeaderSearch.h:159
suggestModule
static bool suggestModule(HeaderSearch &HS, const FileEntry *File, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule)
Definition: HeaderSearch.cpp:1480
clang::DirectoryLookup::getHeaderMap
const HeaderMap * getHeaderMap() const
getHeaderMap - Return the directory that this entry refers to.
Definition: DirectoryLookup.h:106
clang::ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource
virtual ~ExternalHeaderFileInfoSource()
clang::HeaderSearch::lookupModule
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
Definition: HeaderSearch.cpp:246
clang::HeaderSearch::suggestPathToFileForDiagnostics
std::string suggestPathToFileForDiagnostics(const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem=nullptr)
Suggest a path by which the specified file could be found, for use in diagnostics to suggest a includ...
Definition: HeaderSearch.cpp:1826
clang::Preprocessor::isMacroDefined
bool isMacroDefined(StringRef Id)
Definition: Preprocessor.h:1088
IdentifierTable.h
clang::ModuleMap::findModuleForHeader
KnownHeader findModuleForHeader(const FileEntry *File, bool AllowTextual=false)
Retrieve the module that owns the given header file, if any.
Definition: ModuleMap.cpp:572
llvm::SmallString
Definition: LLVM.h:37
clang::FrameworkCacheEntry
This structure is used to record entries in our framework cache.
Definition: HeaderSearch.h:157
clang::HeaderSearch::LookupFile
Optional< FileEntryRef > LookupFile(StringRef Filename, SourceLocation IncludeLoc, bool isAngled, const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, ArrayRef< std::pair< const FileEntry *, const DirectoryEntry * >> Includers, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool BuildSystemModule=false)
Given a "foo" or <foo> reference, look up the indicated file, return null on failure.
Definition: HeaderSearch.cpp:795
clang::ModuleMap::getModuleMapFileForUniquing
const FileEntry * getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
Definition: ModuleMap.cpp:1259
clang::HeaderSearch::getModuleHash
StringRef getModuleHash() const
Retrieve the module hash.
Definition: HeaderSearch.h:354
clang::DirectoryLookup::LookupFile
Optional< FileEntryRef > LookupFile(StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound, bool &IsInHeaderMap, SmallVectorImpl< char > &MappedName) const
LookupFile - Lookup the specified file in this search path, returning it if it exists or returning nu...
Definition: HeaderSearch.cpp:399
clang::SrcMgr::C_User
@ C_User
Definition: SourceManager.h:79
clang::HeaderMap
This class represents an Apple concept known as a 'header map'.
Definition: HeaderMap.h:70
getName
static std::string getName(const CallEvent &Call)
Definition: ReturnValueChecker.cpp:60
clang::DirectoryLookup::isHeaderMap
bool isHeaderMap() const
isHeaderMap - Return true if this is a header map, not a normal directory.
Definition: DirectoryLookup.h:118
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:331
clang::ModuleMap
Definition: ModuleMap.h:75
clang::FileEntry::getUID
unsigned getUID() const
Definition: FileEntry.h:370
clang::HeaderSearch::MarkFileModuleHeader
void MarkFileModuleHeader(const FileEntry *FE, ModuleMap::ModuleHeaderRole Role, bool isCompilingModuleHeader)
Mark the specified file as part of a module.
Definition: HeaderSearch.cpp:1292
clang::format::hash_combine
static void hash_combine(std::size_t &seed, const T &v)
Definition: UnwrappedLineParser.cpp:579
clang::HeaderSearch::CreateHeaderMap
const HeaderMap * CreateHeaderMap(const FileEntry *FE)
This method returns a HeaderMap for the specified FileEntry, uniquing them through the 'HeaderMaps' d...
Definition: HeaderSearch.cpp:127
clang::HeaderSearch::getCachedModuleFileName
std::string getCachedModuleFileName(Module *Module)
Retrieve the name of the cached module file that should be used to load the given module.
Definition: HeaderSearch.cpp:153
clang::ModuleMap::isBuiltinHeader
static bool isBuiltinHeader(StringRef FileName)
Is this a compiler builtin header?
Definition: ModuleMap.cpp:375
clang::ModuleMap::TextualHeader
@ TextualHeader
This header is part of the module (for layering purposes) but should be textually included.
Definition: ModuleMap.h:137
clang::HeaderSearch::lookupModuleMapFile
const FileEntry * lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework)
Try to find a module map file in the given directory, returning nullptr if none is found.
Definition: HeaderSearch.cpp:1643
isFrameworkStylePath
static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader, SmallVectorImpl< char > &FrameworkName)
Definition: HeaderSearch.cpp:722
clang::HeaderSearch::LookupSubframeworkHeader
Optional< FileEntryRef > LookupSubframeworkHeader(StringRef Filename, const FileEntry *ContextFileEnt, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule)
Look up a subframework for the specified #include file.
Definition: HeaderSearch.cpp:1085
ALWAYS_ENABLED_STATISTIC
ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.")
HeaderMap.h
false
#define false
Definition: stdbool.h:17
clang::HeaderSearch::findModuleForHeader
ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File, bool AllowTextual=false) const
Retrieve the module that corresponds to the given file, if any.
Definition: HeaderSearch.cpp:1460
needModuleLookup
static bool needModuleLookup(Module *RequestingModule, bool HasSuggestedModule)
Definition: HeaderSearch.cpp:531
clang::HeaderFileInfo::NumIncludes
unsigned short NumIncludes
The number of times the file has been included already.
Definition: HeaderSearch.h:93
clang::HeaderSearch::getModuleCachePath
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:357
clang::DirectoryLookup::setSearchedAllModuleMaps
void setSearchedAllModuleMaps(bool SAMM)
Specify whether we have already searched all of the subdirectories for module maps.
Definition: DirectoryLookup.h:126
llvm::ArrayRef
Definition: LLVM.h:34
HeaderSearch.h
clang::HeaderFileInfo::isModuleHeader
unsigned isModuleHeader
Whether this header is part of a module.
Definition: HeaderSearch.h:71
clang::ModuleMap::resolveHeaderDirectives
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1187
clang::HeaderSearch::searchDirIdx
Optional< unsigned > searchDirIdx(const DirectoryLookup &DL) const
Get the index of the given search directory.
Definition: HeaderSearch.cpp:1401
clang::HeaderMap::lookupFilename
StringRef lookupFilename(StringRef Filename, SmallVectorImpl< char > &DestPath) const
If the specified relative filename is located in this HeaderMap return the filename it is mapped to,...
Definition: HeaderMap.cpp:197
clang::HeaderFileInfo
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:53
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
clang::HeaderSearch::loadTopLevelSystemModules
void loadTopLevelSystemModules()
Load all known, top-level system modules.
Definition: HeaderSearch.cpp:1784
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::HeaderSearch::getHeaderSearchOpts
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:282
std
Definition: Format.h:4034
clang::interp::NE
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:225
clang::ModuleMap::findAllModulesForHeader
ArrayRef< KnownHeader > findAllModulesForHeader(const FileEntry *File)
Retrieve all the modules that contain the given header file.
Definition: ModuleMap.cpp:670
clang::FileManager::makeAbsolutePath
bool makeAbsolutePath(SmallVectorImpl< char > &Path) const
Makes Path absolute taking into account FileSystemOptions and the working directory option.
Definition: FileManager.cpp:498
clang::Builtin::ID
ID
Definition: Builtins.h:48
clang::DirectoryLookup::getDirCharacteristic
SrcMgr::CharacteristicKind getDirCharacteristic() const
DirCharacteristic - The type of directory this is, one of the DirType enum values.
Definition: DirectoryLookup.h:132
clang
Definition: CalledOnceCheck.h:17
clang::FileManager
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
clang::FileManager::getCanonicalName
StringRef getCanonicalName(const DirectoryEntry *Dir)
Retrieve the canonical name for a given directory.
Definition: FileManager.cpp:616
clang::FileEntry::getName
StringRef getName() const
Definition: FileEntry.h:364
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:40
clang::HeaderSearch::getTotalMemory
size_t getTotalMemory() const
Definition: HeaderSearch.cpp:1393
mergeHeaderFileInfo
static void mergeHeaderFileInfo(HeaderFileInfo &HFI, const HeaderFileInfo &OtherHFI)
Merge the header file info provided by OtherHFI into the current header file info (HFI)
Definition: HeaderSearch.cpp:1199
clang::FileManager::getDirectory
llvm::ErrorOr< const DirectoryEntry * > getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
Definition: FileManager.cpp:188
checkMSVCHeaderSearch
static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, const FileEntry *MSFE, const FileEntry *FE, SourceLocation IncludeLoc)
Return true with a diagnostic if the file that MSVC would have found fails to match the one that Clan...
Definition: HeaderSearch.cpp:704
clang::HeaderSearch::getPrebuiltModuleFileName
std::string getPrebuiltModuleFileName(StringRef ModuleName, bool FileMapOnly=false)
Retrieve the name of the prebuilt module file that should be used to load a module with the given nam...
Definition: HeaderSearch.cpp:159
clang::FileManager::getFile
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Definition: FileManager.cpp:196
clang::DirectoryLookup::isIndexHeaderMap
bool isIndexHeaderMap() const
Whether this header map is building a framework or not.
Definition: DirectoryLookup.h:142
clang::HeaderFileInfo::DirInfo
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:64
clang::HeaderSearch::getPrebuiltImplicitModuleFileName
std::string getPrebuiltImplicitModuleFileName(Module *Module)
Retrieve the name of the prebuilt module file that should be used to load the given module.
Definition: HeaderSearch.cpp:181
clang::HeaderSearch::HeaderSearch
HeaderSearch(std::shared_ptr< HeaderSearchOptions > HSOpts, SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target)
Definition: HeaderSearch.cpp:81
clang::HeaderSearch::getHeaderMapFileNames
void getHeaderMapFileNames(SmallVectorImpl< std::string > &Names) const
Get filenames for all registered header maps.
Definition: HeaderSearch.cpp:147
Parent
NodeId Parent
Definition: ASTDiff.cpp:192
clang::ModuleMap::parseModuleMapFile
bool parseModuleMapFile(const FileEntry *File, bool IsSystem, const DirectoryEntry *HomeDir, FileID ID=FileID(), unsigned *Offset=nullptr, SourceLocation ExternModuleLoc=SourceLocation())
Parse the given module map file, and record any modules we encounter.
Definition: ModuleMap.cpp:2995
clang::HeaderFileInfo::isImport
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:55
clang::DirectoryLookup::isSystemHeaderDirectory
bool isSystemHeaderDirectory() const
Whether this describes a system header directory.
Definition: DirectoryLookup.h:137
llvm::SmallVectorImpl
Definition: LLVM.h:39
FileManager.h
clang::SrcMgr::C_System
@ C_System
Definition: SourceManager.h:80
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:130
clang::HeaderFileInfo::ControllingMacroID
unsigned ControllingMacroID
The ID number of the controlling macro.
Definition: HeaderSearch.h:100
clang::ModuleMap::setTarget
void setTarget(const TargetInfo &Target)
Set the target information.
Definition: ModuleMap.cpp:329
clang::FileManager::getVirtualFile
const FileEntry * getVirtualFile(StringRef Filename, off_t Size, time_t ModificationTime)
Definition: FileManager.cpp:372
clang::DirectoryLookup::getName
StringRef getName() const
getName - Return the directory or filename corresponding to this lookup object.
Definition: HeaderSearch.cpp:358
clang::HeaderSearch::getModuleMap
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:740
copyString
static const char * copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc)
Definition: HeaderSearch.cpp:714
getPrivateModuleMap
static const FileEntry * getPrivateModuleMap(const FileEntry *File, FileManager &FileMgr)
Definition: HeaderSearch.cpp:1550
clang::HeaderSearch::setTarget
void setTarget(const TargetInfo &Target)
Set the target information for the header search, if not already known.
Definition: HeaderSearch.cpp:693
clang::HeaderSearch::PrintStats
void PrintStats()
Definition: HeaderSearch.cpp:89
clang::Preprocessor::isMacroDefinedInLocalModule
bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M)
Determine whether II is defined as a macro within the module M, if that is a module that we've alread...
Definition: Preprocessor.h:1099
clang::DirectoryLookup::haveSearchedAllModuleMaps
bool haveSearchedAllModuleMaps() const
Determine whether we have already searched this entire directory for module maps.
Definition: DirectoryLookup.h:122
clang::FixItHint::CreateReplacement
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:133
clang::HeaderFileInfo::isCompilingModuleHeader
unsigned isCompilingModuleHeader
Whether this header is part of the module that we are building.
Definition: HeaderSearch.h:74
ExternalPreprocessorSource.h
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1523