Utils.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Utils.h - Misc utilities for the front-end ---------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This header contains miscellaneous utilities for various front-end actions.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_FRONTEND_UTILS_H
  18. #define LLVM_CLANG_FRONTEND_UTILS_H
  19. #include "clang/Basic/Diagnostic.h"
  20. #include "clang/Basic/LLVM.h"
  21. #include "clang/Driver/OptionUtils.h"
  22. #include "clang/Frontend/DependencyOutputOptions.h"
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  25. #include "llvm/ADT/StringMap.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/StringSet.h"
  28. #include "llvm/Support/FileCollector.h"
  29. #include "llvm/Support/VirtualFileSystem.h"
  30. #include <cstdint>
  31. #include <memory>
  32. #include <string>
  33. #include <system_error>
  34. #include <utility>
  35. #include <vector>
  36. namespace clang {
  37. class ASTReader;
  38. class CompilerInstance;
  39. class CompilerInvocation;
  40. class DiagnosticsEngine;
  41. class ExternalSemaSource;
  42. class FrontendOptions;
  43. class PCHContainerReader;
  44. class Preprocessor;
  45. class PreprocessorOptions;
  46. class PreprocessorOutputOptions;
  47. /// InitializePreprocessor - Initialize the preprocessor getting it and the
  48. /// environment ready to process a single file.
  49. void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts,
  50. const PCHContainerReader &PCHContainerRdr,
  51. const FrontendOptions &FEOpts);
  52. /// DoPrintPreprocessedInput - Implement -E mode.
  53. void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
  54. const PreprocessorOutputOptions &Opts);
  55. /// An interface for collecting the dependencies of a compilation. Users should
  56. /// use \c attachToPreprocessor and \c attachToASTReader to get all of the
  57. /// dependencies.
  58. /// FIXME: Migrate DependencyGraphGen to use this interface.
  59. class DependencyCollector {
  60. public:
  61. virtual ~DependencyCollector();
  62. virtual void attachToPreprocessor(Preprocessor &PP);
  63. virtual void attachToASTReader(ASTReader &R);
  64. ArrayRef<std::string> getDependencies() const { return Dependencies; }
  65. /// Called when a new file is seen. Return true if \p Filename should be added
  66. /// to the list of dependencies.
  67. ///
  68. /// The default implementation ignores <built-in> and system files.
  69. virtual bool sawDependency(StringRef Filename, bool FromModule,
  70. bool IsSystem, bool IsModuleFile, bool IsMissing);
  71. /// Called when the end of the main file is reached.
  72. virtual void finishedMainFile(DiagnosticsEngine &Diags) {}
  73. /// Return true if system files should be passed to sawDependency().
  74. virtual bool needSystemDependencies() { return false; }
  75. /// Add a dependency \p Filename if it has not been seen before and
  76. /// sawDependency() returns true.
  77. virtual void maybeAddDependency(StringRef Filename, bool FromModule,
  78. bool IsSystem, bool IsModuleFile,
  79. bool IsMissing);
  80. protected:
  81. /// Return true if the filename was added to the list of dependencies, false
  82. /// otherwise.
  83. bool addDependency(StringRef Filename);
  84. private:
  85. llvm::StringSet<> Seen;
  86. std::vector<std::string> Dependencies;
  87. };
  88. /// Builds a dependency file when attached to a Preprocessor (for includes) and
  89. /// ASTReader (for module imports), and writes it out at the end of processing
  90. /// a source file. Users should attach to the ast reader whenever a module is
  91. /// loaded.
  92. class DependencyFileGenerator : public DependencyCollector {
  93. public:
  94. DependencyFileGenerator(const DependencyOutputOptions &Opts);
  95. void attachToPreprocessor(Preprocessor &PP) override;
  96. void finishedMainFile(DiagnosticsEngine &Diags) override;
  97. bool needSystemDependencies() final { return IncludeSystemHeaders; }
  98. bool sawDependency(StringRef Filename, bool FromModule, bool IsSystem,
  99. bool IsModuleFile, bool IsMissing) final;
  100. protected:
  101. void outputDependencyFile(llvm::raw_ostream &OS);
  102. private:
  103. void outputDependencyFile(DiagnosticsEngine &Diags);
  104. std::string OutputFile;
  105. std::vector<std::string> Targets;
  106. bool IncludeSystemHeaders;
  107. bool PhonyTarget;
  108. bool AddMissingHeaderDeps;
  109. bool SeenMissingHeader;
  110. bool IncludeModuleFiles;
  111. DependencyOutputFormat OutputFormat;
  112. unsigned InputFileIndex;
  113. };
  114. /// Collects the dependencies for imported modules into a directory. Users
  115. /// should attach to the AST reader whenever a module is loaded.
  116. class ModuleDependencyCollector : public DependencyCollector {
  117. std::string DestDir;
  118. bool HasErrors = false;
  119. llvm::StringSet<> Seen;
  120. llvm::vfs::YAMLVFSWriter VFSWriter;
  121. llvm::FileCollector::PathCanonicalizer Canonicalizer;
  122. std::error_code copyToRoot(StringRef Src, StringRef Dst = {});
  123. public:
  124. ModuleDependencyCollector(std::string DestDir)
  125. : DestDir(std::move(DestDir)) {}
  126. ~ModuleDependencyCollector() override { writeFileMap(); }
  127. StringRef getDest() { return DestDir; }
  128. virtual bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
  129. virtual void addFile(StringRef Filename, StringRef FileDst = {});
  130. virtual void addFileMapping(StringRef VPath, StringRef RPath) {
  131. VFSWriter.addFileMapping(VPath, RPath);
  132. }
  133. void attachToPreprocessor(Preprocessor &PP) override;
  134. void attachToASTReader(ASTReader &R) override;
  135. virtual void writeFileMap();
  136. virtual bool hasErrors() { return HasErrors; }
  137. };
  138. /// AttachDependencyGraphGen - Create a dependency graph generator, and attach
  139. /// it to the given preprocessor.
  140. void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
  141. StringRef SysRoot);
  142. /// AttachHeaderIncludeGen - Create a header include list generator, and attach
  143. /// it to the given preprocessor.
  144. ///
  145. /// \param DepOpts - Options controlling the output.
  146. /// \param ShowAllHeaders - If true, show all header information instead of just
  147. /// headers following the predefines buffer. This is useful for making sure
  148. /// includes mentioned on the command line are also reported, but differs from
  149. /// the default behavior used by -H.
  150. /// \param OutputPath - If non-empty, a path to write the header include
  151. /// information to, instead of writing to stderr.
  152. /// \param ShowDepth - Whether to indent to show the nesting of the includes.
  153. /// \param MSStyle - Whether to print in cl.exe /showIncludes style.
  154. void AttachHeaderIncludeGen(Preprocessor &PP,
  155. const DependencyOutputOptions &DepOpts,
  156. bool ShowAllHeaders = false,
  157. StringRef OutputPath = {},
  158. bool ShowDepth = true, bool MSStyle = false);
  159. /// The ChainedIncludesSource class converts headers to chained PCHs in
  160. /// memory, mainly for testing.
  161. IntrusiveRefCntPtr<ExternalSemaSource>
  162. createChainedIncludesSource(CompilerInstance &CI,
  163. IntrusiveRefCntPtr<ExternalSemaSource> &Reader);
  164. /// Optional inputs to createInvocation.
  165. struct CreateInvocationOptions {
  166. /// Receives diagnostics encountered while parsing command-line flags.
  167. /// If not provided, these are printed to stderr.
  168. IntrusiveRefCntPtr<DiagnosticsEngine> Diags = nullptr;
  169. /// Used e.g. to probe for system headers locations.
  170. /// If not provided, the real filesystem is used.
  171. /// FIXME: the driver does perform some non-virtualized IO.
  172. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr;
  173. /// Whether to attempt to produce a non-null (possibly incorrect) invocation
  174. /// if any errors were encountered.
  175. /// By default, always return null on errors.
  176. bool RecoverOnError = false;
  177. /// Allow the driver to probe the filesystem for PCH files.
  178. /// This is used to replace -include with -include-pch in the cc1 args.
  179. /// FIXME: ProbePrecompiled=true is a poor, historical default.
  180. /// It misbehaves if the PCH file is from GCC, has the wrong version, etc.
  181. bool ProbePrecompiled = false;
  182. /// If set, the target is populated with the cc1 args produced by the driver.
  183. /// This may be populated even if createInvocation returns nullptr.
  184. std::vector<std::string> *CC1Args = nullptr;
  185. };
  186. /// Interpret clang arguments in preparation to parse a file.
  187. ///
  188. /// This simulates a number of steps Clang takes when its driver is invoked:
  189. /// - choosing actions (e.g compile + link) to run
  190. /// - probing the system for settings like standard library locations
  191. /// - spawning a cc1 subprocess to compile code, with more explicit arguments
  192. /// - in the cc1 process, assembling those arguments into a CompilerInvocation
  193. /// which is used to configure the parser
  194. ///
  195. /// This simulation is lossy, e.g. in some situations one driver run would
  196. /// result in multiple parses. (Multi-arch, CUDA, ...).
  197. /// This function tries to select a reasonable invocation that tools should use.
  198. ///
  199. /// Args[0] should be the driver name, such as "clang" or "/usr/bin/g++".
  200. /// Absolute path is preferred - this affects searching for system headers.
  201. ///
  202. /// May return nullptr if an invocation could not be determined.
  203. /// See CreateInvocationOptions::ShouldRecoverOnErrors to try harder!
  204. std::unique_ptr<CompilerInvocation>
  205. createInvocation(ArrayRef<const char *> Args,
  206. CreateInvocationOptions Opts = {});
  207. } // namespace clang
  208. #endif // LLVM_CLANG_FRONTEND_UTILS_H
  209. #ifdef __GNUC__
  210. #pragma GCC diagnostic pop
  211. #endif