1 //===- Utils.h - Misc utilities for the front-end ---------------*- 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 header contains miscellaneous utilities for various front-end actions.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_FRONTEND_UTILS_H
15 #define LLVM_CLANG_FRONTEND_UTILS_H
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Basic/VirtualFileSystem.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"
29 #include <system_error>
48 class CompilerInstance;
49 class CompilerInvocation;
50 class DependencyOutputOptions;
51 class DiagnosticsEngine;
52 class ExternalSemaSource;
53 class FrontendOptions;
55 class HeaderSearchOptions;
57 class PCHContainerReader;
59 class PreprocessorOptions;
60 class PreprocessorOutputOptions;
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);
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);
74 /// DoPrintPreprocessedInput - Implement -E mode.
75 void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
76 const PreprocessorOutputOptions &Opts);
78 /// An interface for collecting the dependencies of a compilation. Users should
79 /// use \c attachToPreprocessor and \c attachToASTReader to get all of the
81 /// FIXME: Migrate DependencyFileGen and DependencyGraphGen to use this
83 class DependencyCollector {
85 virtual ~DependencyCollector();
87 virtual void attachToPreprocessor(Preprocessor &PP);
88 virtual void attachToASTReader(ASTReader &R);
89 ArrayRef<std::string> getDependencies() const { return Dependencies; }
91 /// Called when a new file is seen. Return true if \p Filename should be added
92 /// to the list of dependencies.
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);
98 /// Called when the end of the main file is reached.
99 virtual void finishedMainFile() {}
101 /// Return true if system files should be passed to sawDependency().
102 virtual bool needSystemDependencies() { return false; }
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);
111 llvm::StringSet<> Seen;
112 std::vector<std::string> Dependencies;
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
119 class DependencyFileGenerator {
120 void *Impl; // Opaque implementation
122 DependencyFileGenerator(void *Impl);
125 static DependencyFileGenerator *CreateAndAttachToPreprocessor(
126 Preprocessor &PP, const DependencyOutputOptions &Opts);
128 void AttachToASTReader(ASTReader &R);
131 /// Collects the dependencies for imported modules into a directory. Users
132 /// should attach to the AST reader whenever a module is loaded.
133 class ModuleDependencyCollector : public DependencyCollector {
135 bool HasErrors = false;
136 llvm::StringSet<> Seen;
137 vfs::YAMLVFSWriter VFSWriter;
138 llvm::StringMap<std::string> SymLinkMap;
140 bool getRealPath(StringRef SrcPath, SmallVectorImpl<char> &Result);
141 std::error_code copyToRoot(StringRef Src, StringRef Dst = {});
144 ModuleDependencyCollector(std::string DestDir)
145 : DestDir(std::move(DestDir)) {}
146 ~ModuleDependencyCollector() override { writeFileMap(); }
148 StringRef getDest() { return DestDir; }
149 bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
150 void addFile(StringRef Filename, StringRef FileDst = {});
152 void addFileMapping(StringRef VPath, StringRef RPath) {
153 VFSWriter.addFileMapping(VPath, RPath);
156 void attachToPreprocessor(Preprocessor &PP) override;
157 void attachToASTReader(ASTReader &R) override;
160 bool hasErrors() { return HasErrors; }
163 /// AttachDependencyGraphGen - Create a dependency graph generator, and attach
164 /// it to the given preprocessor.
165 void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
168 /// AttachHeaderIncludeGen - Create a header include list generator, and attach
169 /// it to the given preprocessor.
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.
180 void AttachHeaderIncludeGen(Preprocessor &PP,
181 const DependencyOutputOptions &DepOpts,
182 bool ShowAllHeaders = false,
183 StringRef OutputPath = {},
184 bool ShowDepth = true, bool MSStyle = false);
186 /// Cache tokens for use with PCH. Note that this requires a seekable stream.
187 void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS);
189 /// The ChainedIncludesSource class converts headers to chained PCHs in
190 /// memory, mainly for testing.
191 IntrusiveRefCntPtr<ExternalSemaSource>
192 createChainedIncludesSource(CompilerInstance &CI,
193 IntrusiveRefCntPtr<ExternalSemaSource> &Reader);
195 /// createInvocationFromCommandLine - Construct a compiler invocation object for
196 /// a command line argument vector.
198 /// \return A CompilerInvocation, or 0 if none was built for the given
200 std::unique_ptr<CompilerInvocation> createInvocationFromCommandLine(
201 ArrayRef<const char *> Args,
202 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
203 IntrusiveRefCntPtr<DiagnosticsEngine>(),
204 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
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);
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);
218 uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
219 llvm::opt::OptSpecifier Id, uint64_t Default,
220 DiagnosticsEngine *Diags = nullptr);
222 inline uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
223 llvm::opt::OptSpecifier Id,
225 DiagnosticsEngine &Diags) {
226 return getLastArgUInt64Value(Args, Id, Default, &Diags);
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());
237 // Frontend timing utils
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;
245 #endif // LLVM_CLANG_FRONTEND_UTILS_H