Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Lex/HeaderSearch.h
Line
Count
Source (jump to first uncovered line)
1
//===- HeaderSearch.h - Resolve Header File Locations -----------*- C++ -*-===//
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 defines the HeaderSearch interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
14
#define LLVM_CLANG_LEX_HEADERSEARCH_H
15
16
#include "clang/Basic/SourceLocation.h"
17
#include "clang/Basic/SourceManager.h"
18
#include "clang/Lex/DirectoryLookup.h"
19
#include "clang/Lex/HeaderMap.h"
20
#include "clang/Lex/ModuleMap.h"
21
#include "llvm/ADT/ArrayRef.h"
22
#include "llvm/ADT/DenseMap.h"
23
#include "llvm/ADT/SetVector.h"
24
#include "llvm/ADT/SmallSet.h"
25
#include "llvm/ADT/SmallString.h"
26
#include "llvm/ADT/StringMap.h"
27
#include "llvm/ADT/StringRef.h"
28
#include "llvm/ADT/StringSet.h"
29
#include "llvm/Support/Allocator.h"
30
#include <cassert>
31
#include <cstddef>
32
#include <memory>
33
#include <string>
34
#include <utility>
35
#include <vector>
36
37
namespace llvm {
38
39
class Triple;
40
41
} // namespace llvm
42
43
namespace clang {
44
45
class DiagnosticsEngine;
46
class DirectoryEntry;
47
class ExternalPreprocessorSource;
48
class FileEntry;
49
class FileManager;
50
class HeaderSearchOptions;
51
class IdentifierInfo;
52
class LangOptions;
53
class Module;
54
class Preprocessor;
55
class TargetInfo;
56
57
/// The preprocessor keeps track of this information for each
58
/// file that is \#included.
59
struct HeaderFileInfo {
60
  /// True if this is a \#import'd file.
61
  unsigned isImport : 1;
62
63
  /// True if this is a \#pragma once file.
64
  unsigned isPragmaOnce : 1;
65
66
  /// Keep track of whether this is a system header, and if so,
67
  /// whether it is C++ clean or not.  This can be set by the include paths or
68
  /// by \#pragma gcc system_header.  This is an instance of
69
  /// SrcMgr::CharacteristicKind.
70
  unsigned DirInfo : 3;
71
72
  /// Whether this header file info was supplied by an external source,
73
  /// and has not changed since.
74
  unsigned External : 1;
75
76
  /// Whether this header is part of a module.
77
  unsigned isModuleHeader : 1;
78
79
  /// Whether this header is part of the module that we are building.
80
  unsigned isCompilingModuleHeader : 1;
81
82
  /// Whether this structure is considered to already have been
83
  /// "resolved", meaning that it was loaded from the external source.
84
  unsigned Resolved : 1;
85
86
  /// Whether this is a header inside a framework that is currently
87
  /// being built.
88
  ///
89
  /// When a framework is being built, the headers have not yet been placed
90
  /// into the appropriate framework subdirectories, and therefore are
91
  /// provided via a header map. This bit indicates when this is one of
92
  /// those framework headers.
93
  unsigned IndexHeaderMapHeader : 1;
94
95
  /// Whether this file has been looked up as a header.
96
  unsigned IsValid : 1;
97
98
  /// The number of times the file has been included already.
99
  unsigned short NumIncludes = 0;
100
101
  /// The ID number of the controlling macro.
102
  ///
103
  /// This ID number will be non-zero when there is a controlling
104
  /// macro whose IdentifierInfo may not yet have been loaded from
105
  /// external storage.
106
  unsigned ControllingMacroID = 0;
107
108
  /// If this file has a \#ifndef XXX (or equivalent) guard that
109
  /// protects the entire contents of the file, this is the identifier
110
  /// for the macro that controls whether or not it has any effect.
111
  ///
112
  /// Note: Most clients should use getControllingMacro() to access
113
  /// the controlling macro of this header, since
114
  /// getControllingMacro() is able to load a controlling macro from
115
  /// external storage.
116
  const IdentifierInfo *ControllingMacro = nullptr;
117
118
  /// If this header came from a framework include, this is the name
119
  /// of the framework.
120
  StringRef Framework;
121
122
  /// List of aliases that this header is known as.
123
  /// Most headers should only have at most one alias, but a handful
124
  /// have two.
125
  llvm::SetVector<llvm::SmallString<32>,
126
                  llvm::SmallVector<llvm::SmallString<32>, 2>,
127
                  llvm::SmallSet<llvm::SmallString<32>, 2>>
128
      Aliases;
129
130
  HeaderFileInfo()
131
      : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
132
        External(false), isModuleHeader(false), isCompilingModuleHeader(false),
133
2.95M
        Resolved(false), IndexHeaderMapHeader(false), IsValid(false)  {}
134
135
  /// Retrieve the controlling macro for this header file, if
136
  /// any.
137
  const IdentifierInfo *
138
  getControllingMacro(ExternalPreprocessorSource *External);
139
};
140
141
/// An external source of header file information, which may supply
142
/// information about header files already included.
143
class ExternalHeaderFileInfoSource {
144
public:
145
  virtual ~ExternalHeaderFileInfoSource();
146
147
  /// Retrieve the header file information for the given file entry.
148
  ///
149
  /// \returns Header file information for the given file entry, with the
150
  /// \c External bit set. If the file entry is not known, return a
151
  /// default-constructed \c HeaderFileInfo.
152
  virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
153
};
154
155
/// This structure is used to record entries in our framework cache.
156
struct FrameworkCacheEntry {
157
  /// The directory entry which should be used for the cached framework.
158
  const DirectoryEntry *Directory;
159
160
  /// Whether this framework has been "user-specified" to be treated as if it
161
  /// were a system framework (even if it was found outside a system framework
162
  /// directory).
163
  bool IsUserSpecifiedSystemFramework;
164
};
165
166
/// Encapsulates the information needed to find the file referenced
167
/// by a \#include or \#include_next, (sub-)framework lookup, etc.
168
class HeaderSearch {
169
  friend class DirectoryLookup;
170
171
  /// Header-search options used to initialize this header search.
172
  std::shared_ptr<HeaderSearchOptions> HSOpts;
173
174
  /// Mapping from SearchDir to HeaderSearchOptions::UserEntries indices.
175
  llvm::DenseMap<unsigned, unsigned> SearchDirToHSEntry;
176
177
  DiagnosticsEngine &Diags;
178
  FileManager &FileMgr;
179
180
  /// \#include search path information.  Requests for \#include "x" search the
181
  /// directory of the \#including file first, then each directory in SearchDirs
182
  /// consecutively. Requests for <x> search the current dir first, then each
183
  /// directory in SearchDirs, starting at AngledDirIdx, consecutively.  If
184
  /// NoCurDirSearch is true, then the check for the file in the current
185
  /// directory is suppressed.
186
  std::vector<DirectoryLookup> SearchDirs;
187
  /// Whether the DirectoryLookup at the corresponding index in SearchDirs has
188
  /// been successfully used to lookup a file.
189
  std::vector<bool> SearchDirsUsage;
190
  unsigned AngledDirIdx = 0;
191
  unsigned SystemDirIdx = 0;
192
  bool NoCurDirSearch = false;
193
194
  /// \#include prefixes for which the 'system header' property is
195
  /// overridden.
196
  ///
197
  /// For a \#include "x" or \#include \<x> directive, the last string in this
198
  /// list which is a prefix of 'x' determines whether the file is treated as
199
  /// a system header.
200
  std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes;
201
202
  /// The hash used for module cache paths.
203
  std::string ModuleHash;
204
205
  /// The path to the module cache.
206
  std::string ModuleCachePath;
207
208
  /// All of the preprocessor-specific data about files that are
209
  /// included, indexed by the FileEntry's UID.
210
  mutable std::vector<HeaderFileInfo> FileInfo;
211
212
  /// Keeps track of each lookup performed by LookupFile.
213
  struct LookupFileCacheInfo {
214
    /// Starting index in SearchDirs that the cached search was performed from.
215
    /// If there is a hit and this value doesn't match the current query, the
216
    /// cache has to be ignored.
217
    unsigned StartIdx = 0;
218
219
    /// The entry in SearchDirs that satisfied the query.
220
    unsigned HitIdx = 0;
221
222
    /// This is non-null if the original filename was mapped to a framework
223
    /// include via a headermap.
224
    const char *MappedName = nullptr;
225
226
    /// Default constructor -- Initialize all members with zero.
227
464k
    LookupFileCacheInfo() = default;
228
229
481k
    void reset(unsigned StartIdx) {
230
481k
      this->StartIdx = StartIdx;
231
481k
      this->MappedName = nullptr;
232
481k
    }
233
  };
234
  llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
235
236
  /// Collection mapping a framework or subframework
237
  /// name like "Carbon" to the Carbon.framework directory.
238
  llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
239
240
  /// Maps include file names (including the quotes or
241
  /// angle brackets) to other include file names.  This is used to support the
242
  /// include_alias pragma for Microsoft compatibility.
243
  using IncludeAliasMap =
244
      llvm::StringMap<std::string, llvm::BumpPtrAllocator>;
245
  std::unique_ptr<IncludeAliasMap> IncludeAliases;
246
247
  /// This is a mapping from FileEntry -> HeaderMap, uniquing headermaps.
248
  std::vector<std::pair<const FileEntry *, std::unique_ptr<HeaderMap>>> HeaderMaps;
249
250
  /// The mapping between modules and headers.
251
  mutable ModuleMap ModMap;
252
253
  /// Describes whether a given directory has a module map in it.
254
  llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
255
256
  /// Set of module map files we've already loaded, and a flag indicating
257
  /// whether they were valid or not.
258
  llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps;
259
260
  /// Uniqued set of framework names, which is used to track which
261
  /// headers were included as framework headers.
262
  llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
263
264
  /// Entity used to resolve the identifier IDs of controlling
265
  /// macros into IdentifierInfo pointers, and keep the identifire up to date,
266
  /// as needed.
267
  ExternalPreprocessorSource *ExternalLookup = nullptr;
268
269
  /// Entity used to look up stored header file information.
270
  ExternalHeaderFileInfoSource *ExternalSource = nullptr;
271
272
public:
273
  HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
274
               SourceManager &SourceMgr, DiagnosticsEngine &Diags,
275
               const LangOptions &LangOpts, const TargetInfo *Target);
276
  HeaderSearch(const HeaderSearch &) = delete;
277
  HeaderSearch &operator=(const HeaderSearch &) = delete;
278
279
  /// Retrieve the header-search options with which this header search
280
  /// was initialized.
281
6.66M
  HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
282
283
3.91M
  FileManager &getFileMgr() const { return FileMgr; }
284
285
33
  DiagnosticsEngine &getDiags() const { return Diags; }
286
287
  /// Interface for setting the file search paths.
288
  void SetSearchPaths(std::vector<DirectoryLookup> dirs, unsigned angledDirIdx,
289
                      unsigned systemDirIdx, bool noCurDirSearch,
290
                      llvm::DenseMap<unsigned, unsigned> searchDirToHSEntry);
291
292
  /// Add an additional search path.
293
  void AddSearchPath(const DirectoryLookup &dir, bool isAngled);
294
295
  /// Add an additional system search path.
296
  void AddSystemSearchPath(const DirectoryLookup &dir) {
297
    SearchDirs.push_back(dir);
298
    SearchDirsUsage.push_back(false);
299
  }
300
301
  /// Set the list of system header prefixes.
302
87.6k
  void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) {
303
87.6k
    SystemHeaderPrefixes.assign(P.begin(), P.end());
304
87.6k
  }
