HeaderSearch.h revision cfa88f893915ceb8ae4ce2f17c46c24a4d67502f
1//===--- HeaderSearch.h - Resolve Header File Locations ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the HeaderSearch interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
15#define LLVM_CLANG_LEX_HEADERSEARCH_H
16
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"
25#include <vector>
26
27namespace clang {
28
29class DiagnosticsEngine;
30class ExternalIdentifierLookup;
31class FileEntry;
32class FileManager;
33class HeaderSearchOptions;
34class IdentifierInfo;
35
36/// \brief The preprocessor keeps track of this information for each
37/// file that is \#included.
38struct HeaderFileInfo {
39  /// \brief True if this is a \#import'd or \#pragma once file.
40  unsigned isImport : 1;
41
42  /// \brief True if this is a \#pragma once file.
43  unsigned isPragmaOnce : 1;
44
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.
49  unsigned DirInfo : 2;
50
51  /// \brief Whether this header file info was supplied by an external source.
52  unsigned External : 1;
53
54  /// \brief Whether this structure is considered to already have been
55  /// "resolved", meaning that it was loaded from the external source.
56  unsigned Resolved : 1;
57
58  /// \brief Whether this is a header inside a framework that is currently
59  /// being built.
60  ///
61  /// When a framework is being built, the headers have not yet been placed
62  /// into the appropriate framework subdirectories, and therefore are
63  /// provided via a header map. This bit indicates when this is one of
64  /// those framework headers.
65  unsigned IndexHeaderMapHeader : 1;
66
67  /// \brief The number of times the file has been included already.
68  unsigned short NumIncludes;
69
70  /// \brief The ID number of the controlling macro.
71  ///
72  /// This ID number will be non-zero when there is a controlling
73  /// macro whose IdentifierInfo may not yet have been loaded from
74  /// external storage.
75  unsigned ControllingMacroID;
76
77  /// If this file has a \#ifndef XXX (or equivalent) guard that
78  /// protects the entire contents of the file, this is the identifier
79  /// for the macro that controls whether or not it has any effect.
80  ///
81  /// Note: Most clients should use getControllingMacro() to access
82  /// the controlling macro of this header, since
83  /// getControllingMacro() is able to load a controlling macro from
84  /// external storage.
85  const IdentifierInfo *ControllingMacro;
86
87  /// \brief If this header came from a framework include, this is the name
88  /// of the framework.
89  StringRef Framework;
90
91  HeaderFileInfo()
92    : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
93      External(false), Resolved(false), IndexHeaderMapHeader(false),
94      NumIncludes(0), ControllingMacroID(0), ControllingMacro(0)  {}
95
96  /// \brief Retrieve the controlling macro for this header file, if
97  /// any.
98  const IdentifierInfo *getControllingMacro(ExternalIdentifierLookup *External);
99
100  /// \brief Determine whether this is a non-default header file info, e.g.,
101  /// it corresponds to an actual header we've included or tried to include.
102  bool isNonDefault() const {
103    return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
104      ControllingMacroID;
105  }
106};
107
108/// \brief An external source of header file information, which may supply
109/// information about header files already included.
110class ExternalHeaderFileInfoSource {
111public:
112  virtual ~ExternalHeaderFileInfoSource();
113
114  /// \brief Retrieve the header file information for the given file entry.
115  ///
116  /// \returns Header file information for the given file entry, with the
117  /// \c External bit set. If the file entry is not known, return a
118  /// default-constructed \c HeaderFileInfo.
119  virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
120};
121
122/// \brief Encapsulates the information needed to find the file referenced
123/// by a \#include or \#include_next, (sub-)framework lookup, etc.
124class HeaderSearch {
125  /// This structure is used to record entries in our framework cache.
126  struct FrameworkCacheEntry {
127    /// The directory entry which should be used for the cached framework.
128    const DirectoryEntry *Directory;
129
130    /// Whether this framework has been "user-specified" to be treated as if it
131    /// were a system framework (even if it was found outside a system framework
132    /// directory).
133    bool IsUserSpecifiedSystemFramework;
134  };
135
136  /// \brief Header-search options used to initialize this header search.
137  IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
138
139  FileManager &FileMgr;
140  /// \#include search path information.  Requests for \#include "x" search the
141  /// directory of the \#including file first, then each directory in SearchDirs
142  /// consecutively. Requests for <x> search the current dir first, then each
143  /// directory in SearchDirs, starting at AngledDirIdx, consecutively.  If
144  /// NoCurDirSearch is true, then the check for the file in the current
145  /// directory is suppressed.
146  std::vector<DirectoryLookup> SearchDirs;
147  unsigned AngledDirIdx;
148  unsigned SystemDirIdx;
149  bool NoCurDirSearch;
150
151  /// \brief \#include prefixes for which the 'system header' property is
152  /// overridden.
153  ///
154  /// For a \#include "x" or \#include \<x> directive, the last string in this
155  /// list which is a prefix of 'x' determines whether the file is treated as
156  /// a system header.
157  std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
158
159  /// \brief The path to the module cache.
160  std::string ModuleCachePath;
161
162  /// \brief All of the preprocessor-specific data about files that are
163  /// included, indexed by the FileEntry's UID.
164  std::vector<HeaderFileInfo> FileInfo;
165
166  /// \brief Keeps track of each lookup performed by LookupFile.
167  ///
168  /// The first part of the value is the starting index in SearchDirs
169  /// that the cached search was performed from.  If there is a hit and
170  /// this value doesn't match the current query, the cache has to be
171  /// ignored.  The second value is the entry in SearchDirs that satisfied
172  /// the query.
173  llvm::StringMap<std::pair<unsigned, unsigned>, llvm::BumpPtrAllocator>
174    LookupFileCache;
175
176  /// \brief Collection mapping a framework or subframework
177  /// name like "Carbon" to the Carbon.framework directory.
178  llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
179
180  /// IncludeAliases - maps include file names (including the quotes or
181  /// angle brackets) to other include file names.  This is used to support the
182  /// include_alias pragma for Microsoft compatibility.
183  typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator>
184    IncludeAliasMap;
185  OwningPtr<IncludeAliasMap> IncludeAliases;
186
187  /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
188  /// headermaps.  This vector owns the headermap.
189  std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
190
191  /// \brief The mapping between modules and headers.
192  ModuleMap ModMap;
193
194  /// \brief Describes whether a given directory has a module map in it.
195  llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
196
197  /// \brief Uniqued set of framework names, which is used to track which
198  /// headers were included as framework headers.
199  llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
200
201  /// \brief Entity used to resolve the identifier IDs of controlling
202  /// macros into IdentifierInfo pointers, as needed.
203  ExternalIdentifierLookup *ExternalLookup;
204
205  /// \brief Entity used to look up stored header file information.
206  ExternalHeaderFileInfoSource *ExternalSource;
207
208  // Various statistics we track for performance analysis.
209  unsigned NumIncluded;
210  unsigned NumMultiIncludeFileOptzn;
211  unsigned NumFrameworkLookups, NumSubFrameworkLookups;
212
213  // HeaderSearch doesn't support default or copy construction.
214  HeaderSearch(const HeaderSearch&) LLVM_DELETED_FUNCTION;
215  void operator=(const HeaderSearch&) LLVM_DELETED_FUNCTION;
216
217  friend class DirectoryLookup;
218
219public:
220  HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
221               FileManager &FM, DiagnosticsEngine &Diags,
222               const LangOptions &LangOpts, const TargetInfo *Target);
223  ~HeaderSearch();
224
225  /// \brief Retrieve the header-search options with which this header search
226  /// was initialized.
227  HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
228
229  FileManager &getFileMgr() const { return FileMgr; }
230
231  /// \brief Interface for setting the file search paths.
232  void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
233                      unsigned angledDirIdx, unsigned systemDirIdx,
234                      bool noCurDirSearch) {
235    assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
236        "Directory indicies are unordered");
237    SearchDirs = dirs;
238    AngledDirIdx = angledDirIdx;
239    SystemDirIdx = systemDirIdx;
240    NoCurDirSearch = noCurDirSearch;
241    //LookupFileCache.clear();
242  }
243
244  /// \brief Add an additional search path.
245  void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
246    unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
247    SearchDirs.insert(SearchDirs.begin() + idx, dir);
248    if (!isAngled)
249      AngledDirIdx++;
250    SystemDirIdx++;
251  }
252
253  /// \brief Set the list of system header prefixes.
254  void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool> > P) {
255    SystemHeaderPrefixes.assign(P.begin(), P.end());
256  }
257
258  /// \brief Checks whether the map exists or not.
259  bool HasIncludeAliasMap() const {
260    return IncludeAliases;
261  }
262
263  /// \brief Map the source include name to the dest include name.
264  ///
265  /// The Source should include the angle brackets or quotes, the dest
266  /// should not.  This allows for distinction between <> and "" headers.
267  void AddIncludeAlias(StringRef Source, StringRef Dest) {
268    if (!IncludeAliases)
269      IncludeAliases.reset(new IncludeAliasMap);
270    (*IncludeAliases)[Source] = Dest;
271  }
272
273  /// MapHeaderToIncludeAlias - Maps one header file name to a different header
274  /// file name, for use with the include_alias pragma.  Note that the source
275  /// file name should include the angle brackets or quotes.  Returns StringRef
276  /// as null if the header cannot be mapped.
277  StringRef MapHeaderToIncludeAlias(StringRef Source) {
278    assert(IncludeAliases && "Trying to map headers when there's no map");
279
280    // Do any filename replacements before anything else
281    IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
282    if (Iter != IncludeAliases->end())
283      return Iter->second;
284    return StringRef();
285  }
286
287  /// \brief Set the path to the module cache.
288  void setModuleCachePath(StringRef CachePath) {
289    ModuleCachePath = CachePath;
290  }
291
292  /// \brief Retrieve the path to the module cache.
293  StringRef getModuleCachePath() const { return ModuleCachePath; }
294
295  /// \brief Consider modules when including files from this directory.
296  void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
297    DirectoryHasModuleMap[Dir] = true;
298  }
299
300  /// \brief Forget everything we know about headers so far.
301  void ClearFileInfo() {
302    FileInfo.clear();
303  }
304
305  void SetExternalLookup(ExternalIdentifierLookup *EIL) {
306    ExternalLookup = EIL;
307  }
308
309  ExternalIdentifierLookup *getExternalLookup() const {
310    return ExternalLookup;
311  }
312
313  /// \brief Set the external source of header information.
314  void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
315    ExternalSource = ES;
316  }
317
318  /// \brief Set the target information for the header search, if not
319  /// already known.
320  void setTarget(const TargetInfo &Target);
321
322  /// \brief Given a "foo" or \<foo> reference, look up the indicated file,
323  /// return null on failure.
324  ///
325  /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
326  /// the file was found in, or null if not applicable.
327  ///
328  /// \param isAngled indicates whether the file reference is a <> reference.
329  ///
330  /// \param CurDir If non-null, the file was found in the specified directory
331  /// search location.  This is used to implement \#include_next.
332  ///
333  /// \param CurFileEnt If non-null, indicates where the \#including file is, in
334  /// case a relative search is needed.
335  ///
336  /// \param SearchPath If non-null, will be set to the search path relative
337  /// to which the file was found. If the include path is absolute, SearchPath
338  /// will be set to an empty string.
339  ///
340  /// \param RelativePath If non-null, will be set to the path relative to
341  /// SearchPath at which the file was found. This only differs from the
342  /// Filename for framework includes.
343  ///
344  /// \param SuggestedModule If non-null, and the file found is semantically
345  /// part of a known module, this will be set to the module that should
346  /// be imported instead of preprocessing/parsing the file found.
347  const FileEntry *LookupFile(StringRef Filename, bool isAngled,
348                              const DirectoryLookup *FromDir,
349                              const DirectoryLookup *&CurDir,
350                              const FileEntry *CurFileEnt,
351                              SmallVectorImpl<char> *SearchPath,
352                              SmallVectorImpl<char> *RelativePath,
353                              Module **SuggestedModule,
354                              bool SkipCache = false);
355
356  /// \brief Look up a subframework for the specified \#include file.
357  ///
358  /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
359  /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
360  /// HIToolbox is a subframework within Carbon.framework.  If so, return
361  /// the FileEntry for the designated file, otherwise return null.
362  const FileEntry *LookupSubframeworkHeader(
363      StringRef Filename,
364      const FileEntry *RelativeFileEnt,
365      SmallVectorImpl<char> *SearchPath,
366      SmallVectorImpl<char> *RelativePath);
367
368  /// \brief Look up the specified framework name in our framework cache.
369  /// \returns The DirectoryEntry it is in if we know, null otherwise.
370  FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
371    return FrameworkMap.GetOrCreateValue(FWName).getValue();
372  }
373
374  /// \brief Mark the specified file as a target of of a \#include,
375  /// \#include_next, or \#import directive.
376  ///
377  /// \return false if \#including the file will have no effect or true
378  /// if we should include it.
379  bool ShouldEnterIncludeFile(const FileEntry *File, bool isImport);
380
381
382  /// \brief Return whether the specified file is a normal header,
383  /// a system header, or a C++ friendly system header.
384  SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
385    return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
386  }
387
388  /// \brief Mark the specified file as a "once only" file, e.g. due to
389  /// \#pragma once.
390  void MarkFileIncludeOnce(const FileEntry *File) {
391    HeaderFileInfo &FI = getFileInfo(File);
392    FI.isImport = true;
393    FI.isPragmaOnce = true;
394  }
395
396  /// \brief Mark the specified file as a system header, e.g. due to
397  /// \#pragma GCC system_header.
398  void MarkFileSystemHeader(const FileEntry *File) {
399    getFileInfo(File).DirInfo = SrcMgr::C_System;
400  }
401
402  /// \brief Increment the count for the number of times the specified
403  /// FileEntry has been entered.
404  void IncrementIncludeCount(const FileEntry *File) {
405    ++getFileInfo(File).NumIncludes;
406  }
407
408  /// \brief Mark the specified file as having a controlling macro.
409  ///
410  /// This is used by the multiple-include optimization to eliminate
411  /// no-op \#includes.
412  void SetFileControllingMacro(const FileEntry *File,
413                               const IdentifierInfo *ControllingMacro) {
414    getFileInfo(File).ControllingMacro = ControllingMacro;
415  }
416
417  /// \brief Determine whether this file is intended to be safe from
418  /// multiple inclusions, e.g., it has \#pragma once or a controlling
419  /// macro.
420  ///
421  /// This routine does not consider the effect of \#import
422  bool isFileMultipleIncludeGuarded(const FileEntry *File);
423
424  /// CreateHeaderMap - This method returns a HeaderMap for the specified
425  /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
426  const HeaderMap *CreateHeaderMap(const FileEntry *FE);
427
428  /// \brief Retrieve the name of the module file that should be used to
429  /// load the given module.
430  ///
431  /// \param Module The module whose module file name will be returned.
432  ///
433  /// \returns The name of the module file that corresponds to this module,
434  /// or an empty string if this module does not correspond to any module file.
435  std::string getModuleFileName(Module *Module);
436
437  /// \brief Retrieve the name of the module file that should be used to
438  /// load a module with the given name.
439  ///
440  /// \param ModuleName The module whose module file name will be returned.
441  ///
442  /// \returns The name of the module file that corresponds to this module,
443  /// or an empty string if this module does not correspond to any module file.
444  std::string getModuleFileName(StringRef ModuleName);
445
446  /// \brief Lookup a module Search for a module with the given name.
447  ///
448  /// \param ModuleName The name of the module we're looking for.
449  ///
450  /// \param AllowSearch Whether we are allowed to search in the various
451  /// search directories to produce a module definition. If not, this lookup
452  /// will only return an already-known module.
453  ///
454  /// \returns The module with the given name.
455  Module *lookupModule(StringRef ModuleName, bool AllowSearch = true);
456
457  void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
458
459  /// \brief Determine whether there is a module map that may map the header
460  /// with the given file name to a (sub)module.
461  ///
462  /// \param Filename The name of the file.
463  ///
464  /// \param Root The "root" directory, at which we should stop looking for
465  /// module maps.
466  bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root);
467
468  /// \brief Retrieve the module that corresponds to the given file, if any.
469  ///
470  /// \param File The header that we wish to map to a module.
471  Module *findModuleForHeader(const FileEntry *File);
472
473  /// \brief Read the contents of the given module map file.
474  ///
475  /// \param File The module map file.
476  ///
477  /// \returns true if an error occurred, false otherwise.
478  bool loadModuleMapFile(const FileEntry *File);
479
480  /// \brief Collect the set of all known, top-level modules.
481  ///
482  /// \param Modules Will be filled with the set of known, top-level modules.
483  void collectAllModules(SmallVectorImpl<Module *> &Modules);
484
485private:
486  /// \brief Retrieve a module with the given name, which may be part of the
487  /// given framework.
488  ///
489  /// \param Name The name of the module to retrieve.
490  ///
491  /// \param Dir The framework directory (e.g., ModuleName.framework).
492  ///
493  /// \param IsSystem Whether the framework directory is part of the system
494  /// frameworks.
495  ///
496  /// \returns The module, if found; otherwise, null.
497  Module *loadFrameworkModule(StringRef Name,
498                              const DirectoryEntry *Dir,
499                              bool IsSystem);
500
501public:
502  /// \brief Retrieve the module map.
503  ModuleMap &getModuleMap() { return ModMap; }
504
505  unsigned header_file_size() const { return FileInfo.size(); }
506
507  // Used by ASTReader.
508  void setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID);
509
510  /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
511  const HeaderFileInfo &getFileInfo(const FileEntry *FE) const {
512    return const_cast<HeaderSearch*>(this)->getFileInfo(FE);
513  }
514
515  // Used by external tools
516  typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
517  search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
518  search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
519  unsigned search_dir_size() const { return SearchDirs.size(); }
520
521  search_dir_iterator quoted_dir_begin() const {
522    return SearchDirs.begin();
523  }
524  search_dir_iterator quoted_dir_end() const {
525    return SearchDirs.begin() + AngledDirIdx;
526  }
527
528  search_dir_iterator angled_dir_begin() const {
529    return SearchDirs.begin() + AngledDirIdx;
530  }
531  search_dir_iterator angled_dir_end() const {
532    return SearchDirs.begin() + SystemDirIdx;
533  }
534
535  search_dir_iterator system_dir_begin() const {
536    return SearchDirs.begin() + SystemDirIdx;
537  }
538  search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
539
540  /// \brief Retrieve a uniqued framework name.
541  StringRef getUniqueFrameworkName(StringRef Framework);
542
543  void PrintStats();
544
545  size_t getTotalMemory() const;
546
547  static std::string NormalizeDashIncludePath(StringRef File,
548                                              FileManager &FileMgr);
549
550private:
551  /// \brief Describes what happened when we tried to load a module map file.
552  enum LoadModuleMapResult {
553    /// \brief The module map file had already been loaded.
554    LMM_AlreadyLoaded,
555    /// \brief The module map file was loaded by this invocation.
556    LMM_NewlyLoaded,
557    /// \brief There is was directory with the given name.
558    LMM_NoDirectory,
559    /// \brief There was either no module map file or the module map file was
560    /// invalid.
561    LMM_InvalidModuleMap
562  };
563
564  /// \brief Try to load the module map file in the given directory.
565  ///
566  /// \param DirName The name of the directory where we will look for a module
567  /// map file.
568  ///
569  /// \returns The result of attempting to load the module map file from the
570  /// named directory.
571  LoadModuleMapResult loadModuleMapFile(StringRef DirName);
572
573  /// \brief Try to load the module map file in the given directory.
574  ///
575  /// \param Dir The directory where we will look for a module map file.
576  ///
577  /// \returns The result of attempting to load the module map file from the
578  /// named directory.
579  LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir);
580
581  /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
582  HeaderFileInfo &getFileInfo(const FileEntry *FE);
583};
584
585}  // end namespace clang
586
587#endif
588