clang  3.8.0
Utils.h
Go to the documentation of this file.
1 //===--- Utils.h - Misc utilities for the front-end -------------*- 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 header contains miscellaneous utilities for various front-end actions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_FRONTEND_UTILS_H
15 #define LLVM_CLANG_FRONTEND_UTILS_H
16 
17 #include "clang/Basic/Diagnostic.h"
19 #include "llvm/ADT/IntrusiveRefCntPtr.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/Option/OptSpecifier.h"
23 
24 namespace llvm {
25 class raw_fd_ostream;
26 class Triple;
27 
28 namespace opt {
29 class ArgList;
30 }
31 }
32 
33 namespace clang {
34 class ASTConsumer;
35 class ASTReader;
36 class CompilerInstance;
37 class CompilerInvocation;
38 class Decl;
39 class DependencyOutputOptions;
40 class DiagnosticsEngine;
41 class DiagnosticOptions;
42 class ExternalSemaSource;
43 class FileManager;
44 class HeaderSearch;
45 class HeaderSearchOptions;
46 class IdentifierTable;
47 class LangOptions;
48 class PCHContainerReader;
49 class Preprocessor;
50 class PreprocessorOptions;
51 class PreprocessorOutputOptions;
52 class SourceManager;
53 class Stmt;
54 class TargetInfo;
55 class FrontendOptions;
56 
57 /// Apply the header search options to get given HeaderSearch object.
58 void ApplyHeaderSearchOptions(HeaderSearch &HS,
59  const HeaderSearchOptions &HSOpts,
60  const LangOptions &Lang,
61  const llvm::Triple &triple);
62 
63 /// InitializePreprocessor - Initialize the preprocessor getting it and the
64 /// environment ready to process a single file.
65 void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts,
66  const PCHContainerReader &PCHContainerRdr,
67  const FrontendOptions &FEOpts);
68 
69 /// DoPrintPreprocessedInput - Implement -E mode.
70 void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream* OS,
71  const PreprocessorOutputOptions &Opts);
72 
73 /// An interface for collecting the dependencies of a compilation. Users should
74 /// use \c attachToPreprocessor and \c attachToASTReader to get all of the
75 /// dependencies.
76 // FIXME: Migrate DependencyFileGen, DependencyGraphGen, ModuleDepCollectory to
77 // use this interface.
79 public:
82  llvm::ArrayRef<std::string> getDependencies() const { return Dependencies; }
83 
84  /// Called when a new file is seen. Return true if \p Filename should be added
85  /// to the list of dependencies.
86  ///
87  /// The default implementation ignores <built-in> and system files.
88  virtual bool sawDependency(StringRef Filename, bool FromModule,
89  bool IsSystem, bool IsModuleFile, bool IsMissing);
90  /// Called when the end of the main file is reached.
91  virtual void finishedMainFile() { }
92  /// Return true if system files should be passed to sawDependency().
93  virtual bool needSystemDependencies() { return false; }
94  virtual ~DependencyCollector();
95 
96 public: // implementation detail
97  /// Add a dependency \p Filename if it has not been seen before and
98  /// sawDependency() returns true.
99  void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem,
100  bool IsModuleFile, bool IsMissing);
101 private:
102  llvm::StringSet<> Seen;
103  std::vector<std::string> Dependencies;
104 };
105 
106 /// Builds a depdenency file when attached to a Preprocessor (for includes) and
107 /// ASTReader (for module imports), and writes it out at the end of processing
108 /// a source file. Users should attach to the ast reader whenever a module is
109 /// loaded.
111  void *Impl; // Opaque implementation
112  DependencyFileGenerator(void *Impl);
113 public:
115  Preprocessor &PP, const DependencyOutputOptions &Opts);
116  void AttachToASTReader(ASTReader &R);
117 };
118 
119 /// Collects the dependencies for imported modules into a directory. Users
120 /// should attach to the AST reader whenever a module is loaded.
122  std::string DestDir;
123  bool HasErrors;
124  llvm::StringSet<> Seen;
125  vfs::YAMLVFSWriter VFSWriter;
126 
127 public:
128  StringRef getDest() { return DestDir; }
129  bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
130  void setHasErrors() { HasErrors = true; }
131  void addFileMapping(StringRef VPath, StringRef RPath) {
132  VFSWriter.addFileMapping(VPath, RPath);
133  }
134 
135  void attachToASTReader(ASTReader &R);
136  void writeFileMap();
137  bool hasErrors() { return HasErrors; }
138  ModuleDependencyCollector(std::string DestDir)
139  : DestDir(DestDir), HasErrors(false) {}
141 };
142 
143 /// AttachDependencyGraphGen - Create a dependency graph generator, and attach
144 /// it to the given preprocessor.
145  void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
146  StringRef SysRoot);
147 
148 /// AttachHeaderIncludeGen - Create a header include list generator, and attach
149 /// it to the given preprocessor.
150 ///
151 /// \param ExtraHeaders - If not empty, will write the header filenames, just
152 /// like they were included during a regular preprocessing. Useful for
153 /// implicit include dependencies, like sanitizer blacklists.
154 /// \param ShowAllHeaders - If true, show all header information instead of just
155 /// headers following the predefines buffer. This is useful for making sure
156 /// includes mentioned on the command line are also reported, but differs from
157 /// the default behavior used by -H.
158 /// \param OutputPath - If non-empty, a path to write the header include
159 /// information to, instead of writing to stderr.
160 /// \param ShowDepth - Whether to indent to show the nesting of the includes.
161 /// \param MSStyle - Whether to print in cl.exe /showIncludes style.
162 void AttachHeaderIncludeGen(Preprocessor &PP,
163  const std::vector<std::string> &ExtraHeaders,
164  bool ShowAllHeaders = false,
165  StringRef OutputPath = "",
166  bool ShowDepth = true, bool MSStyle = false);
167 
168 /// Cache tokens for use with PCH. Note that this requires a seekable stream.
169 void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS);
170 
171 /// The ChainedIncludesSource class converts headers to chained PCHs in
172 /// memory, mainly for testing.
173 IntrusiveRefCntPtr<ExternalSemaSource>
174 createChainedIncludesSource(CompilerInstance &CI,
175  IntrusiveRefCntPtr<ExternalSemaSource> &Reader);
176 
177 /// createInvocationFromCommandLine - Construct a compiler invocation object for
178 /// a command line argument vector.
179 ///
180 /// \return A CompilerInvocation, or 0 if none was built for the given
181 /// argument vector.
182 CompilerInvocation *
183 createInvocationFromCommandLine(ArrayRef<const char *> Args,
184  IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
185  IntrusiveRefCntPtr<DiagnosticsEngine>());
186 
187 /// Return the value of the last argument as an integer, or a default. If Diags
188 /// is non-null, emits an error if the argument is given, but non-integral.
189 int getLastArgIntValue(const llvm::opt::ArgList &Args,
190  llvm::opt::OptSpecifier Id, int Default,
191  DiagnosticsEngine *Diags = nullptr);
192 
193 inline int getLastArgIntValue(const llvm::opt::ArgList &Args,
194  llvm::opt::OptSpecifier Id, int Default,
195  DiagnosticsEngine &Diags) {
196  return getLastArgIntValue(Args, Id, Default, &Diags);
197 }
198 
199 uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
200  llvm::opt::OptSpecifier Id, uint64_t Default,
201  DiagnosticsEngine *Diags = nullptr);
202 
203 inline uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
204  llvm::opt::OptSpecifier Id,
205  uint64_t Default,
206  DiagnosticsEngine &Diags) {
207  return getLastArgUInt64Value(Args, Id, Default, &Diags);
208 }
209 
210 // When Clang->getFrontendOpts().DisableFree is set we don't delete some of the
211 // global objects, but we don't want LeakDetectors to complain, so we bury them
212 // in a globally visible array.
213 void BuryPointer(const void *Ptr);
214 template <typename T> void BuryPointer(std::unique_ptr<T> Ptr) {
215  BuryPointer(Ptr.release());
216 }
217 
218 } // end namespace clang
219 
220 #endif
llvm::ArrayRef< std::string > getDependencies() const
Definition: Utils.h:82
IntrusiveRefCntPtr< ExternalSemaSource > createChainedIncludesSource(CompilerInstance &CI, IntrusiveRefCntPtr< ExternalSemaSource > &Reader)
The ChainedIncludesSource class converts headers to chained PCHs in memory, mainly for testing...
An interface for collecting the dependencies of a compilation.
Definition: Utils.h:78
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
virtual bool needSystemDependencies()
Return true if system files should be passed to sawDependency().
Definition: Utils.h:93
void attachToASTReader(ASTReader &R)
void addFileMapping(StringRef VirtualPath, StringRef RealPath)
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
void AttachHeaderIncludeGen(Preprocessor &PP, const std::vector< std::string > &ExtraHeaders, bool ShowAllHeaders=false, StringRef OutputPath="", bool ShowDepth=true, bool MSStyle=false)
AttachHeaderIncludeGen - Create a header include list generator, and attach it to the given preproces...
void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS)
Cache tokens for use with PCH. Note that this requires a seekable stream.
ModuleDependencyCollector(std::string DestDir)
Definition: Utils.h:138
Builds a depdenency file when attached to a Preprocessor (for includes) and ASTReader (for module imp...
Definition: Utils.h:110
static DependencyFileGenerator * CreateAndAttachToPreprocessor(Preprocessor &PP, const DependencyOutputOptions &Opts)
StringRef Filename
Definition: Format.cpp:1723
uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, uint64_t Default, DiagnosticsEngine *Diags=nullptr)
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts)
DoPrintPreprocessedInput - Implement -E mode.
void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem, bool IsModuleFile, bool IsMissing)
Add a dependency Filename if it has not been seen before and sawDependency() returns true...
void addFileMapping(StringRef VPath, StringRef RPath)
Definition: Utils.h:131
virtual void finishedMainFile()
Called when the end of the main file is reached.
Definition: Utils.h:91
Collects the dependencies for imported modules into a directory.
Definition: Utils.h:121
#define false
Definition: stdbool.h:33
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
void AttachToASTReader(ASTReader &R)
void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile, StringRef SysRoot)
AttachDependencyGraphGen - Create a dependency graph generator, and attach it to the given preprocess...
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:311
CompilerInvocation * createInvocationFromCommandLine(ArrayRef< const char * > Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >())
createInvocationFromCommandLine - Construct a compiler invocation object for a command line argument ...
Defines the virtual file system interface vfs::FileSystem.
Defines the Diagnostic-related interfaces.
void BuryPointer(const void *Ptr)
void attachToPreprocessor(Preprocessor &PP)
int getLastArgIntValue(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, int Default, DiagnosticsEngine *Diags=nullptr)
Return the value of the last argument as an integer, or a default.
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
virtual bool sawDependency(StringRef Filename, bool FromModule, bool IsSystem, bool IsModuleFile, bool IsMissing)
Called when a new file is seen.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:96
bool insertSeen(StringRef Filename)
Definition: Utils.h:129