305
306
  /// Checks whether the map exists or not.
307
1.66M
  bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
308
309
  /// Map the source include name to the dest include name.
310
  ///
311
  /// The Source should include the angle brackets or quotes, the dest
312
  /// should not.  This allows for distinction between <> and "" headers.
313
16
  void AddIncludeAlias(StringRef Source, StringRef Dest) {
314
16
    if (!IncludeAliases)
315
4
      IncludeAliases.reset(new IncludeAliasMap);
316
16
    (*IncludeAliases)[Source] = std::string(Dest);
317
16
  }
318
319
  /// Maps one header file name to a different header
320
  /// file name, for use with the include_alias pragma.  Note that the source
321
  /// file name should include the angle brackets or quotes.  Returns StringRef
322
  /// as null if the header cannot be mapped.
323
10
  StringRef MapHeaderToIncludeAlias(StringRef Source) {
324
10
    assert(IncludeAliases && "Trying to map headers when there's no map");
325
326
    // Do any filename replacements before anything else
327
0
    IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
328
10
    if (Iter != IncludeAliases->end())
329
8
      return Iter->second;
330
2
    return {};
331
10
  }
332
333
  /// Set the hash to use for module cache paths.
334
6.89k
  void setModuleHash(StringRef Hash) { ModuleHash = std::string(Hash); }
