1 //===--- HeaderSearch.h - Resolve Header File Locations ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the HeaderSearch interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
15 #define LLVM_CLANG_LEX_HEADERSEARCH_H
17 #include "clang/Lex/DirectoryLookup.h"
18 #include "clang/Lex/ModuleMap.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/IntrusiveRefCntPtr.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/Support/Allocator.h"
29 class DiagnosticsEngine;
30 class ExternalIdentifierLookup;
33 class HeaderSearchOptions;
37 /// \brief The preprocessor keeps track of this information for each
38 /// file that is \#included.
39 struct HeaderFileInfo {
40 /// \brief True if this is a \#import'd or \#pragma once file.
41 unsigned isImport : 1;
43 /// \brief True if this is a \#pragma once file.
44 unsigned isPragmaOnce : 1;
46 /// DirInfo - Keep track of whether this is a system header, and if so,
47 /// whether it is C++ clean or not. This can be set by the include paths or
48 /// by \#pragma gcc system_header. This is an instance of
49 /// SrcMgr::CharacteristicKind.
52 /// \brief Whether this header file info was supplied by an external source.
53 unsigned External : 1;
55 /// \brief Whether this header is part of a module.
56 unsigned isModuleHeader : 1;
58 /// \brief Whether this header is part of the module that we are building.
59 unsigned isCompilingModuleHeader : 1;
61 /// \brief Whether this header is part of the module that we are building.
62 /// This is an instance of ModuleMap::ModuleHeaderRole.
63 unsigned HeaderRole : 2;
65 /// \brief Whether this structure is considered to already have been
66 /// "resolved", meaning that it was loaded from the external source.
67 unsigned Resolved : 1;
69 /// \brief Whether this is a header inside a framework that is currently
72 /// When a framework is being built, the headers have not yet been placed
73 /// into the appropriate framework subdirectories, and therefore are
74 /// provided via a header map. This bit indicates when this is one of
75 /// those framework headers.
76 unsigned IndexHeaderMapHeader : 1;
78 /// \brief Whether this file had been looked up as a header.
81 /// \brief The number of times the file has been included already.
82 unsigned short NumIncludes;
84 /// \brief The ID number of the controlling macro.
86 /// This ID number will be non-zero when there is a controlling
87 /// macro whose IdentifierInfo may not yet have been loaded from
89 unsigned ControllingMacroID;
91 /// If this file has a \#ifndef XXX (or equivalent) guard that
92 /// protects the entire contents of the file, this is the identifier
93 /// for the macro that controls whether or not it has any effect.
95 /// Note: Most clients should use getControllingMacro() to access
96 /// the controlling macro of this header, since
97 /// getControllingMacro() is able to load a controlling macro from
99 const IdentifierInfo *ControllingMacro;
101 /// \brief If this header came from a framework include, this is the name
102 /// of the framework.
106 : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
107 External(false), isModuleHeader(false), isCompilingModuleHeader(false),
108 HeaderRole(ModuleMap::NormalHeader),
109 Resolved(false), IndexHeaderMapHeader(false), IsValid(0),
110 NumIncludes(0), ControllingMacroID(0), ControllingMacro(nullptr) {}
112 /// \brief Retrieve the controlling macro for this header file, if
114 const IdentifierInfo *getControllingMacro(ExternalIdentifierLookup *External);
116 /// \brief Determine whether this is a non-default header file info, e.g.,
117 /// it corresponds to an actual header we've included or tried to include.
118 bool isNonDefault() const {
119 return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
123 /// \brief Get the HeaderRole properly typed.
124 ModuleMap::ModuleHeaderRole getHeaderRole() const {
125 return static_cast<ModuleMap::ModuleHeaderRole>(HeaderRole);
128 /// \brief Set the HeaderRole properly typed.
129 void setHeaderRole(ModuleMap::ModuleHeaderRole Role) {
134 /// \brief An external source of header file information, which may supply
135 /// information about header files already included.
136 class ExternalHeaderFileInfoSource {
138 virtual ~ExternalHeaderFileInfoSource();
140 /// \brief Retrieve the header file information for the given file entry.
142 /// \returns Header file information for the given file entry, with the
143 /// \c External bit set. If the file entry is not known, return a
144 /// default-constructed \c HeaderFileInfo.
145 virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
148 /// \brief Encapsulates the information needed to find the file referenced
149 /// by a \#include or \#include_next, (sub-)framework lookup, etc.
151 /// This structure is used to record entries in our framework cache.
152 struct FrameworkCacheEntry {
153 /// The directory entry which should be used for the cached framework.
154 const DirectoryEntry *Directory;
156 /// Whether this framework has been "user-specified" to be treated as if it
157 /// were a system framework (even if it was found outside a system framework
159 bool IsUserSpecifiedSystemFramework;
162 /// \brief Header-search options used to initialize this header search.
163 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
165 DiagnosticsEngine &Diags;
166 FileManager &FileMgr;
167 /// \#include search path information. Requests for \#include "x" search the
168 /// directory of the \#including file first, then each directory in SearchDirs
169 /// consecutively. Requests for <x> search the current dir first, then each
170 /// directory in SearchDirs, starting at AngledDirIdx, consecutively. If
171 /// NoCurDirSearch is true, then the check for the file in the current
172 /// directory is suppressed.
173 std::vector<DirectoryLookup> SearchDirs;
174 unsigned AngledDirIdx;
175 unsigned SystemDirIdx;
178 /// \brief \#include prefixes for which the 'system header' property is
181 /// For a \#include "x" or \#include \<x> directive, the last string in this
182 /// list which is a prefix of 'x' determines whether the file is treated as
184 std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
186 /// \brief The path to the module cache.
187 std::string ModuleCachePath;
189 /// \brief All of the preprocessor-specific data about files that are
190 /// included, indexed by the FileEntry's UID.
191 std::vector<HeaderFileInfo> FileInfo;
193 /// Keeps track of each lookup performed by LookupFile.
194 struct LookupFileCacheInfo {
195 /// Starting index in SearchDirs that the cached search was performed from.
196 /// If there is a hit and this value doesn't match the current query, the
197 /// cache has to be ignored.
199 /// The entry in SearchDirs that satisfied the query.
201 /// This is non-null if the original filename was mapped to a framework
202 /// include via a headermap.
203 const char *MappedName;
205 /// Default constructor -- Initialize all members with zero.
206 LookupFileCacheInfo(): StartIdx(0), HitIdx(0), MappedName(nullptr) {}
208 void reset(unsigned StartIdx) {
209 this->StartIdx = StartIdx;
210 this->MappedName = nullptr;
213 llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
215 /// \brief Collection mapping a framework or subframework
216 /// name like "Carbon" to the Carbon.framework directory.
217 llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
219 /// IncludeAliases - maps include file names (including the quotes or
220 /// angle brackets) to other include file names. This is used to support the
221 /// include_alias pragma for Microsoft compatibility.
222 typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator>
224 std::unique_ptr<IncludeAliasMap> IncludeAliases;
226 /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
227 /// headermaps. This vector owns the headermap.
228 std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
230 /// \brief The mapping between modules and headers.
231 mutable ModuleMap ModMap;
233 /// \brief Describes whether a given directory has a module map in it.
234 llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
236 /// \brief Set of module map files we've already loaded, and a flag indicating
237 /// whether they were valid or not.
238 llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps;
240 /// \brief Uniqued set of framework names, which is used to track which
241 /// headers were included as framework headers.
242 llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
244 /// \brief Entity used to resolve the identifier IDs of controlling
245 /// macros into IdentifierInfo pointers, as needed.
246 ExternalIdentifierLookup *ExternalLookup;
248 /// \brief Entity used to look up stored header file information.
249 ExternalHeaderFileInfoSource *ExternalSource;
251 // Various statistics we track for performance analysis.
252 unsigned NumIncluded;
253 unsigned NumMultiIncludeFileOptzn;
254 unsigned NumFrameworkLookups, NumSubFrameworkLookups;
256 const LangOptions &LangOpts;
258 // HeaderSearch doesn't support default or copy construction.
259 HeaderSearch(const HeaderSearch&) = delete;
260 void operator=(const HeaderSearch&) = delete;
262 friend class DirectoryLookup;
265 HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
266 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
267 const LangOptions &LangOpts, const TargetInfo *Target);
270 /// \brief Retrieve the header-search options with which this header search
272 HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
274 FileManager &getFileMgr() const { return FileMgr; }
276 /// \brief Interface for setting the file search paths.
277 void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
278 unsigned angledDirIdx, unsigned systemDirIdx,
279 bool noCurDirSearch) {
280 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
281 "Directory indicies are unordered");
283 AngledDirIdx = angledDirIdx;
284 SystemDirIdx = systemDirIdx;
285 NoCurDirSearch = noCurDirSearch;
286 //LookupFileCache.clear();
289 /// \brief Add an additional search path.
290 void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
291 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
292 SearchDirs.insert(SearchDirs.begin() + idx, dir);
298 /// \brief Set the list of system header prefixes.
299 void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool> > P) {
300 SystemHeaderPrefixes.assign(P.begin(), P.end());
303 /// \brief Checks whether the map exists or not.
304 bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
306 /// \brief Map the source include name to the dest include name.
308 /// The Source should include the angle brackets or quotes, the dest
309 /// should not. This allows for distinction between <> and "" headers.
310 void AddIncludeAlias(StringRef Source, StringRef Dest) {
312 IncludeAliases.reset(new IncludeAliasMap);
313 (*IncludeAliases)[Source] = Dest;
316 /// MapHeaderToIncludeAlias - Maps one header file name to a different header
317 /// file name, for use with the include_alias pragma. Note that the source
318 /// file name should include the angle brackets or quotes. Returns StringRef
319 /// as null if the header cannot be mapped.
320 StringRef MapHeaderToIncludeAlias(StringRef Source) {
321 assert(IncludeAliases && "Trying to map headers when there's no map");
323 // Do any filename replacements before anything else
324 IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
325 if (Iter != IncludeAliases->end())
330 /// \brief Set the path to the module cache.
331 void setModuleCachePath(StringRef CachePath) {
332 ModuleCachePath = CachePath;
335 /// \brief Retrieve the path to the module cache.
336 StringRef getModuleCachePath() const { return ModuleCachePath; }
338 /// \brief Consider modules when including files from this directory.
339 void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
340 DirectoryHasModuleMap[Dir] = true;
343 /// \brief Forget everything we know about headers so far.
344 void ClearFileInfo() {
348 void SetExternalLookup(ExternalIdentifierLookup *EIL) {
349 ExternalLookup = EIL;
352 ExternalIdentifierLookup *getExternalLookup() const {
353 return ExternalLookup;
356 /// \brief Set the external source of header information.
357 void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
361 /// \brief Set the target information for the header search, if not
363 void setTarget(const TargetInfo &Target);
365 /// \brief Given a "foo" or \<foo> reference, look up the indicated file,
366 /// return null on failure.
368 /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
369 /// the file was found in, or null if not applicable.
371 /// \param IncludeLoc Used for diagnostics if valid.
373 /// \param isAngled indicates whether the file reference is a <> reference.
375 /// \param CurDir If non-null, the file was found in the specified directory
376 /// search location. This is used to implement \#include_next.
378 /// \param Includers Indicates where the \#including file(s) are, in case
379 /// relative searches are needed. In reverse order of inclusion.
381 /// \param SearchPath If non-null, will be set to the search path relative
382 /// to which the file was found. If the include path is absolute, SearchPath
383 /// will be set to an empty string.
385 /// \param RelativePath If non-null, will be set to the path relative to
386 /// SearchPath at which the file was found. This only differs from the
387 /// Filename for framework includes.
389 /// \param SuggestedModule If non-null, and the file found is semantically
390 /// part of a known module, this will be set to the module that should
391 /// be imported instead of preprocessing/parsing the file found.
392 const FileEntry *LookupFile(
393 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
394 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
395 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
396 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
397 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache = false);
399 /// \brief Look up a subframework for the specified \#include file.
401 /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
402 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
403 /// HIToolbox is a subframework within Carbon.framework. If so, return
404 /// the FileEntry for the designated file, otherwise return null.
405 const FileEntry *LookupSubframeworkHeader(
407 const FileEntry *RelativeFileEnt,
408 SmallVectorImpl<char> *SearchPath,
409 SmallVectorImpl<char> *RelativePath,
410 ModuleMap::KnownHeader *SuggestedModule);
412 /// \brief Look up the specified framework name in our framework cache.
413 /// \returns The DirectoryEntry it is in if we know, null otherwise.
414 FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
415 return FrameworkMap[FWName];
418 /// \brief Mark the specified file as a target of of a \#include,
419 /// \#include_next, or \#import directive.
421 /// \return false if \#including the file will have no effect or true
422 /// if we should include it.
423 bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File,
426 /// \brief Return whether the specified file is a normal header,
427 /// a system header, or a C++ friendly system header.
428 SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
429 return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
432 /// \brief Mark the specified file as a "once only" file, e.g. due to
434 void MarkFileIncludeOnce(const FileEntry *File) {
435 HeaderFileInfo &FI = getFileInfo(File);
437 FI.isPragmaOnce = true;
440 /// \brief Mark the specified file as a system header, e.g. due to
441 /// \#pragma GCC system_header.
442 void MarkFileSystemHeader(const FileEntry *File) {
443 getFileInfo(File).DirInfo = SrcMgr::C_System;
446 /// \brief Mark the specified file as part of a module.
447 void MarkFileModuleHeader(const FileEntry *File,
448 ModuleMap::ModuleHeaderRole Role,
449 bool IsCompiledModuleHeader);
451 /// \brief Increment the count for the number of times the specified
452 /// FileEntry has been entered.
453 void IncrementIncludeCount(const FileEntry *File) {
454 ++getFileInfo(File).NumIncludes;
457 /// \brief Mark the specified file as having a controlling macro.
459 /// This is used by the multiple-include optimization to eliminate
460 /// no-op \#includes.
461 void SetFileControllingMacro(const FileEntry *File,
462 const IdentifierInfo *ControllingMacro) {
463 getFileInfo(File).ControllingMacro = ControllingMacro;
466 /// \brief Return true if this is the first time encountering this header.
467 bool FirstTimeLexingFile(const FileEntry *File) {
468 return getFileInfo(File).NumIncludes == 1;
471 /// \brief Determine whether this file is intended to be safe from
472 /// multiple inclusions, e.g., it has \#pragma once or a controlling
475 /// This routine does not consider the effect of \#import
476 bool isFileMultipleIncludeGuarded(const FileEntry *File);
478 /// CreateHeaderMap - This method returns a HeaderMap for the specified
479 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
480 const HeaderMap *CreateHeaderMap(const FileEntry *FE);
482 /// \brief Retrieve the name of the module file that should be used to
483 /// load the given module.
485 /// \param Module The module whose module file name will be returned.
487 /// \returns The name of the module file that corresponds to this module,
488 /// or an empty string if this module does not correspond to any module file.
489 std::string getModuleFileName(Module *Module);
491 /// \brief Retrieve the name of the module file that should be used to
492 /// load a module with the given name.
494 /// \param ModuleName The module whose module file name will be returned.
496 /// \param ModuleMapPath A path that when combined with \c ModuleName
497 /// uniquely identifies this module. See Module::ModuleMap.
499 /// \returns The name of the module file that corresponds to this module,
500 /// or an empty string if this module does not correspond to any module file.
501 std::string getModuleFileName(StringRef ModuleName, StringRef ModuleMapPath);
503 /// \brief Lookup a module Search for a module with the given name.
505 /// \param ModuleName The name of the module we're looking for.
507 /// \param AllowSearch Whether we are allowed to search in the various
508 /// search directories to produce a module definition. If not, this lookup
509 /// will only return an already-known module.
511 /// \returns The module with the given name.
512 Module *lookupModule(StringRef ModuleName, bool AllowSearch = true);
514 /// \brief Try to find a module map file in the given directory, returning
515 /// \c nullptr if none is found.
516 const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir,
519 void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
521 /// \brief Determine whether there is a module map that may map the header
522 /// with the given file name to a (sub)module.
523 /// Always returns false if modules are disabled.
525 /// \param Filename The name of the file.
527 /// \param Root The "root" directory, at which we should stop looking for
530 /// \param IsSystem Whether the directories we're looking at are system
531 /// header directories.
532 bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root,
535 /// \brief Retrieve the module that corresponds to the given file, if any.
537 /// \param File The header that we wish to map to a module.
538 ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File) const;
540 /// \brief Read the contents of the given module map file.
542 /// \param File The module map file.
543 /// \param IsSystem Whether this file is in a system header directory.
545 /// \returns true if an error occurred, false otherwise.
546 bool loadModuleMapFile(const FileEntry *File, bool IsSystem);
548 /// \brief Collect the set of all known, top-level modules.
550 /// \param Modules Will be filled with the set of known, top-level modules.
551 void collectAllModules(SmallVectorImpl<Module *> &Modules);
553 /// \brief Load all known, top-level system modules.
554 void loadTopLevelSystemModules();
557 /// \brief Retrieve a module with the given name, which may be part of the
560 /// \param Name The name of the module to retrieve.
562 /// \param Dir The framework directory (e.g., ModuleName.framework).
564 /// \param IsSystem Whether the framework directory is part of the system
567 /// \returns The module, if found; otherwise, null.
568 Module *loadFrameworkModule(StringRef Name,
569 const DirectoryEntry *Dir,
572 /// \brief Load all of the module maps within the immediate subdirectories
573 /// of the given search directory.
574 void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
576 /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
577 const HeaderFileInfo &getFileInfo(const FileEntry *FE) const {
578 return const_cast<HeaderSearch*>(this)->getFileInfo(FE);
582 /// \brief Retrieve the module map.
583 ModuleMap &getModuleMap() { return ModMap; }
585 unsigned header_file_size() const { return FileInfo.size(); }
587 /// \brief Get a \c HeaderFileInfo structure for the specified \c FileEntry,
589 bool tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const;
591 // Used by external tools
592 typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
593 search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
594 search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
595 unsigned search_dir_size() const { return SearchDirs.size(); }
597 search_dir_iterator quoted_dir_begin() const {
598 return SearchDirs.begin();
600 search_dir_iterator quoted_dir_end() const {
601 return SearchDirs.begin() + AngledDirIdx;
604 search_dir_iterator angled_dir_begin() const {
605 return SearchDirs.begin() + AngledDirIdx;
607 search_dir_iterator angled_dir_end() const {
608 return SearchDirs.begin() + SystemDirIdx;
611 search_dir_iterator system_dir_begin() const {
612 return SearchDirs.begin() + SystemDirIdx;
614 search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
616 /// \brief Retrieve a uniqued framework name.
617 StringRef getUniqueFrameworkName(StringRef Framework);
621 size_t getTotalMemory() const;
623 static std::string NormalizeDashIncludePath(StringRef File,
624 FileManager &FileMgr);
627 /// \brief Describes what happened when we tried to load a module map file.
628 enum LoadModuleMapResult {
629 /// \brief The module map file had already been loaded.
631 /// \brief The module map file was loaded by this invocation.
633 /// \brief There is was directory with the given name.
635 /// \brief There was either no module map file or the module map file was
640 LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
642 const DirectoryEntry *Dir);
644 /// \brief Try to load the module map file in the given directory.
646 /// \param DirName The name of the directory where we will look for a module
648 /// \param IsSystem Whether this is a system header directory.
649 /// \param IsFramework Whether this is a framework directory.
651 /// \returns The result of attempting to load the module map file from the
653 LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem,
656 /// \brief Try to load the module map file in the given directory.
658 /// \param Dir The directory where we will look for a module map file.
659 /// \param IsSystem Whether this is a system header directory.
660 /// \param IsFramework Whether this is a framework directory.
662 /// \returns The result of attempting to load the module map file from the
664 LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir,
665 bool IsSystem, bool IsFramework);
667 /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
668 HeaderFileInfo &getFileInfo(const FileEntry *FE);
671 } // end namespace clang