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"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/IntrusiveRefCntPtr.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/Option/OptSpecifier.h"
25 #include "llvm/Support/VirtualFileSystem.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.
83 class DependencyCollector {
84 public:
85   virtual ~DependencyCollector();
86 
87   virtual void attachToPreprocessor(Preprocessor &PP);
88   virtual void attachToASTReader(ASTReader &R);
getDependencies()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.
finishedMainFile()99   virtual void finishedMainFile() {}
100 
101   /// Return true if system files should be passed to sawDependency().
needSystemDependencies()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.
119 class DependencyFileGenerator {
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.
133 class ModuleDependencyCollector : public DependencyCollector {
134   std::string DestDir;
135   bool HasErrors = false;
136   llvm::StringSet<> Seen;
137   llvm::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:
ModuleDependencyCollector(std::string DestDir)144   ModuleDependencyCollector(std::string DestDir)
145       : DestDir(std::move(DestDir)) {}
~ModuleDependencyCollector()146   ~ModuleDependencyCollector() override { writeFileMap(); }
147 
getDest()148   StringRef getDest() { return DestDir; }
insertSeen(StringRef Filename)149   bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
150   void addFile(StringRef Filename, StringRef FileDst = {});
151 
addFileMapping(StringRef VPath,StringRef RPath)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();
hasErrors()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.
180 void AttachHeaderIncludeGen(Preprocessor &PP,
181                             const DependencyOutputOptions &DepOpts,
182                             bool ShowAllHeaders = false,
183                             StringRef OutputPath = {},
184                             bool ShowDepth = true, bool MSStyle = false);
185 
186 /// The ChainedIncludesSource class converts headers to chained PCHs in
187 /// memory, mainly for testing.
188 IntrusiveRefCntPtr<ExternalSemaSource>
189 createChainedIncludesSource(CompilerInstance &CI,
190                             IntrusiveRefCntPtr<ExternalSemaSource> &Reader);
191 
192 /// createInvocationFromCommandLine - Construct a compiler invocation object for
193 /// a command line argument vector.
194 ///
195 /// \return A CompilerInvocation, or 0 if none was built for the given
196 /// argument vector.
197 std::unique_ptr<CompilerInvocation> createInvocationFromCommandLine(
198     ArrayRef<const char *> Args,
199     IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
200         IntrusiveRefCntPtr<DiagnosticsEngine>(),
201     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
202 
203 /// Return the value of the last argument as an integer, or a default. If Diags
204 /// is non-null, emits an error if the argument is given, but non-integral.
205 int getLastArgIntValue(const llvm::opt::ArgList &Args,
206                        llvm::opt::OptSpecifier Id, int Default,
207                        DiagnosticsEngine *Diags = nullptr);
208 
getLastArgIntValue(const llvm::opt::ArgList & Args,llvm::opt::OptSpecifier Id,int Default,DiagnosticsEngine & Diags)209 inline int getLastArgIntValue(const llvm::opt::ArgList &Args,
210                               llvm::opt::OptSpecifier Id, int Default,
211                               DiagnosticsEngine &Diags) {
212   return getLastArgIntValue(Args, Id, Default, &Diags);
213 }
214 
215 uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
216                                llvm::opt::OptSpecifier Id, uint64_t Default,
217                                DiagnosticsEngine *Diags = nullptr);
218 
getLastArgUInt64Value(const llvm::opt::ArgList & Args,llvm::opt::OptSpecifier Id,uint64_t Default,DiagnosticsEngine & Diags)219 inline uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
220                                       llvm::opt::OptSpecifier Id,
221                                       uint64_t Default,
222                                       DiagnosticsEngine &Diags) {
223   return getLastArgUInt64Value(Args, Id, Default, &Diags);
224 }
225 
226 // Frontend timing utils
227 
228 /// If the user specifies the -ftime-report argument on an Clang command line
229 /// then the value of this boolean will be true, otherwise false.
230 extern bool FrontendTimesIsEnabled;
231 
232 } // namespace clang
233 
234 #endif // LLVM_CLANG_FRONTEND_UTILS_H
235