335
336
  /// Set the path to the module cache.
337
6.89k
  void setModuleCachePath(StringRef CachePath) {
338
6.89k
    ModuleCachePath = std::string(CachePath);
339
6.89k
  }
340
341
  /// Retrieve the module hash.
342
3
  StringRef getModuleHash() const { return ModuleHash; }
343
344
  /// Retrieve the path to the module cache.
345
27.4k
  StringRef getModuleCachePath() const { return ModuleCachePath; }
346
347
  /// Consider modules when including files from this directory.
348
0
  void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
349
0
    DirectoryHasModuleMap[Dir] = true;
350
0
  }
351
352
  /// Forget everything we know about headers so far.
353
0
  void ClearFileInfo() {
354
0
    FileInfo.clear();
355
0
  }
356
357
7.23k
  void SetExternalLookup(ExternalPreprocessorSource *EPS) {
358
7.23k
    ExternalLookup = EPS;
359
7.23k
  }
360
361
17.9k
  ExternalPreprocessorSource *getExternalLookup() const {
362
17.9k
    return ExternalLookup;
363
17.9k
  }
364
365
  /// Set the external source of header information.
366
17.9k
  void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
367
17.9k
    ExternalSource = ES;
368
17.9k
  }
369
370
  /// Set the target information for the header search, if not
