Home | History | Annotate | Download | only in Driver
      1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- 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_DRIVER_DRIVER_H
     11 #define LLVM_CLANG_DRIVER_DRIVER_H
     12 
     13 #include "clang/Basic/Diagnostic.h"
     14 #include "clang/Basic/LLVM.h"
     15 #include "clang/Driver/Phases.h"
     16 #include "clang/Driver/Types.h"
     17 #include "clang/Driver/Util.h"
     18 #include "llvm/ADT/StringMap.h"
     19 #include "llvm/ADT/StringRef.h"
     20 #include "llvm/ADT/Triple.h"
     21 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo
     22 #include <memory>
     23                               // lands.
     24 #include <list>
     25 #include <set>
     26 #include <string>
     27 
     28 namespace llvm {
     29 namespace opt {
     30   class Arg;
     31   class ArgList;
     32   class DerivedArgList;
     33   class InputArgList;
     34   class OptTable;
     35 }
     36 }
     37 
     38 namespace clang {
     39 
     40 namespace vfs {
     41 class FileSystem;
     42 }
     43 
     44 namespace driver {
     45 
     46   class Action;
     47   class Command;
     48   class Compilation;
     49   class InputInfo;
     50   class JobList;
     51   class JobAction;
     52   class SanitizerArgs;
     53   class ToolChain;
     54 
     55 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
     56 enum LTOKind {
     57   LTOK_None,
     58   LTOK_Full,
     59   LTOK_Thin,
     60   LTOK_Unknown
     61 };
     62 
     63 /// Driver - Encapsulate logic for constructing compilation processes
     64 /// from a set of gcc-driver-like command line arguments.
     65 class Driver {
     66   llvm::opt::OptTable *Opts;
     67 
     68   DiagnosticsEngine &Diags;
     69 
     70   IntrusiveRefCntPtr<vfs::FileSystem> VFS;
     71 
     72   enum DriverMode {
     73     GCCMode,
     74     GXXMode,
     75     CPPMode,
     76     CLMode
     77   } Mode;
     78 
     79   enum SaveTempsMode {
     80     SaveTempsNone,
     81     SaveTempsCwd,
     82     SaveTempsObj
     83   } SaveTemps;
     84 
     85   /// LTO mode selected via -f(no-)?lto(=.*)? options.
     86   LTOKind LTOMode;
     87 
     88 public:
     89   // Diag - Forwarding function for diagnostics.
     90   DiagnosticBuilder Diag(unsigned DiagID) const {
     91     return Diags.Report(DiagID);
     92   }
     93 
     94   // FIXME: Privatize once interface is stable.
     95 public:
     96   /// The name the driver was invoked as.
     97   std::string Name;
     98 
     99   /// The path the driver executable was in, as invoked from the
    100   /// command line.
    101   std::string Dir;
    102 
    103   /// The original path to the clang executable.
    104   std::string ClangExecutable;
    105 
    106   /// The path to the installed clang directory, if any.
    107   std::string InstalledDir;
    108 
    109   /// The path to the compiler resource directory.
    110   std::string ResourceDir;
    111 
    112   /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
    113   /// functionality.
    114   /// FIXME: This type of customization should be removed in favor of the
    115   /// universal driver when it is ready.
    116   typedef SmallVector<std::string, 4> prefix_list;
    117   prefix_list PrefixDirs;
    118 
    119   /// sysroot, if present
    120   std::string SysRoot;
    121 
    122   /// Dynamic loader prefix, if present
    123   std::string DyldPrefix;
    124 
    125   /// If the standard library is used
    126   bool UseStdLib;
    127 
    128   /// Default target triple.
    129   std::string DefaultTargetTriple;
    130 
    131   /// Driver title to use with help.
    132   std::string DriverTitle;
    133 
    134   /// Information about the host which can be overridden by the user.
    135   std::string HostBits, HostMachine, HostSystem, HostRelease;
    136 
    137   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
    138   const char *CCPrintOptionsFilename;
    139 
    140   /// The file to log CC_PRINT_HEADERS output to, if enabled.
    141   const char *CCPrintHeadersFilename;
    142 
    143   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
    144   const char *CCLogDiagnosticsFilename;
    145 
    146   /// A list of inputs and their types for the given arguments.
    147   typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
    148       InputList;
    149 
    150   /// Whether the driver should follow g++ like behavior.
    151   bool CCCIsCXX() const { return Mode == GXXMode; }
    152 
    153   /// Whether the driver is just the preprocessor.
    154   bool CCCIsCPP() const { return Mode == CPPMode; }
    155 
    156   /// Whether the driver should follow cl.exe like behavior.
    157   bool IsCLMode() const { return Mode == CLMode; }
    158 
    159   /// Only print tool bindings, don't build any jobs.
    160   unsigned CCCPrintBindings : 1;
    161 
    162   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
    163   /// CCPrintOptionsFilename or to stderr.
    164   unsigned CCPrintOptions : 1;
    165 
    166   /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
    167   /// information to CCPrintHeadersFilename or to stderr.
    168   unsigned CCPrintHeaders : 1;
    169 
    170   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
    171   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
    172   /// format.
    173   unsigned CCLogDiagnostics : 1;
    174 
    175   /// Whether the driver is generating diagnostics for debugging purposes.
    176   unsigned CCGenDiagnostics : 1;
    177 
    178 private:
    179   /// Name to use when invoking gcc/g++.
    180   std::string CCCGenericGCCName;
    181 
    182   /// Whether to check that input files exist when constructing compilation
    183   /// jobs.
    184   unsigned CheckInputsExist : 1;
    185 
    186 public:
    187   /// Use lazy precompiled headers for PCH support.
    188   unsigned CCCUsePCH : 1;
    189 
    190 private:
    191   /// Certain options suppress the 'no input files' warning.
    192   bool SuppressMissingInputWarning : 1;
    193 
    194   std::list<std::string> TempFiles;
    195   std::list<std::string> ResultFiles;
    196 
    197   /// \brief Cache of all the ToolChains in use by the driver.
    198   ///
    199   /// This maps from the string representation of a triple to a ToolChain
    200   /// created targeting that triple. The driver owns all the ToolChain objects
    201   /// stored in it, and will clean them up when torn down.
    202   mutable llvm::StringMap<ToolChain *> ToolChains;
    203 
    204 private:
    205   /// TranslateInputArgs - Create a new derived argument list from the input
    206   /// arguments, after applying the standard argument translations.
    207   llvm::opt::DerivedArgList *
    208   TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
    209 
    210   // getFinalPhase - Determine which compilation mode we are in and record
    211   // which option we used to determine the final phase.
    212   phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
    213                            llvm::opt::Arg **FinalPhaseArg = nullptr) const;
    214 
    215   // Before executing jobs, sets up response files for commands that need them.
    216   void setUpResponseFiles(Compilation &C, Command &Cmd);
    217 
    218   void generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
    219                                  SmallVectorImpl<std::string> &Names) const;
    220 
    221 public:
    222   Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
    223          DiagnosticsEngine &Diags,
    224          IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
    225   ~Driver();
    226 
    227   /// @name Accessors
    228   /// @{
    229 
    230   /// Name to use when invoking gcc/g++.
    231   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
    232 
    233   const llvm::opt::OptTable &getOpts() const { return *Opts; }
    234 
    235   const DiagnosticsEngine &getDiags() const { return Diags; }
    236 
    237   vfs::FileSystem &getVFS() const { return *VFS; }
    238 
    239   bool getCheckInputsExist() const { return CheckInputsExist; }
    240 
    241   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
    242 
    243   const std::string &getTitle() { return DriverTitle; }
    244   void setTitle(std::string Value) { DriverTitle = Value; }
    245 
    246   /// \brief Get the path to the main clang executable.
    247   const char *getClangProgramPath() const {
    248     return ClangExecutable.c_str();
    249   }
    250 
    251   /// \brief Get the path to where the clang executable was installed.
    252   const char *getInstalledDir() const {
    253     if (!InstalledDir.empty())
    254       return InstalledDir.c_str();
    255     return Dir.c_str();
    256   }
    257   void setInstalledDir(StringRef Value) {
    258     InstalledDir = Value;
    259   }
    260 
    261   bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
    262   bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
    263 
    264   /// @}
    265   /// @name Primary Functionality
    266   /// @{
    267 
    268   /// BuildCompilation - Construct a compilation object for a command
    269   /// line argument vector.
    270   ///
    271   /// \return A compilation, or 0 if none was built for the given
    272   /// argument vector. A null return value does not necessarily
    273   /// indicate an error condition, the diagnostics should be queried
    274   /// to determine if an error occurred.
    275   Compilation *BuildCompilation(ArrayRef<const char *> Args);
    276 
    277   /// @name Driver Steps
    278   /// @{
    279 
    280   /// ParseDriverMode - Look for and handle the driver mode option in Args.
    281   void ParseDriverMode(ArrayRef<const char *> Args);
    282 
    283   /// ParseArgStrings - Parse the given list of strings into an
    284   /// ArgList.
    285   llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args);
    286 
    287   /// BuildInputs - Construct the list of inputs and their types from
    288   /// the given arguments.
    289   ///
    290   /// \param TC - The default host tool chain.
    291   /// \param Args - The input arguments.
    292   /// \param Inputs - The list to store the resulting compilation
    293   /// inputs onto.
    294   void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
    295                    InputList &Inputs) const;
    296 
    297   /// BuildActions - Construct the list of actions to perform for the
    298   /// given arguments, which are only done for a single architecture.
    299   ///
    300   /// \param C - The compilation that is being built.
    301   /// \param TC - The default host tool chain.
    302   /// \param Args - The input arguments.
    303   /// \param Actions - The list to store the resulting actions onto.
    304   void BuildActions(Compilation &C, const ToolChain &TC,
    305                     llvm::opt::DerivedArgList &Args, const InputList &Inputs,
    306                     ActionList &Actions) const;
    307 
    308   /// BuildUniversalActions - Construct the list of actions to perform
    309   /// for the given arguments, which may require a universal build.
    310   ///
    311   /// \param C - The compilation that is being built.
    312   /// \param TC - The default host tool chain.
    313   void BuildUniversalActions(Compilation &C, const ToolChain &TC,
    314                              const InputList &BAInputs) const;
    315 
    316   /// BuildJobs - Bind actions to concrete tools and translate
    317   /// arguments to form the list of jobs to run.
    318   ///
    319   /// \param C - The compilation that is being built.
    320   void BuildJobs(Compilation &C) const;
    321 
    322   /// ExecuteCompilation - Execute the compilation according to the command line
    323   /// arguments and return an appropriate exit code.
    324   ///
    325   /// This routine handles additional processing that must be done in addition
    326   /// to just running the subprocesses, for example reporting errors, setting
    327   /// up response files, removing temporary files, etc.
    328   int ExecuteCompilation(Compilation &C,
    329      SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
    330 
    331   /// generateCompilationDiagnostics - Generate diagnostics information
    332   /// including preprocessed source file(s).
    333   ///
    334   void generateCompilationDiagnostics(Compilation &C,
    335                                       const Command &FailingCommand);
    336 
    337   /// @}
    338   /// @name Helper Methods
    339   /// @{
    340 
    341   /// PrintActions - Print the list of actions.
    342   void PrintActions(const Compilation &C) const;
    343 
    344   /// PrintHelp - Print the help text.
    345   ///
    346   /// \param ShowHidden - Show hidden options.
    347   void PrintHelp(bool ShowHidden) const;
    348 
    349   /// PrintVersion - Print the driver version.
    350   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
    351 
    352   /// GetFilePath - Lookup \p Name in the list of file search paths.
    353   ///
    354   /// \param TC - The tool chain for additional information on
    355   /// directories to search.
    356   //
    357   // FIXME: This should be in CompilationInfo.
    358   std::string GetFilePath(const char *Name, const ToolChain &TC) const;
    359 
    360   /// GetProgramPath - Lookup \p Name in the list of program search paths.
    361   ///
    362   /// \param TC - The provided tool chain for additional information on
    363   /// directories to search.
    364   //
    365   // FIXME: This should be in CompilationInfo.
    366   std::string GetProgramPath(const char *Name, const ToolChain &TC) const;
    367 
    368   /// HandleImmediateArgs - Handle any arguments which should be
    369   /// treated before building actions or binding tools.
    370   ///
    371   /// \return Whether any compilation should be built for this
    372   /// invocation.
    373   bool HandleImmediateArgs(const Compilation &C);
    374 
    375   /// ConstructAction - Construct the appropriate action to do for
    376   /// \p Phase on the \p Input, taking in to account arguments
    377   /// like -fsyntax-only or --analyze.
    378   std::unique_ptr<Action>
    379   ConstructPhaseAction(const ToolChain &TC, const llvm::opt::ArgList &Args,
    380                        phases::ID Phase, std::unique_ptr<Action> Input) const;
    381 
    382   /// BuildJobsForAction - Construct the jobs to perform for the
    383   /// action \p A.
    384   void BuildJobsForAction(Compilation &C,
    385                           const Action *A,
    386                           const ToolChain *TC,
    387                           const char *BoundArch,
    388                           bool AtTopLevel,
    389                           bool MultipleArchs,
    390                           const char *LinkingOutput,
    391                           InputInfo &Result) const;
    392 
    393   /// Returns the default name for linked images (e.g., "a.out").
    394   const char *getDefaultImageName() const;
    395 
    396   /// GetNamedOutputPath - Return the name to use for the output of
    397   /// the action \p JA. The result is appended to the compilation's
    398   /// list of temporary or result files, as appropriate.
    399   ///
    400   /// \param C - The compilation.
    401   /// \param JA - The action of interest.
    402   /// \param BaseInput - The original input file that this action was
    403   /// triggered by.
    404   /// \param BoundArch - The bound architecture.
    405   /// \param AtTopLevel - Whether this is a "top-level" action.
    406   /// \param MultipleArchs - Whether multiple -arch options were supplied.
    407   const char *GetNamedOutputPath(Compilation &C,
    408                                  const JobAction &JA,
    409                                  const char *BaseInput,
    410                                  const char *BoundArch,
    411                                  bool AtTopLevel,
    412                                  bool MultipleArchs) const;
    413 
    414   /// GetTemporaryPath - Return the pathname of a temporary file to use
    415   /// as part of compilation; the file will have the given prefix and suffix.
    416   ///
    417   /// GCC goes to extra lengths here to be a bit more robust.
    418   std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
    419 
    420   /// ShouldUseClangCompiler - Should the clang compiler be used to
    421   /// handle this action.
    422   bool ShouldUseClangCompiler(const JobAction &JA) const;
    423 
    424   /// Returns true if we are performing any kind of LTO.
    425   bool isUsingLTO() const { return LTOMode != LTOK_None; }
    426 
    427   /// Get the specific kind of LTO being performed.
    428   LTOKind getLTOMode() const { return LTOMode; }
    429 
    430 private:
    431   /// Parse the \p Args list for LTO options and record the type of LTO
    432   /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
    433   void setLTOMode(const llvm::opt::ArgList &Args);
    434 
    435   /// \brief Retrieves a ToolChain for a particular \p Target triple.
    436   ///
    437   /// Will cache ToolChains for the life of the driver object, and create them
    438   /// on-demand.
    439   const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
    440                                 const llvm::Triple &Target) const;
    441 
    442   /// @}
    443 
    444   /// \brief Get bitmasks for which option flags to include and exclude based on
    445   /// the driver mode.
    446   std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
    447 
    448 public:
    449   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
    450   /// return the grouped values as integers. Numbers which are not
    451   /// provided are set to 0.
    452   ///
    453   /// \return True if the entire string was parsed (9.2), or all
    454   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
    455   /// groups were parsed but extra characters remain at the end.
    456   static bool GetReleaseVersion(const char *Str, unsigned &Major,
    457                                 unsigned &Minor, unsigned &Micro,
    458                                 bool &HadExtra);
    459 };
    460 
    461 /// \return True if the last defined optimization level is -Ofast.
    462 /// And False otherwise.
    463 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
    464 
    465 } // end namespace driver
    466 } // end namespace clang
    467 
    468 #endif
    469