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/OwningPtr.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringSet.h"
24 #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 structure is considered to already have been
58 /// "resolved", meaning that it was loaded from the external source.
59 unsigned Resolved : 1;
61 /// \brief Whether this is a header inside a framework that is currently
64 /// When a framework is being built, the headers have not yet been placed
65 /// into the appropriate framework subdirectories, and therefore are
66 /// provided via a header map. This bit indicates when this is one of
67 /// those framework headers.
68 unsigned IndexHeaderMapHeader : 1;
70 /// \brief The number of times the file has been included already.
71 unsigned short NumIncludes;
73 /// \brief The ID number of the controlling macro.
75 /// This ID number will be non-zero when there is a controlling
76 /// macro whose IdentifierInfo may not yet have been loaded from
78 unsigned ControllingMacroID;
80 /// If this file has a \#ifndef XXX (or equivalent) guard that
81 /// protects the entire contents of the file, this is the identifier
82 /// for the macro that controls whether or not it has any effect.
84 /// Note: Most clients should use getControllingMacro() to access
85 /// the controlling macro of this header, since
86 /// getControllingMacro() is able to load a controlling macro from
88 const IdentifierInfo *ControllingMacro;
90 /// \brief If this header came from a framework include, this is the name
95 : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
96 External(false), isModuleHeader(false), Resolved(false),
97 IndexHeaderMapHeader(false),
98 NumIncludes(0), ControllingMacroID(0), ControllingMacro(0) {}
100 /// \brief Retrieve the controlling macro for this header file, if
102 const IdentifierInfo *getControllingMacro(ExternalIdentifierLookup *External);
104 /// \brief Determine whether this is a non-default header file info, e.g.,
105 /// it corresponds to an actual header we've included or tried to include.
106 bool isNonDefault() const {
107 return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
112 /// \brief An external source of header file information, which may supply
113 /// information about header files already included.
114 class ExternalHeaderFileInfoSource {
116 virtual ~ExternalHeaderFileInfoSource();
118 /// \brief Retrieve the header file information for the given file entry.
120 /// \returns Header file information for the given file entry, with the
121 /// \c External bit set. If the file entry is not known, return a
122 /// default-constructed \c HeaderFileInfo.
123 virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
126 /// \brief Encapsulates the information needed to find the file referenced
127 /// by a \#include or \#include_next, (sub-)framework lookup, etc.
129 /// This structure is used to record entries in our framework cache.
130 struct FrameworkCacheEntry {
131 /// The directory entry which should be used for the cached framework.
132 const DirectoryEntry *Directory;
134 /// Whether this framework has been "user-specified" to be treated as if it
135 /// were a system framework (even if it was found outside a system framework
137 bool IsUserSpecifiedSystemFramework;
140 /// \brief Header-search options used to initialize this header search.
141 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
143 FileManager &FileMgr;
144 /// \#include search path information. Requests for \#include "x" search the
145 /// directory of the \#including file first, then each directory in SearchDirs
146 /// consecutively. Requests for <x> search the current dir first, then each
147 /// directory in SearchDirs, starting at AngledDirIdx, consecutively. If
148 /// NoCurDirSearch is true, then the check for the file in the current
149 /// directory is suppressed.
150 std::vector<DirectoryLookup> SearchDirs;
151 unsigned AngledDirIdx;
152 unsigned SystemDirIdx;
155 /// \brief \#include prefixes for which the 'system header' property is
158 /// For a \#include "x" or \#include \<x> directive, the last string in this
159 /// list which is a prefix of 'x' determines whether the file is treated as
161 std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
163 /// \brief The path to the module cache.
164 std::string ModuleCachePath;
166 /// \brief All of the preprocessor-specific data about files that are
167 /// included, indexed by the FileEntry's UID.
168 std::vector<HeaderFileInfo> FileInfo;
170 /// \brief Keeps track of each lookup performed by LookupFile.
172 /// The first part of the value is the starting index in SearchDirs
173 /// that the cached search was performed from. If there is a hit and
174 /// this value doesn't match the current query, the cache has to be
175 /// ignored. The second value is the entry in SearchDirs that satisfied
177 llvm::StringMap<std::pair<unsigned, unsigned>, llvm::BumpPtrAllocator>
180 /// \brief Collection mapping a framework or subframework
181 /// name like "Carbon" to the Carbon.framework directory.
182 llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
184 /// IncludeAliases - maps include file names (including the quotes or
185 /// angle brackets) to other include file names. This is used to support the
186 /// include_alias pragma for Microsoft compatibility.
187 typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator>
189 OwningPtr<IncludeAliasMap> IncludeAliases;
191 /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
192 /// headermaps. This vector owns the headermap.
193 std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
195 /// \brief The mapping between modules and headers.
196 mutable ModuleMap ModMap;
198 /// \brief Describes whether a given directory has a module map in it.
199 llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
201 /// \brief Uniqued set of framework names, which is used to track which
202 /// headers were included as framework headers.
203 llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
205 /// \brief Entity used to resolve the identifier IDs of controlling
206 /// macros into IdentifierInfo pointers, as needed.
207 ExternalIdentifierLookup *ExternalLookup;
209 /// \brief Entity used to look up stored header file information.
210 ExternalHeaderFileInfoSource *ExternalSource;
212 // Various statistics we track for performance analysis.
213 unsigned NumIncluded;
214 unsigned NumMultiIncludeFileOptzn;
215 unsigned NumFrameworkLookups, NumSubFrameworkLookups;
217 // HeaderSearch doesn't support default or copy construction.
218 HeaderSearch(const HeaderSearch&) LLVM_DELETED_FUNCTION;
219 void operator=(const HeaderSearch&) LLVM_DELETED_FUNCTION;
221 friend class DirectoryLookup;
224 HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
225 FileManager &FM, DiagnosticsEngine &Diags,
226 const LangOptions &LangOpts, const TargetInfo *Target);
229 /// \brief Retrieve the header-search options with which this header search
231 HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
233 FileManager &getFileMgr() const { return FileMgr; }
235 /// \brief Interface for setting the file search paths.
236 void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
237 unsigned angledDirIdx, unsigned systemDirIdx,
238 bool noCurDirSearch) {
239 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
240 "Directory indicies are unordered");
242 AngledDirIdx = angledDirIdx;
243 SystemDirIdx = systemDirIdx;
244 NoCurDirSearch = noCurDirSearch;
245 //LookupFileCache.clear();
248 /// \brief Add an additional search path.
249 void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
250 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
251 SearchDirs.insert(SearchDirs.begin() + idx, dir);
257 /// \brief Set the list of system header prefixes.
258 void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool> > P) {
259 SystemHeaderPrefixes.assign(P.begin(), P.end());
262 /// \brief Checks whether the map exists or not.
263 bool HasIncludeAliasMap() const {
264 return IncludeAliases;
267 /// \brief Map the source include name to the dest include name.
269 /// The Source should include the angle brackets or quotes, the dest
270 /// should not. This allows for distinction between <> and "" headers.
271 void AddIncludeAlias(StringRef Source, StringRef Dest) {
273 IncludeAliases.reset(new IncludeAliasMap);
274 (*IncludeAliases)[Source] = Dest;
277 /// MapHeaderToIncludeAlias - Maps one header file name to a different header
278 /// file name, for use with the include_alias pragma. Note that the source
279 /// file name should include the angle brackets or quotes. Returns StringRef
280 /// as null if the header cannot be mapped.
281 StringRef MapHeaderToIncludeAlias(StringRef Source) {
282 assert(IncludeAliases && "Trying to map headers when there's no map");
284 // Do any filename replacements before anything else
285 IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
286 if (Iter != IncludeAliases->end())
291 /// \brief Set the path to the module cache.
292 void setModuleCachePath(StringRef CachePath) {
293 ModuleCachePath = CachePath;
296 /// \brief Retrieve the path to the module cache.
297 StringRef getModuleCachePath() const { return ModuleCachePath; }
299 /// \brief Consider modules when including files from this directory.
300 void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
301 DirectoryHasModuleMap[Dir] = true;
304 /// \brief Forget everything we know about headers so far.
305 void ClearFileInfo() {
309 void SetExternalLookup(ExternalIdentifierLookup *EIL) {
310 ExternalLookup = EIL;
313 ExternalIdentifierLookup *getExternalLookup() const {
314 return ExternalLookup;
317 /// \brief Set the external source of header information.
318 void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
322 /// \brief Set the target information for the header search, if not
324 void setTarget(const TargetInfo &Target);
326 /// \brief Given a "foo" or \<foo> reference, look up the indicated file,
327 /// return null on failure.
329 /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
330 /// the file was found in, or null if not applicable.
332 /// \param isAngled indicates whether the file reference is a <> reference.
334 /// \param CurDir If non-null, the file was found in the specified directory
335 /// search location. This is used to implement \#include_next.
337 /// \param CurFileEnt If non-null, indicates where the \#including file is, in
338 /// case a relative search is needed.
340 /// \param SearchPath If non-null, will be set to the search path relative
341 /// to which the file was found. If the include path is absolute, SearchPath
342 /// will be set to an empty string.
344 /// \param RelativePath If non-null, will be set to the path relative to
345 /// SearchPath at which the file was found. This only differs from the
346 /// Filename for framework includes.
348 /// \param SuggestedModule If non-null, and the file found is semantically
349 /// part of a known module, this will be set to the module that should
350 /// be imported instead of preprocessing/parsing the file found.
351 const FileEntry *LookupFile(StringRef Filename, bool isAngled,
352 const DirectoryLookup *FromDir,
353 const DirectoryLookup *&CurDir,
354 const FileEntry *CurFileEnt,
355 SmallVectorImpl<char> *SearchPath,
356 SmallVectorImpl<char> *RelativePath,
357 Module **SuggestedModule,
358 bool SkipCache = false);
360 /// \brief Look up a subframework for the specified \#include file.
362 /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
363 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
364 /// HIToolbox is a subframework within Carbon.framework. If so, return
365 /// the FileEntry for the designated file, otherwise return null.
366 const FileEntry *LookupSubframeworkHeader(
368 const FileEntry *RelativeFileEnt,
369 SmallVectorImpl<char> *SearchPath,
370 SmallVectorImpl<char> *RelativePath,
371 Module **SuggestedModule);
373 /// \brief Look up the specified framework name in our framework cache.
374 /// \returns The DirectoryEntry it is in if we know, null otherwise.
375 FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
376 return FrameworkMap.GetOrCreateValue(FWName).getValue();
379 /// \brief Mark the specified file as a target of of a \#include,
380 /// \#include_next, or \#import directive.
382 /// \return false if \#including the file will have no effect or true
383 /// if we should include it.
384 bool ShouldEnterIncludeFile(const FileEntry *File, bool isImport);
387 /// \brief Return whether the specified file is a normal header,
388 /// a system header, or a C++ friendly system header.
389 SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
390 return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
393 /// \brief Mark the specified file as a "once only" file, e.g. due to
395 void MarkFileIncludeOnce(const FileEntry *File) {
396 HeaderFileInfo &FI = getFileInfo(File);
398 FI.isPragmaOnce = true;
401 /// \brief Mark the specified file as a system header, e.g. due to
402 /// \#pragma GCC system_header.
403 void MarkFileSystemHeader(const FileEntry *File) {
404 getFileInfo(File).DirInfo = SrcMgr::C_System;
407 /// \brief Mark the specified file as part of a module.
408 void MarkFileModuleHeader(const FileEntry *File);
410 /// \brief Increment the count for the number of times the specified
411 /// FileEntry has been entered.
412 void IncrementIncludeCount(const FileEntry *File) {
413 ++getFileInfo(File).NumIncludes;
416 /// \brief Mark the specified file as having a controlling macro.
418 /// This is used by the multiple-include optimization to eliminate
419 /// no-op \#includes.
420 void SetFileControllingMacro(const FileEntry *File,
421 const IdentifierInfo *ControllingMacro) {
422 getFileInfo(File).ControllingMacro = ControllingMacro;
425 /// \brief Determine whether this file is intended to be safe from
426 /// multiple inclusions, e.g., it has \#pragma once or a controlling
429 /// This routine does not consider the effect of \#import
430 bool isFileMultipleIncludeGuarded(const FileEntry *File);
432 /// CreateHeaderMap - This method returns a HeaderMap for the specified
433 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
434 const HeaderMap *CreateHeaderMap(const FileEntry *FE);
436 /// \brief Retrieve the name of the module file that should be used to
437 /// load the given module.
439 /// \param Module The module whose module file name will be returned.
441 /// \returns The name of the module file that corresponds to this module,
442 /// or an empty string if this module does not correspond to any module file.
443 std::string getModuleFileName(Module *Module);
445 /// \brief Retrieve the name of the module file that should be used to
446 /// load a module with the given name.
448 /// \param ModuleName The module whose module file name will be returned.
450 /// \returns The name of the module file that corresponds to this module,
451 /// or an empty string if this module does not correspond to any module file.
452 std::string getModuleFileName(StringRef ModuleName);
454 /// \brief Lookup a module Search for a module with the given name.
456 /// \param ModuleName The name of the module we're looking for.
458 /// \param AllowSearch Whether we are allowed to search in the various
459 /// search directories to produce a module definition. If not, this lookup
460 /// will only return an already-known module.
462 /// \returns The module with the given name.
463 Module *lookupModule(StringRef ModuleName, bool AllowSearch = true);
465 void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
467 /// \brief Determine whether there is a module map that may map the header
468 /// with the given file name to a (sub)module.
470 /// \param Filename The name of the file.
472 /// \param Root The "root" directory, at which we should stop looking for
474 bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root);
476 /// \brief Retrieve the module that corresponds to the given file, if any.
478 /// \param File The header that we wish to map to a module.
479 Module *findModuleForHeader(const FileEntry *File) const;
481 /// \brief Read the contents of the given module map file.
483 /// \param File The module map file.
485 /// \returns true if an error occurred, false otherwise.
486 bool loadModuleMapFile(const FileEntry *File);
488 /// \brief Collect the set of all known, top-level modules.
490 /// \param Modules Will be filled with the set of known, top-level modules.
491 void collectAllModules(SmallVectorImpl<Module *> &Modules);
494 /// \brief Retrieve a module with the given name, which may be part of the
497 /// \param Name The name of the module to retrieve.
499 /// \param Dir The framework directory (e.g., ModuleName.framework).
501 /// \param IsSystem Whether the framework directory is part of the system
504 /// \returns The module, if found; otherwise, null.
505 Module *loadFrameworkModule(StringRef Name,
506 const DirectoryEntry *Dir,
509 /// \brief Load all of the module maps within the immediate subdirectories
510 /// of the given search directory.
511 void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
514 /// \brief Retrieve the module map.
515 ModuleMap &getModuleMap() { return ModMap; }
517 unsigned header_file_size() const { return FileInfo.size(); }
519 // Used by ASTReader.
520 void setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID);
522 /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
523 const HeaderFileInfo &getFileInfo(const FileEntry *FE) const {
524 return const_cast<HeaderSearch*>(this)->getFileInfo(FE);
527 // Used by external tools
528 typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
529 search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
530 search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
531 unsigned search_dir_size() const { return SearchDirs.size(); }
533 search_dir_iterator quoted_dir_begin() const {
534 return SearchDirs.begin();
536 search_dir_iterator quoted_dir_end() const {
537 return SearchDirs.begin() + AngledDirIdx;
540 search_dir_iterator angled_dir_begin() const {
541 return SearchDirs.begin() + AngledDirIdx;
543 search_dir_iterator angled_dir_end() const {
544 return SearchDirs.begin() + SystemDirIdx;
547 search_dir_iterator system_dir_begin() const {
548 return SearchDirs.begin() + SystemDirIdx;
550 search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
552 /// \brief Retrieve a uniqued framework name.
553 StringRef getUniqueFrameworkName(StringRef Framework);
557 size_t getTotalMemory() const;
559 static std::string NormalizeDashIncludePath(StringRef File,
560 FileManager &FileMgr);
563 /// \brief Describes what happened when we tried to load a module map file.
564 enum LoadModuleMapResult {
565 /// \brief The module map file had already been loaded.
567 /// \brief The module map file was loaded by this invocation.
569 /// \brief There is was directory with the given name.
571 /// \brief There was either no module map file or the module map file was
576 /// \brief Try to load the module map file in the given directory.
578 /// \param DirName The name of the directory where we will look for a module
581 /// \returns The result of attempting to load the module map file from the
583 LoadModuleMapResult loadModuleMapFile(StringRef DirName);
585 /// \brief Try to load the module map file in the given directory.
587 /// \param Dir The directory where we will look for a module map file.
589 /// \returns The result of attempting to load the module map file from the
591 LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir);
593 /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
594 HeaderFileInfo &getFileInfo(const FileEntry *FE);
597 } // end namespace clang