371
  /// already known.
372
  void setTarget(const TargetInfo &Target);
373
374
  /// Given a "foo" or \<foo> reference, look up the indicated file,
375
  /// return null on failure.
376
  ///
377
  /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
378
  /// the file was found in, or null if not applicable.
379
  ///
380
  /// \param IncludeLoc Used for diagnostics if valid.
381
  ///
382
  /// \param isAngled indicates whether the file reference is a <> reference.
383
  ///
384
  /// \param CurDir If non-null, the file was found in the specified directory
385
  /// search location.  This is used to implement \#include_next.
386
  ///
387
  /// \param Includers Indicates where the \#including file(s) are, in case
388
  /// relative searches are needed. In reverse order of inclusion.
389
  ///
390
  /// \param SearchPath If non-null, will be set to the search path relative
391
  /// to which the file was found. If the include path is absolute, SearchPath
392
  /// will be set to an empty string.
393
  ///
394
  /// \param RelativePath If non-null, will be set to the path relative to
395
  /// SearchPath at which the file was found. This only differs from the
396
  /// Filename for framework includes.
397
  ///
398
  /// \param SuggestedModule If non-null, and the file found is semantically
399
  /// part of a known module, this will be set to the module that should
400
  /// be imported instead of preprocessing/parsing the file found.
401
  ///
402
  /// \param IsMapped If non-null, and the search involved header maps, set to
403
  /// true.
404
  ///
405
  /// \param IsFrameworkFound If non-null, will be set to true if a framework is
406
  /// found in any of searched SearchDirs. Will be set to false if a framework
407
  /// is found only through header maps. Doesn't guarantee the requested file is
408
  /// found.
409
  Optional<FileEntryRef> LookupFile(
410
      StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
411
      const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
412
      ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
413
      SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
414
      Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
415
      bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
416
      bool BuildSystemModule = false);
417
418
  /// Look up a subframework for the specified \#include file.
419
  ///
420
  /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
421
  /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
422
  /// HIToolbox is a subframework within Carbon.framework.  If so, return
423
  /// the FileEntry for the designated file, otherwise return null.
424
  Optional<FileEntryRef> LookupSubframeworkHeader(
425
      StringRef Filename, const FileEntry *ContextFileEnt,
426
      SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
427
      Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule);
428
429
  /// Look up the specified framework name in our framework cache.
430
  /// \returns The DirectoryEntry it is in if we know, null otherwise.
431
340k
  FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
432
340k
    return FrameworkMap[FWName];
433
340k
  }
434
435
  /// Mark the specified file as a target of a \#include,
436
  /// \#include_next, or \#import directive.
437
  ///
438
  /// \return false if \#including the file will have no effect or true
439
  /// if we should include it.
440
  bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File,
441
                              bool isImport, bool ModulesEnabled, Module *M,
442
                              bool &IsFirstIncludeOfFile);
443
444
  /// Return whether the specified file is a normal header,
445
  /// a system header, or a C++ friendly system header.
