Home | History | Annotate | Download | only in Frontend
      1 //===--- FrontendOptions.h --------------------------------------*- 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 #ifndef LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
     11 #define LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
     12 
     13 #include "clang/Frontend/CommandLineSourceLoc.h"
     14 #include "clang/Serialization/ModuleFileExtension.h"
     15 #include "clang/Sema/CodeCompleteOptions.h"
     16 #include "llvm/ADT/StringRef.h"
     17 #include <string>
     18 #include <vector>
     19 #include <unordered_map>
     20 
     21 namespace llvm {
     22 class MemoryBuffer;
     23 }
     24 
     25 namespace clang {
     26 class FileEntry;
     27 
     28 namespace frontend {
     29   enum ActionKind {
     30     ASTDeclList,            ///< Parse ASTs and list Decl nodes.
     31     ASTDump,                ///< Parse ASTs and dump them.
     32     ASTPrint,               ///< Parse ASTs and print them.
     33     ASTView,                ///< Parse ASTs and view them in Graphviz.
     34     DumpRawTokens,          ///< Dump out raw tokens.
     35     DumpTokens,             ///< Dump out preprocessed tokens.
     36     EmitAssembly,           ///< Emit a .s file.
     37     EmitBC,                 ///< Emit a .bc file.
     38     EmitHTML,               ///< Translate input source into HTML.
     39     EmitLLVM,               ///< Emit a .ll file.
     40     EmitLLVMOnly,           ///< Generate LLVM IR, but do not emit anything.
     41     EmitCodeGenOnly,        ///< Generate machine code, but don't emit anything.
     42     EmitObj,                ///< Emit a .o file.
     43     FixIt,                  ///< Parse and apply any fixits to the source.
     44     GenerateModule,         ///< Generate pre-compiled module from a module map.
     45     GenerateModuleInterface,///< Generate pre-compiled module from a C++ module
     46                             ///< interface file.
     47     GeneratePCH,            ///< Generate pre-compiled header.
     48     GeneratePTH,            ///< Generate pre-tokenized header.
     49     InitOnly,               ///< Only execute frontend initialization.
     50     ModuleFileInfo,         ///< Dump information about a module file.
     51     VerifyPCH,              ///< Load and verify that a PCH file is usable.
     52     ParseSyntaxOnly,        ///< Parse and perform semantic analysis.
     53     PluginAction,           ///< Run a plugin action, \see ActionName.
     54     PrintDeclContext,       ///< Print DeclContext and their Decls.
     55     PrintPreamble,          ///< Print the "preamble" of the input file
     56     PrintPreprocessedInput, ///< -E mode.
     57     RewriteMacros,          ///< Expand macros but not \#includes.
     58     RewriteObjC,            ///< ObjC->C Rewriter.
     59     RewriteTest,            ///< Rewriter playground
     60     RunAnalysis,            ///< Run one or more source code analyses.
     61     MigrateSource,          ///< Run migrator.
     62     RunPreprocessorOnly     ///< Just lex, no output.
     63   };
     64 }
     65 
     66 /// The kind of a file that we've been handed as an input.
     67 class InputKind {
     68 private:
     69   unsigned Lang : 4;
     70   unsigned Fmt : 3;
     71   unsigned Preprocessed : 1;
     72 
     73 public:
     74   /// The language for the input, used to select and validate the language
     75   /// standard and possible actions.
     76   enum Language {
     77     Unknown,
     78 
     79     /// Assembly: we accept this only so that we can preprocess it.
     80     Asm,
     81 
     82     /// LLVM IR: we accept this so that we can run the optimizer on it,
     83     /// and compile it to assembly or object code.
     84     LLVM_IR,
     85 
     86     ///@{ Languages that the frontend can parse and compile.
     87     C,
     88     CXX,
     89     ObjC,
     90     ObjCXX,
     91     OpenCL,
     92     CUDA,
     93     RenderScript,
     94     ///@}
     95   };
     96 
     97   /// The input file format.
     98   enum Format {
     99     Source,
    100     ModuleMap,
    101     Precompiled
    102   };
    103 
    104   constexpr InputKind(Language L = Unknown, Format F = Source,
    105                       bool PP = false)
    106       : Lang(L), Fmt(F), Preprocessed(PP) {}
    107 
    108   Language getLanguage() const { return static_cast<Language>(Lang); }
    109   Format getFormat() const { return static_cast<Format>(Fmt); }
    110   bool isPreprocessed() const { return Preprocessed; }
    111 
    112   /// Is the input kind fully-unknown?
    113   bool isUnknown() const { return Lang == Unknown && Fmt == Source; }
    114 
    115   /// Is the language of the input some dialect of Objective-C?
    116   bool isObjectiveC() const { return Lang == ObjC || Lang == ObjCXX; }
    117 
    118   InputKind getPreprocessed() const {
    119     return InputKind(getLanguage(), getFormat(), true);
    120   }
    121   InputKind withFormat(Format F) const {
    122     return InputKind(getLanguage(), F, isPreprocessed());
    123   }
    124 };
    125 
    126 /// \brief An input file for the front end.
    127 class FrontendInputFile {
    128   /// \brief The file name, or "-" to read from standard input.
    129   std::string File;
    130 
    131   llvm::MemoryBuffer *Buffer;
    132 
    133   /// \brief The kind of input, e.g., C source, AST file, LLVM IR.
    134   InputKind Kind;
    135 
    136   /// \brief Whether we're dealing with a 'system' input (vs. a 'user' input).
    137   bool IsSystem;
    138 
    139 public:
    140   FrontendInputFile() : Buffer(nullptr), Kind(), IsSystem(false) { }
    141   FrontendInputFile(StringRef File, InputKind Kind, bool IsSystem = false)
    142     : File(File.str()), Buffer(nullptr), Kind(Kind), IsSystem(IsSystem) { }
    143   FrontendInputFile(llvm::MemoryBuffer *buffer, InputKind Kind,
    144                     bool IsSystem = false)
    145     : Buffer(buffer), Kind(Kind), IsSystem(IsSystem) { }
    146 
    147   InputKind getKind() const { return Kind; }
    148   bool isSystem() const { return IsSystem; }
    149 
    150   bool isEmpty() const { return File.empty() && Buffer == nullptr; }
    151   bool isFile() const { return !isBuffer(); }
    152   bool isBuffer() const { return Buffer != nullptr; }
    153   bool isPreprocessed() const { return Kind.isPreprocessed(); }
    154 
    155   StringRef getFile() const {
    156     assert(isFile());
    157     return File;
    158   }
    159   llvm::MemoryBuffer *getBuffer() const {
    160     assert(isBuffer());
    161     return Buffer;
    162   }
    163 };
    164 
    165 /// FrontendOptions - Options for controlling the behavior of the frontend.
    166 class FrontendOptions {
    167 public:
    168   unsigned DisableFree : 1;                ///< Disable memory freeing on exit.
    169   unsigned RelocatablePCH : 1;             ///< When generating PCH files,
    170                                            /// instruct the AST writer to create
    171                                            /// relocatable PCH files.
    172   unsigned ShowHelp : 1;                   ///< Show the -help text.
    173   unsigned ShowStats : 1;                  ///< Show frontend performance
    174                                            /// metrics and statistics.
    175   unsigned ShowTimers : 1;                 ///< Show timers for individual
    176                                            /// actions.
    177   unsigned ShowVersion : 1;                ///< Show the -version text.
    178   unsigned FixWhatYouCan : 1;              ///< Apply fixes even if there are
    179                                            /// unfixable errors.
    180   unsigned FixOnlyWarnings : 1;            ///< Apply fixes only for warnings.
    181   unsigned FixAndRecompile : 1;            ///< Apply fixes and recompile.
    182   unsigned FixToTemporaries : 1;           ///< Apply fixes to temporary files.
    183   unsigned ARCMTMigrateEmitARCErrors : 1;  /// Emit ARC errors even if the
    184                                            /// migrator can fix them
    185   unsigned SkipFunctionBodies : 1;         ///< Skip over function bodies to
    186                                            /// speed up parsing in cases you do
    187                                            /// not need them (e.g. with code
    188                                            /// completion).
    189   unsigned UseGlobalModuleIndex : 1;       ///< Whether we can use the
    190                                            ///< global module index if available.
    191   unsigned GenerateGlobalModuleIndex : 1;  ///< Whether we can generate the
    192                                            ///< global module index if needed.
    193   unsigned ASTDumpDecls : 1;               ///< Whether we include declaration
    194                                            ///< dumps in AST dumps.
    195   unsigned ASTDumpAll : 1;                 ///< Whether we deserialize all decls
    196                                            ///< when forming AST dumps.
    197   unsigned ASTDumpLookups : 1;             ///< Whether we include lookup table
    198                                            ///< dumps in AST dumps.
    199   unsigned BuildingImplicitModule : 1;     ///< Whether we are performing an
    200                                            ///< implicit module build.
    201   unsigned ModulesEmbedAllFiles : 1;       ///< Whether we should embed all used
    202                                            ///< files into the PCM file.
    203   unsigned IncludeTimestamps : 1;          ///< Whether timestamps should be
    204                                            ///< written to the produced PCH file.
    205 
    206   CodeCompleteOptions CodeCompleteOpts;
    207 
    208   enum {
    209     ARCMT_None,
    210     ARCMT_Check,
    211     ARCMT_Modify,
    212     ARCMT_Migrate
    213   } ARCMTAction;
    214 
    215   enum {
    216     ObjCMT_None = 0,
    217     /// \brief Enable migration to modern ObjC literals.
    218     ObjCMT_Literals = 0x1,
    219     /// \brief Enable migration to modern ObjC subscripting.
    220     ObjCMT_Subscripting = 0x2,
    221     /// \brief Enable migration to modern ObjC readonly property.
    222     ObjCMT_ReadonlyProperty = 0x4,
    223     /// \brief Enable migration to modern ObjC readwrite property.
    224     ObjCMT_ReadwriteProperty = 0x8,
    225     /// \brief Enable migration to modern ObjC property.
    226     ObjCMT_Property = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty),
    227     /// \brief Enable annotation of ObjCMethods of all kinds.
    228     ObjCMT_Annotation = 0x10,
    229     /// \brief Enable migration of ObjC methods to 'instancetype'.
    230     ObjCMT_Instancetype = 0x20,
    231     /// \brief Enable migration to NS_ENUM/NS_OPTIONS macros.
    232     ObjCMT_NsMacros = 0x40,
    233     /// \brief Enable migration to add conforming protocols.
    234     ObjCMT_ProtocolConformance = 0x80,
    235     /// \brief prefer 'atomic' property over 'nonatomic'.
    236     ObjCMT_AtomicProperty = 0x100,
    237     /// \brief annotate property with NS_RETURNS_INNER_POINTER
    238     ObjCMT_ReturnsInnerPointerProperty = 0x200,
    239     /// \brief use NS_NONATOMIC_IOSONLY for property 'atomic' attribute
    240     ObjCMT_NsAtomicIOSOnlyProperty = 0x400,
    241     /// \brief Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
    242     ObjCMT_DesignatedInitializer = 0x800,
    243     /// \brief Enable converting setter/getter expressions to property-dot syntx.
    244     ObjCMT_PropertyDotSyntax = 0x1000,
    245     ObjCMT_MigrateDecls = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty |
    246                            ObjCMT_Annotation | ObjCMT_Instancetype |
    247                            ObjCMT_NsMacros | ObjCMT_ProtocolConformance |
    248                            ObjCMT_NsAtomicIOSOnlyProperty |
    249                            ObjCMT_DesignatedInitializer),
    250     ObjCMT_MigrateAll = (ObjCMT_Literals | ObjCMT_Subscripting |
    251                          ObjCMT_MigrateDecls | ObjCMT_PropertyDotSyntax)
    252   };
    253   unsigned ObjCMTAction;
    254   std::string ObjCMTWhiteListPath;
    255 
    256   std::string MTMigrateDir;
    257   std::string ARCMTMigrateReportOut;
    258 
    259   /// The input files and their types.
    260   std::vector<FrontendInputFile> Inputs;
    261 
    262   /// When the input is a module map, the original module map file from which
    263   /// that map was inferred, if any (for umbrella modules).
    264   std::string OriginalModuleMap;
    265 
    266   /// The output file, if any.
    267   std::string OutputFile;
    268 
    269   /// If given, the new suffix for fix-it rewritten files.
    270   std::string FixItSuffix;
    271 
    272   /// If given, filter dumped AST Decl nodes by this substring.
    273   std::string ASTDumpFilter;
    274 
    275   /// If given, enable code completion at the provided location.
    276   ParsedSourceLocation CodeCompletionAt;
    277 
    278   /// The frontend action to perform.
    279   frontend::ActionKind ProgramAction;
    280 
    281   /// The name of the action to run when using a plugin action.
    282   std::string ActionName;
    283 
    284   /// Args to pass to the plugins
    285   std::unordered_map<std::string,std::vector<std::string>> PluginArgs;
    286 
    287   /// The list of plugin actions to run in addition to the normal action.
    288   std::vector<std::string> AddPluginActions;
    289 
    290   /// The list of plugins to load.
    291   std::vector<std::string> Plugins;
    292 
    293   /// The list of module file extensions.
    294   std::vector<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
    295 
    296   /// \brief The list of module map files to load before processing the input.
    297   std::vector<std::string> ModuleMapFiles;
    298 
    299   /// \brief The list of additional prebuilt module files to load before
    300   /// processing the input.
    301   std::vector<std::string> ModuleFiles;
    302 
    303   /// \brief The list of files to embed into the compiled module file.
    304   std::vector<std::string> ModulesEmbedFiles;
    305 
    306   /// \brief The list of AST files to merge.
    307   std::vector<std::string> ASTMergeFiles;
    308 
    309   /// \brief A list of arguments to forward to LLVM's option processing; this
    310   /// should only be used for debugging and experimental features.
    311   std::vector<std::string> LLVMArgs;
    312 
    313   /// \brief File name of the file that will provide record layouts
    314   /// (in the format produced by -fdump-record-layouts).
    315   std::string OverrideRecordLayoutsFile;
    316 
    317   /// \brief Auxiliary triple for CUDA compilation.
    318   std::string AuxTriple;
    319 
    320   /// \brief If non-empty, search the pch input file as if it was a header
    321   /// included by this file.
    322   std::string FindPchSource;
    323 
    324   /// Filename to write statistics to.
    325   std::string StatsFile;
    326 
    327 public:
    328   FrontendOptions() :
    329     DisableFree(false), RelocatablePCH(false), ShowHelp(false),
    330     ShowStats(false), ShowTimers(false), ShowVersion(false),
    331     FixWhatYouCan(false), FixOnlyWarnings(false), FixAndRecompile(false),
    332     FixToTemporaries(false), ARCMTMigrateEmitARCErrors(false),
    333     SkipFunctionBodies(false), UseGlobalModuleIndex(true),
    334     GenerateGlobalModuleIndex(true), ASTDumpDecls(false), ASTDumpLookups(false),
    335     BuildingImplicitModule(false), ModulesEmbedAllFiles(false),
    336     IncludeTimestamps(true), ARCMTAction(ARCMT_None),
    337     ObjCMTAction(ObjCMT_None), ProgramAction(frontend::ParseSyntaxOnly)
    338   {}
    339 
    340   /// getInputKindForExtension - Return the appropriate input kind for a file
    341   /// extension. For example, "c" would return InputKind::C.
    342   ///
    343   /// \return The input kind for the extension, or InputKind::Unknown if the
    344   /// extension is not recognized.
    345   static InputKind getInputKindForExtension(StringRef Extension);
    346 };
    347 
    348 }  // end namespace clang
    349 
    350 #endif
    351