clang  7.0.0svn
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"
18 #include "clang/Basic/LLVM.h"
20 #include "llvm/ADT/IntrusiveRefCntPtr.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/Option/OptSpecifier.h"
26 #include <cstdint>
27 #include <memory>
28 #include <string>
29 #include <system_error>
30 #include <utility>
31 #include <vector>
32 
33 namespace llvm {
34 
35 class Triple;
36 
37 namespace opt {
38 
39 class ArgList;
40 
41 } // namespace opt
42 
43 } // namespace llvm
44 
45 namespace clang {
46 
47 class ASTReader;
48 class CompilerInstance;
49 class CompilerInvocation;
50 class DependencyOutputOptions;
51 class DiagnosticsEngine;
52 class ExternalSemaSource;
53 class FrontendOptions;
54 class HeaderSearch;
55 class HeaderSearchOptions;
56 class LangOptions;
57 class PCHContainerReader;
58 class Preprocessor;
59 class PreprocessorOptions;
60 class PreprocessorOutputOptions;
61 
62 /// Apply the header search options to get given HeaderSearch object.
63 void ApplyHeaderSearchOptions(HeaderSearch &HS,
64  const HeaderSearchOptions &HSOpts,
65  const LangOptions &Lang,
66  const llvm::Triple &triple);
67 
68 /// InitializePreprocessor - Initialize the preprocessor getting it and the
69 /// environment ready to process a single file.
70 void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts,
71  const PCHContainerReader &PCHContainerRdr,
72  const FrontendOptions &FEOpts);
73 
74 /// DoPrintPreprocessedInput - Implement -E mode.
75 void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
76  const PreprocessorOutputOptions &Opts);
77 
78 /// An interface for collecting the dependencies of a compilation. Users should
79 /// use \c attachToPreprocessor and \c attachToASTReader to get all of the
80 /// dependencies.
81 /// FIXME: Migrate DependencyFileGen and DependencyGraphGen to use this
82 /// interface.
84 public:
85  virtual ~DependencyCollector();
86 
87  virtual void attachToPreprocessor(Preprocessor &PP);
88  virtual void attachToASTReader(ASTReader &R);
89  ArrayRef<std::string> getDependencies() const { return Dependencies; }
90 
91  /// Called when a new file is seen. Return true if \p Filename should be added
92  /// to the list of dependencies.
93  ///
94  /// The default implementation ignores <built-in> and system files.
95  virtual bool sawDependency(StringRef Filename, bool FromModule,
96  bool IsSystem, bool IsModuleFile, bool IsMissing);
97 
98  /// Called when the end of the main file is reached.
99  virtual void finishedMainFile() {}
100 
101  /// Return true if system files should be passed to sawDependency().
102  virtual bool needSystemDependencies() { return false; }
103 
104  // implementation detail
105  /// Add a dependency \p Filename if it has not been seen before and
106  /// sawDependency() returns true.
107  void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem,
108  bool IsModuleFile, bool IsMissing);
109 
110 private:
111  llvm::StringSet<> Seen;
112  std::vector<std::string> Dependencies;
113 };
114 
115 /// Builds a depdenency file when attached to a Preprocessor (for includes) and
116 /// ASTReader (for module imports), and writes it out at the end of processing
117 /// a source file. Users should attach to the ast reader whenever a module is
118 /// loaded.
120  void *Impl; // Opaque implementation
121 
122  DependencyFileGenerator(void *Impl);
123 
124 public:
125  static DependencyFileGenerator *CreateAndAttachToPreprocessor(
126  Preprocessor &PP, const DependencyOutputOptions &Opts);
127 
128  void AttachToASTReader(ASTReader &R);
129 };
130 
131 /// Collects the dependencies for imported modules into a directory. Users
132 /// should attach to the AST reader whenever a module is loaded.
134  std::string DestDir;
135  bool HasErrors = false;
136  llvm::StringSet<> Seen;
137  vfs::YAMLVFSWriter VFSWriter;
138  llvm::StringMap<std::string> SymLinkMap;
139 
140  bool getRealPath(StringRef SrcPath, SmallVectorImpl<char> &Result);
141  std::error_code copyToRoot(StringRef Src, StringRef Dst = {});
142 
143 public:
144  ModuleDependencyCollector(std::string DestDir)
145  : DestDir(std::move(DestDir)) {}
146  ~ModuleDependencyCollector() override { writeFileMap(); }
147 
148  StringRef getDest() { return DestDir; }
149  bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
150  void addFile(StringRef Filename, StringRef FileDst = {});
151 
152  void addFileMapping(StringRef VPath, StringRef RPath) {
153  VFSWriter.addFileMapping(VPath, RPath);
154  }
155 
156  void attachToPreprocessor(Preprocessor &PP) override;
157  void attachToASTReader(ASTReader &R) override;
158 
159  void writeFileMap();
160  bool hasErrors() { return HasErrors; }
161 };
162 
163 /// AttachDependencyGraphGen - Create a dependency graph generator, and attach
164 /// it to the given preprocessor.
165 void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
166  StringRef SysRoot);
167 
168 /// AttachHeaderIncludeGen - Create a header include list generator, and attach
169 /// it to the given preprocessor.
170 ///
171 /// \param DepOpts - Options controlling the output.
172 /// \param ShowAllHeaders - If true, show all header information instead of just
173 /// headers following the predefines buffer. This is useful for making sure
174 /// includes mentioned on the command line are also reported, but differs from
175 /// the default behavior used by -H.
176 /// \param OutputPath - If non-empty, a path to write the header include
177 /// information to, instead of writing to stderr.
178 /// \param ShowDepth - Whether to indent to show the nesting of the includes.
179 /// \param MSStyle - Whether to print in cl.exe /showIncludes style.
181  const DependencyOutputOptions &DepOpts,
182  bool ShowAllHeaders = false,
183  StringRef OutputPath = {},
184  bool ShowDepth = true, bool MSStyle = false);
185 
186 /// Cache tokens for use with PCH. Note that this requires a seekable stream.
187 void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS);
188 
189 /// The ChainedIncludesSource class converts headers to chained PCHs in
190 /// memory, mainly for testing.
194 
195 /// createInvocationFromCommandLine - Construct a compiler invocation object for
196 /// a command line argument vector.
197 ///
198 /// \return A CompilerInvocation, or 0 if none was built for the given
199 /// argument vector.
200 std::unique_ptr<CompilerInvocation> createInvocationFromCommandLine(
205 
206 /// Return the value of the last argument as an integer, or a default. If Diags
207 /// is non-null, emits an error if the argument is given, but non-integral.
208 int getLastArgIntValue(const llvm::opt::ArgList &Args,
209  llvm::opt::OptSpecifier Id, int Default,
210  DiagnosticsEngine *Diags = nullptr);
211 
212 inline int getLastArgIntValue(const llvm::opt::ArgList &Args,
213  llvm::opt::OptSpecifier Id, int Default,
214  DiagnosticsEngine &Diags) {
215  return getLastArgIntValue(Args, Id, Default, &Diags);
216 }
217 
218 uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
219  llvm::opt::OptSpecifier Id, uint64_t Default,
220  DiagnosticsEngine *Diags = nullptr);
221 
222 inline uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
223  llvm::opt::OptSpecifier Id,
224  uint64_t Default,
225  DiagnosticsEngine &Diags) {
226  return getLastArgUInt64Value(Args, Id, Default, &Diags);
227 }
228 
229 // When Clang->getFrontendOpts().DisableFree is set we don't delete some of the
230 // global objects, but we don't want LeakDetectors to complain, so we bury them
231 // in a globally visible array.
232 void BuryPointer(const void *Ptr);
233 template <typename T> void BuryPointer(std::unique_ptr<T> Ptr) {
234  BuryPointer(Ptr.release());
235 }
236 
237 // Frontend timing utils
238 
239 /// If the user specifies the -ftime-report argument on an Clang command line
240 /// then the value of this boolean will be true, otherwise false.
241 extern bool FrontendTimesIsEnabled;
242 
243 } // namespace clang
244 
245 #endif // LLVM_CLANG_FRONTEND_UTILS_H
IntrusiveRefCntPtr< ExternalSemaSource > createChainedIncludesSource(CompilerInstance &CI, IntrusiveRefCntPtr< ExternalSemaSource > &Reader)
The ChainedIncludesSource class converts headers to chained PCHs in memory, mainly for testing...
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
An interface for collecting the dependencies of a compilation.
Definition: Utils.h:83
Definition: Format.h:2022
virtual bool needSystemDependencies()
Return true if system files should be passed to sawDependency().
Definition: Utils.h:102
void addFileMapping(StringRef VirtualPath, StringRef RealPath)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
Defines the Diagnostic-related interfaces.
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:144
Builds a depdenency file when attached to a Preprocessor (for includes) and ASTReader (for module imp...
Definition: Utils.h:119
uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, uint64_t Default, DiagnosticsEngine &Diags)
Definition: Utils.h:222
StringRef Filename
Definition: Format.cpp:1598
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts)
DoPrintPreprocessedInput - Implement -E mode.
ArrayRef< std::string > getDependencies() const
Definition: Utils.h:89
void addFileMapping(StringRef VPath, StringRef RPath)
Definition: Utils.h:152
int Id
Definition: ASTDiff.cpp:191
virtual void finishedMainFile()
Called when the end of the main file is reached.
Definition: Utils.h:99
void AttachHeaderIncludeGen(Preprocessor &PP, const DependencyOutputOptions &DepOpts, 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...
Collects the dependencies for imported modules into a directory.
Definition: Utils.h:133
std::unique_ptr< CompilerInvocation > createInvocationFromCommandLine(ArrayRef< const char *> Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >(), IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
createInvocationFromCommandLine - Construct a compiler invocation object for a command line argument ...
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
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.
void BuryPointer(std::unique_ptr< T > Ptr)
Definition: Utils.h:233
Dataflow Directional Tag Classes.
bool FrontendTimesIsEnabled
If the user specifies the -ftime-report argument on an Clang command line then the value of this bool...
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:354
Defines the virtual file system interface vfs::FileSystem.
~ModuleDependencyCollector() override
Definition: Utils.h:146
int getLastArgIntValue(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, int Default, DiagnosticsEngine &Diags)
Definition: Utils.h:212
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 ...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127
bool insertSeen(StringRef Filename)
Definition: Utils.h:149