446
1.67M
  SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
447
1.67M
    return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
448
1.67M
  }
449
450
  /// Mark the specified file as a "once only" file due to
451
  /// \#pragma once.
452
270
  void MarkFileIncludeOnce(const FileEntry *File) {
453
270
    HeaderFileInfo &FI = getFileInfo(File);
454
270
    FI.isPragmaOnce = true;
455
270
  }
456
457
  /// Mark the specified file as a system header, e.g. due to
458
  /// \#pragma GCC system_header.
459
131k
  void MarkFileSystemHeader(const FileEntry *File) {
460
131k
    getFileInfo(File).DirInfo = SrcMgr::C_System;
461
131k
  }
462
463
14
  void AddFileAlias(const FileEntry *File, StringRef Alias) {
464
14
    getFileInfo(File).Aliases.insert(Alias);
465
14
  }
466
467
  /// Mark the specified file as part of a module.
468
  void MarkFileModuleHeader(const FileEntry *FE,
469
                            ModuleMap::ModuleHeaderRole Role,
470
                            bool isCompilingModuleHeader);
471
472
  /// Increment the count for the number of times the specified
473
  /// FileEntry has been entered.
474
76.3k
  void IncrementIncludeCount(const FileEntry *File) {
475
76.3k
    ++getFileInfo(File).NumIncludes;
476
76.3k
  }
477
478
  /// Mark the specified file as having a controlling macro.
479
  ///
480
  /// This is used by the multiple-include optimization to eliminate
481
  /// no-op \#includes.
482
  void SetFileControllingMacro(const FileEntry *File,
483
403k
                               const IdentifierInfo *ControllingMacro) {
484
403k
    getFileInfo(File).ControllingMacro = ControllingMacro;
485
403k
  }
486
487
  /// Determine whether this file is intended to be safe from
488
  /// multiple inclusions, e.g., it has \#pragma once or a controlling
489
  /// macro.
490
  ///
491
  /// This routine does not consider the effect of \#import
492
  bool isFileMultipleIncludeGuarded(const FileEntry *File);
493
494
  /// Determine whether the given file is known to have ever been \#imported.
495
2
  bool hasFileBeenImported(const FileEntry *File) {
496
2
    const HeaderFileInfo *FI = getExistingFileInfo(File);
497
2
    return FI && FI->isImport;
498
2
  }
499
500
  /// Determine which HeaderSearchOptions::UserEntries have been successfully
501
  /// used so far and mark their index with 'true' in the resulting bit vector.
502
  std::vector<bool> computeUserEntryUsage() const;
503
504
  /// This method returns a HeaderMap for the specified
505
  /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
506
  const HeaderMap *CreateHeaderMap(const FileEntry *FE);
507
508
  /// Get filenames for all registered header maps.
509
  void getHeaderMapFileNames(SmallVectorImpl<std::string> &Names) const;
510
511
  /// Retrieve the name of the cached module file that should be used
512
  /// to load the given module.
513
  ///
514
  /// \param Module The module whose module file name will be returned.
515
  ///
516
  /// \returns The name of the module file that corresponds to this module,
517
  /// or an empty string if this module does not correspond to any module file.
518
  std::string getCachedModuleFileName(Module *Module);
519
520
  /// Retrieve the name of the prebuilt module file that should be used
521
  /// to load a module with the given name.
522
  ///
523
  /// \param ModuleName The module whose module file name will be returned.
524
  ///
525
  /// \param FileMapOnly If true, then only look in the explicit module name
526
  //  to file name map and skip the directory search.
527
  ///
528
  /// \returns The name of the module file that corresponds to this module,
529
  /// or an empty string if this module does not correspond to any module file.
530
  std::string getPrebuiltModuleFileName(StringRef ModuleName,
531
                                        bool FileMapOnly = false);
532
533
  /// Retrieve the name of the prebuilt module file that should be used
534
  /// to load the given module.
535
  ///
536
  /// \param Module The module whose module file name will be returned.
537
  ///
538
  /// \returns The name of the module file that corresponds to this module,
539
  /// or an empty string if this module does not correspond to any module file.
540
  std::string getPrebuiltImplicitModuleFileName(Module *Module);
541
542
  /// Retrieve the name of the (to-be-)cached module file that should
543
  /// be used to load a module with the given name.
544
  ///
545
  /// \param ModuleName The module whose module file name will be returned.
