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