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;
36 /// \brief The preprocessor keeps track of this information for each
37 /// file that is \#included.
38 struct HeaderFileInfo {
39 /// \brief True if this is a \#import'd or \#pragma once file.
40 unsigned isImport : 1;
42 /// \brief True if this is a \#pragma once file.
43 unsigned isPragmaOnce : 1;
45 /// DirInfo - Keep track of whether this is a system header, and if so,
46 /// whether it is C++ clean or not. This can be set by the include paths or
47 /// by \#pragma gcc system_header. This is an instance of
48 /// SrcMgr::CharacteristicKind.
51 /// \brief Whether this header file info was supplied by an external source.
52 unsigned External : 1;
54 /// \brief Whether this header is part of a module.
55 unsigned isModuleHeader : 1;
57 /// \brief Whether this header is part of the module that we are building.
58 unsigned isCompilingModuleHeader : 1;
60 /// \brief Whether this header is part of the module that we are building.
61 /// This is an instance of ModuleMap::ModuleHeaderRole.
62 unsigned HeaderRole : 2;
64 /// \brief Whether this structure is considered to already have been
65 /// "resolved", meaning that it was loaded from the external source.
66 unsigned Resolved : 1;
68 /// \brief Whether this is a header inside a framework that is currently
71 /// When a framework is being built, the headers have not yet been placed
72 /// into the appropriate framework subdirectories, and therefore are
73 /// provided via a header map. This bit indicates when this is one of
74 /// those framework headers.
75 unsigned IndexHeaderMapHeader : 1;
77 /// \brief Whether this file had been looked up as a header.
80 /// \brief The number of times the file has been included already.
81 unsigned short NumIncludes;
83 /// \brief The ID number of the controlling macro.
85 /// This ID number will be non-zero when there is a controlling
86 /// macro whose IdentifierInfo may not yet have been loaded from
88 unsigned ControllingMacroID;
90 /// If this file has a \#ifndef XXX (or equivalent) guard that
91 /// protects the entire contents of the file, this is the identifier
92 /// for the macro that controls whether or not it has any effect.
94 /// Note: Most clients should use getControllingMacro() to access
95 /// the controlling macro of this header, since
96 /// getControllingMacro() is able to load a controlling macro from
98 const IdentifierInfo *ControllingMacro;
100 /// \brief If this header came from a framework include, this is the name
101 /// of the framework.
105 : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
106 External(false), isModuleHeader(false), isCompilingModuleHeader(false),
107 HeaderRole(ModuleMap::NormalHeader),
108 Resolved(false), IndexHeaderMapHeader(false), IsValid(0),
109 NumIncludes(0), ControllingMacroID(0), ControllingMacro(nullptr) {}
111 /// \brief Retrieve the controlling macro for this header file, if
113 const IdentifierInfo *getControllingMacro(ExternalIdentifierLookup *External);
115 /// \brief Determine whether this is a non-default header file info, e.g.,
116 /// it corresponds to an actual header we've included or tried to include.
117 bool isNonDefault() const {
118 return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
122 /// \brief Get the HeaderRole properly typed.
123 ModuleMap::ModuleHeaderRole getHeaderRole() const {
124 return static_cast<ModuleMap::ModuleHeaderRole>(HeaderRole);
127 /// \brief Set the HeaderRole properly typed.
128 void setHeaderRole(ModuleMap::ModuleHeaderRole Role) {
133 /// \brief An external source of header file information, which may supply
134 /// information about header files already included.
135 class ExternalHeaderFileInfoSource {
137 virtual ~ExternalHeaderFileInfoSource();
139 /// \brief Retrieve the header file information for the given file entry.
141 /// \returns Header file information for the given file entry, with the
142 /// \c External bit set. If the file entry is not known, return a
143 /// default-constructed \c HeaderFileInfo.
144 virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
147 /// \brief Encapsulates the information needed to find the file referenced
148 /// by a \#include or \#include_next, (sub-)framework lookup, etc.
150 /// This structure is used to record entries in our framework cache.
151 struct FrameworkCacheEntry {
152 /// The directory entry which should be used for the cached framework.
153 const DirectoryEntry *Directory;
155 /// Whether this framework has been "user-specified" to be treated as if it
156 /// were a system framework (even if it was found outside a system framework
158 bool IsUserSpecifiedSystemFramework;
161 /// \brief Header-search options used to initialize this header search.
162 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
164 DiagnosticsEngine &Diags;
165 FileManager &FileMgr;
166 /// \#include search path information. Requests for \#include "x" search the
167 /// directory of the \#including file first, then each directory in SearchDirs
168 /// consecutively. Requests for <x> search the current dir first, then each
169 /// directory in SearchDirs, starting at AngledDirIdx, consecutively. If
170 /// NoCurDirSearch is true, then the check for the file in the current
171 /// directory is suppressed.
172 std::vector<DirectoryLookup> SearchDirs;
173 unsigned AngledDirIdx;
174 unsigned SystemDirIdx;
177 /// \brief \#include prefixes for which the 'system header' property is
180 /// For a \#include "x" or \#include \<x> directive, the last string in this
181 /// list which is a prefix of 'x' determines whether the file is treated as
183 std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
185 /// \brief The path to the module cache.
186 std::string ModuleCachePath;
188 /// \brief All of the preprocessor-specific data about files that are
189 /// included, indexed by the FileEntry's UID.
190 std::vector<HeaderFileInfo> FileInfo;
192 /// Keeps track of each lookup performed by LookupFile.
193 struct LookupFileCacheInfo {
194 /// Starting index in SearchDirs that the cached search was performed from.
195 /// If there is a hit and this value doesn't match the current query, the
196 /// cache has to be ignored.
198 /// The entry in SearchDirs that satisfied the query.
200 /// This is non-null if the original filename was mapped to a framework
201 /// include via a headermap.
202 const char *MappedName;
204 /// Default constructor -- Initialize all members with zero.
205 LookupFileCacheInfo(): StartIdx(0), HitIdx(0), MappedName(nullptr) {}
207 void reset(unsigned StartIdx) {
208 this->StartIdx = StartIdx;
209 this->MappedName = nullptr;
212 llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
214 /// \brief Collection mapping a framework or subframework
215 /// name like "Carbon" to the Carbon.framework directory.
216 llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
218 /// IncludeAliases - maps include file names (including the quotes or
219 /// angle brackets) to other include file names. This is used to support the
220 /// include_alias pragma for Microsoft compatibility.
221 typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator>
223 std::unique_ptr<IncludeAliasMap> IncludeAliases;
225 /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
226 /// headermaps. This vector owns the headermap.
227 std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
229 /// \brief The mapping between modules and headers.
230 mutable ModuleMap ModMap;
232 /// \brief Describes whether a given directory has a module map in it.
233 llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
235 /// \brief Uniqued set of framework names, which is used to track which
236 /// headers were included as framework headers.
237 llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
239 /// \brief Entity used to resolve the identifier IDs of controlling
240 /// macros into IdentifierInfo pointers, as needed.
241 ExternalIdentifierLookup *ExternalLookup;
243 /// \brief Entity used to look up stored header file information.
244 ExternalHeaderFileInfoSource *ExternalSource;
246 // Various statistics we track for performance analysis.
247 unsigned NumIncluded;
248 unsigned NumMultiIncludeFileOptzn;
249 unsigned NumFrameworkLookups, NumSubFrameworkLookups;
253 // HeaderSearch doesn't support default or copy construction.
254 HeaderSearch(const HeaderSearch&) LLVM_DELETED_FUNCTION;
255 void operator=(const HeaderSearch&) LLVM_DELETED_FUNCTION;
257 friend class DirectoryLookup;
260 HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
261 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
262 const LangOptions &LangOpts, const TargetInfo *Target);
265 /// \brief Retrieve the header-search options with which this header search
267 HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
269 FileManager &getFileMgr() const { return FileMgr; }
271 /// \brief Interface for setting the file search paths.
272 void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
273 unsigned angledDirIdx, unsigned systemDirIdx,
274 bool noCurDirSearch) {
275 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
276 "Directory indicies are unordered");
278 AngledDirIdx = angledDirIdx;
279 SystemDirIdx = systemDirIdx;
280 NoCurDirSearch = noCurDirSearch;
281 //LookupFileCache.clear();
284 /// \brief Add an additional search path.
285 void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
286 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
287 SearchDirs.insert(SearchDirs.begin() + idx, dir);
293 /// \brief Set the list of system header prefixes.
294 void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool> > P) {
295 SystemHeaderPrefixes.assign(P.begin(), P.end());
298 /// \brief Checks whether the map exists or not.
299 bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
301 /// \brief Map the source include name to the dest include name.
303 /// The Source should include the angle brackets or quotes, the dest
304 /// should not. This allows for distinction between <> and "" headers.
305 void AddIncludeAlias(StringRef Source, StringRef Dest) {
307 IncludeAliases.reset(new IncludeAliasMap);
308 (*IncludeAliases)[Source] = Dest;
311 /// MapHeaderToIncludeAlias - Maps one header file name to a different header
312 /// file name, for use with the include_alias pragma. Note that the source
313 /// file name should include the angle brackets or quotes. Returns StringRef
314 /// as null if the header cannot be mapped.
315 StringRef MapHeaderToIncludeAlias(StringRef Source) {
316 assert(IncludeAliases && "Trying to map headers when there's no map");
318 // Do any filename replacements before anything else
319 IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
320 if (Iter != IncludeAliases->end())
325 /// \brief Set the path to the module cache.
326 void setModuleCachePath(StringRef CachePath) {
327 ModuleCachePath = CachePath;
330 /// \brief Retrieve the path to the module cache.
331 StringRef getModuleCachePath() const { return ModuleCachePath; }
333 /// \brief Consider modules when including files from this directory.
334 void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
335 DirectoryHasModuleMap[Dir] = true;
338 /// \brief Forget everything we know about headers so far.
339 void ClearFileInfo() {
343 void SetExternalLookup(ExternalIdentifierLookup *EIL) {
344 ExternalLookup = EIL;
347 ExternalIdentifierLookup *getExternalLookup() const {
348 return ExternalLookup;
351 /// \brief Set the external source of header information.
352 void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
356 /// \brief Set the target information for the header search, if not
358 void setTarget(const TargetInfo &Target);
360 /// \brief Given a "foo" or \<foo> reference, look up the indicated file,
361 /// return null on failure.
363 /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
364 /// the file was found in, or null if not applicable.
366 /// \param IncludeLoc Used for diagnostics if valid.
368 /// \param isAngled indicates whether the file reference is a <> reference.
370 /// \param CurDir If non-null, the file was found in the specified directory
371 /// search location. This is used to implement \#include_next.
373 /// \param Includers Indicates where the \#including file(s) are, in case
374 /// relative searches are needed. In reverse order of inclusion.
376 /// \param SearchPath If non-null, will be set to the search path relative
377 /// to which the file was found. If the include path is absolute, SearchPath
378 /// will be set to an empty string.
380 /// \param RelativePath If non-null, will be set to the path relative to
381 /// SearchPath at which the file was found. This only differs from the
382 /// Filename for framework includes.
384 /// \param SuggestedModule If non-null, and the file found is semantically
385 /// part of a known module, this will be set to the module that should
386 /// be imported instead of preprocessing/parsing the file found.
387 const FileEntry *LookupFile(StringRef Filename, SourceLocation IncludeLoc,
388 bool isAngled, const DirectoryLookup *FromDir,
389 const DirectoryLookup *&CurDir,
390 ArrayRef<const FileEntry *> Includers,
391 SmallVectorImpl<char> *SearchPath,
392 SmallVectorImpl<char> *RelativePath,
393 ModuleMap::KnownHeader *SuggestedModule,
394 bool SkipCache = false);
396 /// \brief Look up a subframework for the specified \#include file.
398 /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
399 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
400 /// HIToolbox is a subframework within Carbon.framework. If so, return
401 /// the FileEntry for the designated file, otherwise return null.
402 const FileEntry *LookupSubframeworkHeader(
404 const FileEntry *RelativeFileEnt,
405 SmallVectorImpl<char> *SearchPath,
406 SmallVectorImpl<char> *RelativePath,
407 ModuleMap::KnownHeader *SuggestedModule);
409 /// \brief Look up the specified framework name in our framework cache.
410 /// \returns The DirectoryEntry it is in if we know, null otherwise.
411 FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
412 return FrameworkMap.GetOrCreateValue(FWName).getValue();
415 /// \brief Mark the specified file as a target of of a \#include,
416 /// \#include_next, or \#import directive.
418 /// \return false if \#including the file will have no effect or true
419 /// if we should include it.
420 bool ShouldEnterIncludeFile(const FileEntry *File, bool isImport);
423 /// \brief Return whether the specified file is a normal header,
424 /// a system header, or a C++ friendly system header.
425 SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
426 return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
429 /// \brief Mark the specified file as a "once only" file, e.g. due to
431 void MarkFileIncludeOnce(const FileEntry *File) {
432 HeaderFileInfo &FI = getFileInfo(File);
434 FI.isPragmaOnce = true;
437 /// \brief Mark the specified file as a system header, e.g. due to
438 /// \#pragma GCC system_header.
439 void MarkFileSystemHeader(const FileEntry *File) {
440 getFileInfo(File).DirInfo = SrcMgr::C_System;
443 /// \brief Mark the specified file as part of a module.
444 void MarkFileModuleHeader(const FileEntry *File,
445 ModuleMap::ModuleHeaderRole Role,
446 bool IsCompiledModuleHeader);
448 /// \brief Increment the count for the number of times the specified
449 /// FileEntry has been entered.
450 void IncrementIncludeCount(const FileEntry *File) {
451 ++getFileInfo(File).NumIncludes;
454 /// \brief Mark the specified file as having a controlling macro.
456 /// This is used by the multiple-include optimization to eliminate
457 /// no-op \#includes.
458 void SetFileControllingMacro(const FileEntry *File,
459 const IdentifierInfo *ControllingMacro) {
460 getFileInfo(File).ControllingMacro = ControllingMacro;
463 /// \brief Return true if this is the first time encountering this header.
464 bool FirstTimeLexingFile(const FileEntry *File) {
465 return getFileInfo(File).NumIncludes == 1;
468 /// \brief Determine whether this file is intended to be safe from
469 /// multiple inclusions, e.g., it has \#pragma once or a controlling
472 /// This routine does not consider the effect of \#import
473 bool isFileMultipleIncludeGuarded(const FileEntry *File);
475 /// CreateHeaderMap - This method returns a HeaderMap for the specified
476 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
477 const HeaderMap *CreateHeaderMap(const FileEntry *FE);
479 /// Returns true if modules are enabled.
480 bool enabledModules() const { return EnabledModules; }
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,
643 /// \brief Try to load the module map file in the given directory.
645 /// \param DirName The name of the directory where we will look for a module
647 /// \param IsSystem Whether this is a system header directory.
648 /// \param IsFramework Whether this is a framework directory.
650 /// \returns The result of attempting to load the module map file from the
652 LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem,
655 /// \brief Try to load the module map file in the given directory.
657 /// \param Dir The directory where we will look for a module map file.
658 /// \param IsSystem Whether this is a system header directory.
659 /// \param IsFramework Whether this is a framework directory.
661 /// \returns The result of attempting to load the module map file from the
663 LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir,
664 bool IsSystem, bool IsFramework);
666 /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
667 HeaderFileInfo &getFileInfo(const FileEntry *FE);
670 } // end namespace clang