546
  ///
547
  /// \param ModuleMapPath A path that when combined with \c ModuleName
548
  /// uniquely identifies this module. See Module::ModuleMap.
549
  ///
550
  /// \returns The name of the module file that corresponds to this module,
551
  /// or an empty string if this module does not correspond to any module file.
552
  std::string getCachedModuleFileName(StringRef ModuleName,
553
                                      StringRef ModuleMapPath);
554
555
  /// Lookup a module Search for a module with the given name.
556
  ///
557
  /// \param ModuleName The name of the module we're looking for.
558
  ///
559
  /// \param ImportLoc Location of the module include/import.
560
  ///
561
  /// \param AllowSearch Whether we are allowed to search in the various
562
  /// search directories to produce a module definition. If not, this lookup
563
  /// will only return an already-known module.
564
  ///
565
  /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
566
  /// in subdirectories.
567
  ///
568
  /// \returns The module with the given name.
569
  Module *lookupModule(StringRef ModuleName,
570
                       SourceLocation ImportLoc = SourceLocation(),
571
                       bool AllowSearch = true,
572
                       bool AllowExtraModuleMapSearch = false);
573
574
  /// Try to find a module map file in the given directory, returning
575
  /// \c nullptr if none is found.
576
  const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir,
577
                                       bool IsFramework);
578
579
  /// Determine whether there is a module map that may map the header
580
  /// with the given file name to a (sub)module.
581
  /// Always returns false if modules are disabled.
582
  ///
583
  /// \param Filename The name of the file.
584
  ///
585
  /// \param Root The "root" directory, at which we should stop looking for
586
  /// module maps.
587
  ///
588
  /// \param IsSystem Whether the directories we're looking at are system
589
  /// header directories.
590
  bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root,
591
                    bool IsSystem);
592
593
  /// Retrieve the module that corresponds to the given file, if any.
594
  ///
595
  /// \param File The header that we wish to map to a module.
596
  /// \param AllowTextual Whether we want to find textual headers too.
597
  ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File,
598
                                             bool AllowTextual = false) const;
599
600
  /// Retrieve all the modules corresponding to the given file.
601
  ///
602
  /// \ref findModuleForHeader should typically be used instead of this.
603
  ArrayRef<ModuleMap::KnownHeader>
604
  findAllModulesForHeader(const FileEntry *File) const;
605
606
  /// Read the contents of the given module map file.
607
  ///
608
  /// \param File The module map file.
609
  /// \param IsSystem Whether this file is in a system header directory.
610
  /// \param ID If the module map file is already mapped (perhaps as part of
611
  ///        processing a preprocessed module), the ID of the file.
612
  /// \param Offset [inout] An offset within ID to start parsing. On exit,
613
  ///        filled by the end of the parsed contents (either EOF or the
614
  ///        location of an end-of-module-map pragma).
615
  /// \param OriginalModuleMapFile The original path to the module map file,
616
  ///        used to resolve paths within the module (this is required when
617
  ///        building the module from preprocessed source).
618
  /// \returns true if an error occurred, false otherwise.
619
  bool loadModuleMapFile(const FileEntry *File, bool IsSystem,
620
                         FileID ID = FileID(), unsigned *Offset = nullptr,
621
                         StringRef OriginalModuleMapFile = StringRef());
622
623
  /// Collect the set of all known, top-level modules.
624
  ///
625
  /// \param Modules Will be filled with the set of known, top-level modules.
626
  void collectAllModules(SmallVectorImpl<Module *> &Modules);
627
628
  /// Load all known, top-level system modules.
629
  void loadTopLevelSystemModules();
630
631
private:
632
  /// Lookup a module with the given module name and search-name.
633
  ///
634
  /// \param ModuleName The name of the module we're looking for.
635
  ///
636
  /// \param SearchName The "search-name" to derive filesystem paths from
637
  /// when looking for the module map; this is usually equal to ModuleName,
638
  /// but for compatibility with some buggy frameworks, additional attempts
639
  /// may be made to find the module under a related-but-different search-name.
640
  ///
641
  /// \param ImportLoc Location of the module include/import.
642
  ///
643
  /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
644
  /// in subdirectories.
645
  ///
646
  /// \returns The module named ModuleName.
647
  Module *lookupModule(StringRef ModuleName, StringRef SearchName,
648
                       SourceLocation ImportLoc,
649
                       bool AllowExtraModuleMapSearch = false);
