FrontendOptions.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- FrontendOptions.h ----------------------------------------*- 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. #ifndef LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
  14. #define LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
  15. #include "clang/AST/ASTDumperUtils.h"
  16. #include "clang/Basic/LangStandard.h"
  17. #include "clang/Frontend/CommandLineSourceLoc.h"
  18. #include "clang/Sema/CodeCompleteOptions.h"
  19. #include "clang/Serialization/ModuleFileExtension.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/Support/MemoryBuffer.h"
  22. #include <cassert>
  23. #include <map>
  24. #include <memory>
  25. #include <optional>
  26. #include <string>
  27. #include <vector>
  28. namespace llvm {
  29. class MemoryBuffer;
  30. } // namespace llvm
  31. namespace clang {
  32. namespace frontend {
  33. enum ActionKind {
  34. /// Parse ASTs and list Decl nodes.
  35. ASTDeclList,
  36. /// Parse ASTs and dump them.
  37. ASTDump,
  38. /// Parse ASTs and print them.
  39. ASTPrint,
  40. /// Parse ASTs and view them in Graphviz.
  41. ASTView,
  42. /// Dump the compiler configuration.
  43. DumpCompilerOptions,
  44. /// Dump out raw tokens.
  45. DumpRawTokens,
  46. /// Dump out preprocessed tokens.
  47. DumpTokens,
  48. /// Emit a .s file.
  49. EmitAssembly,
  50. /// Emit a .bc file.
  51. EmitBC,
  52. /// Translate input source into HTML.
  53. EmitHTML,
  54. /// Emit a .ll file.
  55. EmitLLVM,
  56. /// Generate LLVM IR, but do not emit anything.
  57. EmitLLVMOnly,
  58. /// Generate machine code, but don't emit anything.
  59. EmitCodeGenOnly,
  60. /// Emit a .o file.
  61. EmitObj,
  62. // Extract API information
  63. ExtractAPI,
  64. /// Parse and apply any fixits to the source.
  65. FixIt,
  66. /// Generate pre-compiled module from a module map.
  67. GenerateModule,
  68. /// Generate pre-compiled module from a C++ module interface file.
  69. GenerateModuleInterface,
  70. /// Generate a C++20 header unit module from a header file.
  71. GenerateHeaderUnit,
  72. /// Generate pre-compiled header.
  73. GeneratePCH,
  74. /// Generate Interface Stub Files.
  75. GenerateInterfaceStubs,
  76. /// Only execute frontend initialization.
  77. InitOnly,
  78. /// Dump information about a module file.
  79. ModuleFileInfo,
  80. /// Load and verify that a PCH file is usable.
  81. VerifyPCH,
  82. /// Parse and perform semantic analysis.
  83. ParseSyntaxOnly,
  84. /// Run a plugin action, \see ActionName.
  85. PluginAction,
  86. /// Print the "preamble" of the input file
  87. PrintPreamble,
  88. /// -E mode.
  89. PrintPreprocessedInput,
  90. /// Expand macros but not \#includes.
  91. RewriteMacros,
  92. /// ObjC->C Rewriter.
  93. RewriteObjC,
  94. /// Rewriter playground
  95. RewriteTest,
  96. /// Run one or more source code analyses.
  97. RunAnalysis,
  98. /// Dump template instantiations
  99. TemplightDump,
  100. /// Run migrator.
  101. MigrateSource,
  102. /// Just lex, no output.
  103. RunPreprocessorOnly,
  104. /// Print the output of the dependency directives source minimizer.
  105. PrintDependencyDirectivesSourceMinimizerOutput
  106. };
  107. } // namespace frontend
  108. /// The kind of a file that we've been handed as an input.
  109. class InputKind {
  110. private:
  111. Language Lang;
  112. unsigned Fmt : 3;
  113. unsigned Preprocessed : 1;
  114. unsigned HeaderUnit : 3;
  115. unsigned IsHeader : 1;
  116. public:
  117. /// The input file format.
  118. enum Format {
  119. Source,
  120. ModuleMap,
  121. Precompiled
  122. };
  123. // If we are building a header unit, what kind it is; this affects whether
  124. // we look for the file in the user or system include search paths before
  125. // flagging a missing input.
  126. enum HeaderUnitKind {
  127. HeaderUnit_None,
  128. HeaderUnit_User,
  129. HeaderUnit_System,
  130. HeaderUnit_Abs
  131. };
  132. constexpr InputKind(Language L = Language::Unknown, Format F = Source,
  133. bool PP = false, HeaderUnitKind HU = HeaderUnit_None,
  134. bool HD = false)
  135. : Lang(L), Fmt(F), Preprocessed(PP), HeaderUnit(HU), IsHeader(HD) {}
  136. Language getLanguage() const { return static_cast<Language>(Lang); }
  137. Format getFormat() const { return static_cast<Format>(Fmt); }
  138. HeaderUnitKind getHeaderUnitKind() const {
  139. return static_cast<HeaderUnitKind>(HeaderUnit);
  140. }
  141. bool isPreprocessed() const { return Preprocessed; }
  142. bool isHeader() const { return IsHeader; }
  143. bool isHeaderUnit() const { return HeaderUnit != HeaderUnit_None; }
  144. /// Is the input kind fully-unknown?
  145. bool isUnknown() const { return Lang == Language::Unknown && Fmt == Source; }
  146. /// Is the language of the input some dialect of Objective-C?
  147. bool isObjectiveC() const {
  148. return Lang == Language::ObjC || Lang == Language::ObjCXX;
  149. }
  150. InputKind getPreprocessed() const {
  151. return InputKind(getLanguage(), getFormat(), true, getHeaderUnitKind(),
  152. isHeader());
  153. }
  154. InputKind getHeader() const {
  155. return InputKind(getLanguage(), getFormat(), isPreprocessed(),
  156. getHeaderUnitKind(), true);
  157. }
  158. InputKind withHeaderUnit(HeaderUnitKind HU) const {
  159. return InputKind(getLanguage(), getFormat(), isPreprocessed(), HU,
  160. isHeader());
  161. }
  162. InputKind withFormat(Format F) const {
  163. return InputKind(getLanguage(), F, isPreprocessed(), getHeaderUnitKind(),
  164. isHeader());
  165. }
  166. };
  167. /// An input file for the front end.
  168. class FrontendInputFile {
  169. /// The file name, or "-" to read from standard input.
  170. std::string File;
  171. /// The input, if it comes from a buffer rather than a file. This object
  172. /// does not own the buffer, and the caller is responsible for ensuring
  173. /// that it outlives any users.
  174. std::optional<llvm::MemoryBufferRef> Buffer;
  175. /// The kind of input, e.g., C source, AST file, LLVM IR.
  176. InputKind Kind;
  177. /// Whether we're dealing with a 'system' input (vs. a 'user' input).
  178. bool IsSystem = false;
  179. public:
  180. FrontendInputFile() = default;
  181. FrontendInputFile(StringRef File, InputKind Kind, bool IsSystem = false)
  182. : File(File.str()), Kind(Kind), IsSystem(IsSystem) {}
  183. FrontendInputFile(llvm::MemoryBufferRef Buffer, InputKind Kind,
  184. bool IsSystem = false)
  185. : Buffer(Buffer), Kind(Kind), IsSystem(IsSystem) {}
  186. InputKind getKind() const { return Kind; }
  187. bool isSystem() const { return IsSystem; }
  188. bool isEmpty() const { return File.empty() && Buffer == std::nullopt; }
  189. bool isFile() const { return !isBuffer(); }
  190. bool isBuffer() const { return Buffer != std::nullopt; }
  191. bool isPreprocessed() const { return Kind.isPreprocessed(); }
  192. bool isHeader() const { return Kind.isHeader(); }
  193. InputKind::HeaderUnitKind getHeaderUnitKind() const {
  194. return Kind.getHeaderUnitKind();
  195. }
  196. StringRef getFile() const {
  197. assert(isFile());
  198. return File;
  199. }
  200. llvm::MemoryBufferRef getBuffer() const {
  201. assert(isBuffer());
  202. return *Buffer;
  203. }
  204. };
  205. /// FrontendOptions - Options for controlling the behavior of the frontend.
  206. class FrontendOptions {
  207. public:
  208. /// Disable memory freeing on exit.
  209. unsigned DisableFree : 1;
  210. /// When generating PCH files, instruct the AST writer to create relocatable
  211. /// PCH files.
  212. unsigned RelocatablePCH : 1;
  213. /// Show the -help text.
  214. unsigned ShowHelp : 1;
  215. /// Show frontend performance metrics and statistics.
  216. unsigned ShowStats : 1;
  217. /// print the supported cpus for the current target
  218. unsigned PrintSupportedCPUs : 1;
  219. /// Output time trace profile.
  220. unsigned TimeTrace : 1;
  221. /// Show the -version text.
  222. unsigned ShowVersion : 1;
  223. /// Apply fixes even if there are unfixable errors.
  224. unsigned FixWhatYouCan : 1;
  225. /// Apply fixes only for warnings.
  226. unsigned FixOnlyWarnings : 1;
  227. /// Apply fixes and recompile.
  228. unsigned FixAndRecompile : 1;
  229. /// Apply fixes to temporary files.
  230. unsigned FixToTemporaries : 1;
  231. /// Emit ARC errors even if the migrator can fix them.
  232. unsigned ARCMTMigrateEmitARCErrors : 1;
  233. /// Skip over function bodies to speed up parsing in cases you do not need
  234. /// them (e.g. with code completion).
  235. unsigned SkipFunctionBodies : 1;
  236. /// Whether we can use the global module index if available.
  237. unsigned UseGlobalModuleIndex : 1;
  238. /// Whether we can generate the global module index if needed.
  239. unsigned GenerateGlobalModuleIndex : 1;
  240. /// Whether we include declaration dumps in AST dumps.
  241. unsigned ASTDumpDecls : 1;
  242. /// Whether we deserialize all decls when forming AST dumps.
  243. unsigned ASTDumpAll : 1;
  244. /// Whether we include lookup table dumps in AST dumps.
  245. unsigned ASTDumpLookups : 1;
  246. /// Whether we include declaration type dumps in AST dumps.
  247. unsigned ASTDumpDeclTypes : 1;
  248. /// Whether we are performing an implicit module build.
  249. unsigned BuildingImplicitModule : 1;
  250. /// Whether to use a filesystem lock when building implicit modules.
  251. unsigned BuildingImplicitModuleUsesLock : 1;
  252. /// Whether we should embed all used files into the PCM file.
  253. unsigned ModulesEmbedAllFiles : 1;
  254. /// Whether timestamps should be written to the produced PCH file.
  255. unsigned IncludeTimestamps : 1;
  256. /// Should a temporary file be used during compilation.
  257. unsigned UseTemporary : 1;
  258. /// When using -emit-module, treat the modulemap as a system module.
  259. unsigned IsSystemModule : 1;
  260. /// Output (and read) PCM files regardless of compiler errors.
  261. unsigned AllowPCMWithCompilerErrors : 1;
  262. /// Whether to share the FileManager when building modules.
  263. unsigned ModulesShareFileManager : 1;
  264. CodeCompleteOptions CodeCompleteOpts;
  265. /// Specifies the output format of the AST.
  266. ASTDumpOutputFormat ASTDumpFormat = ADOF_Default;
  267. enum {
  268. ARCMT_None,
  269. ARCMT_Check,
  270. ARCMT_Modify,
  271. ARCMT_Migrate
  272. } ARCMTAction = ARCMT_None;
  273. enum {
  274. ObjCMT_None = 0,
  275. /// Enable migration to modern ObjC literals.
  276. ObjCMT_Literals = 0x1,
  277. /// Enable migration to modern ObjC subscripting.
  278. ObjCMT_Subscripting = 0x2,
  279. /// Enable migration to modern ObjC readonly property.
  280. ObjCMT_ReadonlyProperty = 0x4,
  281. /// Enable migration to modern ObjC readwrite property.
  282. ObjCMT_ReadwriteProperty = 0x8,
  283. /// Enable migration to modern ObjC property.
  284. ObjCMT_Property = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty),
  285. /// Enable annotation of ObjCMethods of all kinds.
  286. ObjCMT_Annotation = 0x10,
  287. /// Enable migration of ObjC methods to 'instancetype'.
  288. ObjCMT_Instancetype = 0x20,
  289. /// Enable migration to NS_ENUM/NS_OPTIONS macros.
  290. ObjCMT_NsMacros = 0x40,
  291. /// Enable migration to add conforming protocols.
  292. ObjCMT_ProtocolConformance = 0x80,
  293. /// prefer 'atomic' property over 'nonatomic'.
  294. ObjCMT_AtomicProperty = 0x100,
  295. /// annotate property with NS_RETURNS_INNER_POINTER
  296. ObjCMT_ReturnsInnerPointerProperty = 0x200,
  297. /// use NS_NONATOMIC_IOSONLY for property 'atomic' attribute
  298. ObjCMT_NsAtomicIOSOnlyProperty = 0x400,
  299. /// Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
  300. ObjCMT_DesignatedInitializer = 0x800,
  301. /// Enable converting setter/getter expressions to property-dot syntx.
  302. ObjCMT_PropertyDotSyntax = 0x1000,
  303. ObjCMT_MigrateDecls = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty |
  304. ObjCMT_Annotation | ObjCMT_Instancetype |
  305. ObjCMT_NsMacros | ObjCMT_ProtocolConformance |
  306. ObjCMT_NsAtomicIOSOnlyProperty |
  307. ObjCMT_DesignatedInitializer),
  308. ObjCMT_MigrateAll = (ObjCMT_Literals | ObjCMT_Subscripting |
  309. ObjCMT_MigrateDecls | ObjCMT_PropertyDotSyntax)
  310. };
  311. unsigned ObjCMTAction = ObjCMT_None;
  312. std::string ObjCMTAllowListPath;
  313. std::string MTMigrateDir;
  314. std::string ARCMTMigrateReportOut;
  315. /// The input kind, either specified via -x argument or deduced from the input
  316. /// file name.
  317. InputKind DashX;
  318. /// The input files and their types.
  319. SmallVector<FrontendInputFile, 0> Inputs;
  320. /// When the input is a module map, the original module map file from which
  321. /// that map was inferred, if any (for umbrella modules).
  322. std::string OriginalModuleMap;
  323. /// The output file, if any.
  324. std::string OutputFile;
  325. /// If given, the new suffix for fix-it rewritten files.
  326. std::string FixItSuffix;
  327. /// If given, filter dumped AST Decl nodes by this substring.
  328. std::string ASTDumpFilter;
  329. /// If given, enable code completion at the provided location.
  330. ParsedSourceLocation CodeCompletionAt;
  331. /// The frontend action to perform.
  332. frontend::ActionKind ProgramAction = frontend::ParseSyntaxOnly;
  333. /// The name of the action to run when using a plugin action.
  334. std::string ActionName;
  335. // Currently this is only used as part of the `-extract-api` action.
  336. /// The name of the product the input files belong too.
  337. std::string ProductName;
  338. // Currently this is only used as part of the `-extract-api` action.
  339. /// The file providing a list of APIs to ignore when extracting documentation
  340. std::string ExtractAPIIgnoresFile;
  341. /// Args to pass to the plugins
  342. std::map<std::string, std::vector<std::string>> PluginArgs;
  343. /// The list of plugin actions to run in addition to the normal action.
  344. std::vector<std::string> AddPluginActions;
  345. /// The list of plugins to load.
  346. std::vector<std::string> Plugins;
  347. /// The list of module file extensions.
  348. std::vector<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
  349. /// The list of module map files to load before processing the input.
  350. std::vector<std::string> ModuleMapFiles;
  351. /// The list of additional prebuilt module files to load before
  352. /// processing the input.
  353. std::vector<std::string> ModuleFiles;
  354. /// The list of files to embed into the compiled module file.
  355. std::vector<std::string> ModulesEmbedFiles;
  356. /// The list of AST files to merge.
  357. std::vector<std::string> ASTMergeFiles;
  358. /// A list of arguments to forward to LLVM's option processing; this
  359. /// should only be used for debugging and experimental features.
  360. std::vector<std::string> LLVMArgs;
  361. /// File name of the file that will provide record layouts
  362. /// (in the format produced by -fdump-record-layouts).
  363. std::string OverrideRecordLayoutsFile;
  364. /// Auxiliary triple for CUDA/HIP compilation.
  365. std::string AuxTriple;
  366. /// Auxiliary target CPU for CUDA/HIP compilation.
  367. std::optional<std::string> AuxTargetCPU;
  368. /// Auxiliary target features for CUDA/HIP compilation.
  369. std::optional<std::vector<std::string>> AuxTargetFeatures;
  370. /// Filename to write statistics to.
  371. std::string StatsFile;
  372. /// Minimum time granularity (in microseconds) traced by time profiler.
  373. unsigned TimeTraceGranularity;
  374. /// Path which stores the output files for -ftime-trace
  375. std::string TimeTracePath;
  376. public:
  377. FrontendOptions()
  378. : DisableFree(false), RelocatablePCH(false), ShowHelp(false),
  379. ShowStats(false), TimeTrace(false), ShowVersion(false),
  380. FixWhatYouCan(false), FixOnlyWarnings(false), FixAndRecompile(false),
  381. FixToTemporaries(false), ARCMTMigrateEmitARCErrors(false),
  382. SkipFunctionBodies(false), UseGlobalModuleIndex(true),
  383. GenerateGlobalModuleIndex(true), ASTDumpDecls(false),
  384. ASTDumpLookups(false), BuildingImplicitModule(false),
  385. BuildingImplicitModuleUsesLock(true), ModulesEmbedAllFiles(false),
  386. IncludeTimestamps(true), UseTemporary(true),
  387. AllowPCMWithCompilerErrors(false), ModulesShareFileManager(true),
  388. TimeTraceGranularity(500) {}
  389. /// getInputKindForExtension - Return the appropriate input kind for a file
  390. /// extension. For example, "c" would return Language::C.
  391. ///
  392. /// \return The input kind for the extension, or Language::Unknown if the
  393. /// extension is not recognized.
  394. static InputKind getInputKindForExtension(StringRef Extension);
  395. };
  396. } // namespace clang
  397. #endif // LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
  398. #ifdef __GNUC__
  399. #pragma GCC diagnostic pop
  400. #endif