650
651
  /// Retrieve the name of the (to-be-)cached module file that should
652
  /// be used to load a module with the given name.
653
  ///
654
  /// \param ModuleName The module whose module file name will be returned.
655
  ///
656
  /// \param ModuleMapPath A path that when combined with \c ModuleName
657
  /// uniquely identifies this module. See Module::ModuleMap.
658
  ///
659
  /// \param CachePath A path to the module cache.
660
  ///
661
  /// \returns The name of the module file that corresponds to this module,
662
  /// or an empty string if this module does not correspond to any module file.
663
  std::string getCachedModuleFileNameImpl(StringRef ModuleName,
664
                                          StringRef ModuleMapPath,
665
                                          StringRef CachePath);
666
667
  /// Retrieve a module with the given name, which may be part of the
668
  /// given framework.
669
  ///
670
  /// \param Name The name of the module to retrieve.
671
  ///
672
  /// \param Dir The framework directory (e.g., ModuleName.framework).
673
  ///
674
  /// \param IsSystem Whether the framework directory is part of the system
675
  /// frameworks.
676
  ///
677
  /// \returns The module, if found; otherwise, null.
678
  Module *loadFrameworkModule(StringRef Name,
679
                              const DirectoryEntry *Dir,
680
                              bool IsSystem);
681
682
  /// Load all of the module maps within the immediate subdirectories
683
  /// of the given search directory.
684
  void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
685
686
  /// Find and suggest a usable module for the given file.
687
  ///
688
  /// \return \c true if the file can be used, \c false if we are not permitted to
689
  ///         find this file due to requirements from \p RequestingModule.
690
  bool findUsableModuleForHeader(const FileEntry *File,
691
                                 const DirectoryEntry *Root,
692
                                 Module *RequestingModule,
693
                                 ModuleMap::KnownHeader *SuggestedModule,
694
                                 bool IsSystemHeaderDir);
695
696
  /// Find and suggest a usable module for the given file, which is part of
697
  /// the specified framework.
698
  ///
699
  /// \return \c true if the file can be used, \c false if we are not permitted to
700
  ///         find this file due to requirements from \p RequestingModule.
701
  bool findUsableModuleForFrameworkHeader(
702
      const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
703
      ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework);
704
705
  /// Look up the file with the specified name and determine its owning
706
  /// module.
707
  Optional<FileEntryRef>
708
  getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc,
709
                          const DirectoryEntry *Dir, bool IsSystemHeaderDir,
710
                          Module *RequestingModule,
711
                          ModuleMap::KnownHeader *SuggestedModule);
712
713
  /// Cache the result of a successful lookup at the given include location
714
  /// using the search path at index `HitIdx`.
715
  void cacheLookupSuccess(LookupFileCacheInfo &CacheLookup, unsigned HitIdx,
716
                          SourceLocation IncludeLoc);
717
  /// Note that a lookup at the given include location was successful using the
718
  /// search path at index `HitIdx`.
719
  void noteLookupUsage(unsigned HitIdx, SourceLocation IncludeLoc);
720
721
public:
722
  /// Retrieve the module map.
723
3.64M
  ModuleMap &getModuleMap() { return ModMap; }
724
725
  /// Retrieve the module map.
726
183k
  const ModuleMap &getModuleMap() const { return ModMap; }
727
728
9.17k
  unsigned header_file_size() const { return FileInfo.size(); }
729
730
  /// Return the HeaderFileInfo structure for the specified FileEntry,
731
  /// in preparation for updating it in some way.
732
  HeaderFileInfo &getFileInfo(const FileEntry *FE);
733
734
  /// Return the HeaderFileInfo structure for the specified FileEntry,
735
  /// if it has ever been filled in.
736
  /// \param WantExternal Whether the caller wants purely-external header file
737
  ///        info (where \p External is true).
738
  const HeaderFileInfo *getExistingFileInfo(const FileEntry *FE,
739
                                            bool WantExternal = true) const;
740
741
  // Used by external tools
742
  using search_dir_iterator = std::vector<DirectoryLookup>::const_iterator;
743
744
1
  search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
745
1
  search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
746
  unsigned search_dir_size() const { return SearchDirs.size(); }
747
748
5
  search_dir_iterator quoted_dir_begin() const {
749
5
    return SearchDirs.begin();
750
5
  }
751
752
5
  search_dir_iterator quoted_dir_end() const {
753
5
    return SearchDirs.begin() + AngledDirIdx;
754
5
  }
755
756
14
  search_dir_iterator angled_dir_begin() const {
757
14
    return SearchDirs.begin() + AngledDirIdx;
758
14
  }
759
760
14
  search_dir_iterator angled_dir_end() const {
761
14
    return SearchDirs.begin() + SystemDirIdx;
762
14
  }
763
764
14
  search_dir_iterator system_dir_begin() const {
765
14
    return SearchDirs.begin() + SystemDirIdx;
766
14
  }
767
768
14
  search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
769
770
  /// Get the index of the given search directory.
771
  Optional<unsigned> searchDirIdx(const DirectoryLookup &DL) const;
772
773
  /// Retrieve a uniqued framework name.
774
  StringRef getUniqueFrameworkName(StringRef Framework);
775
776
  /// Suggest a path by which the specified file could be found, for use in
777
  /// diagnostics to suggest a #include. Returned path will only contain forward
778
  /// slashes as separators. MainFile is the absolute path of the file that we
779
  /// are generating the diagnostics for. It will try to shorten the path using
780
  /// MainFile location, if none of the include search directories were prefix
781
  /// of File.
782
  ///
783
  /// \param IsSystem If non-null, filled in to indicate whether the suggested
784
  ///        path is relative to a system header directory.
785
  std::string suggestPathToFileForDiagnostics(const FileEntry *File,
786
                                              llvm::StringRef MainFile,
787
                                              bool *IsSystem = nullptr);
788
789
  /// Suggest a path by which the specified file could be found, for use in
790
  /// diagnostics to suggest a #include. Returned path will only contain forward
791
  /// slashes as separators. MainFile is the absolute path of the file that we
792
  /// are generating the diagnostics for. It will try to shorten the path using
793
  /// MainFile location, if none of the include search directories were prefix
794
  /// of File.
795
  ///
796
  /// \param WorkingDir If non-empty, this will be prepended to search directory
797
  /// paths that are relative.
798
  std::string suggestPathToFileForDiagnostics(llvm::StringRef File,
799
                                              llvm::StringRef WorkingDir,
800
                                              llvm::StringRef MainFile,
801
                                              bool *IsSystem = nullptr);
802
803
  void PrintStats();
804
805
  size_t getTotalMemory() const;
806
807
private:
808
  /// Describes what happened when we tried to load a module map file.
809
  enum LoadModuleMapResult {
810
    /// The module map file had already been loaded.
811
    LMM_AlreadyLoaded,
812
813
    /// The module map file was loaded by this invocation.
814
    LMM_NewlyLoaded,
815
816
    /// There is was directory with the given name.
817
    LMM_NoDirectory,
818
819
    /// There was either no module map file or the module map file was
820
    /// invalid.
821
    LMM_InvalidModuleMap
822
  };
823
824
  LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
825
                                            bool IsSystem,
826
                                            const DirectoryEntry *Dir,
827
                                            FileID ID = FileID(),
828
                                            unsigned *Offset = nullptr);
829
830
  /// Try to load the module map file in the given directory.
831
  ///
832
  /// \param DirName The name of the directory where we will look for a module
833
  /// map file.
834
  /// \param IsSystem Whether this is a system header directory.
835
  /// \param IsFramework Whether this is a framework directory.
836
  ///
837
  /// \returns The result of attempting to load the module map file from the
838
  /// named directory.
839
  LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem,
840
                                        bool IsFramework);
841
842
  /// Try to load the module map file in the given directory.
843
  ///
844
  /// \param Dir The directory where we will look for a module map file.
845
  /// \param IsSystem Whether this is a system header directory.
846
  /// \param IsFramework Whether this is a framework directory.
847
  ///
848
  /// \returns The result of attempting to load the module map file from the
849
  /// named directory.
850
  LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir,
851
                                        bool IsSystem, bool IsFramework);
852
};
853
854
/// Apply the header search options to get given HeaderSearch object.
855
void ApplyHeaderSearchOptions(HeaderSearch &HS,
856
                              const HeaderSearchOptions &HSOpts,
857
                              const LangOptions &Lang,
858
                              const llvm::Triple &triple);
859
860
} // namespace clang
861
862
#endif // LLVM_CLANG_LEX_HEADERSEARCH_H