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 CLANG_DRIVER_DRIVER_H_
     11 #define CLANG_DRIVER_DRIVER_H_
     12 
     13 #include "clang/Basic/Diagnostic.h"
     14 
     15 #include "clang/Driver/Phases.h"
     16 #include "clang/Driver/Util.h"
     17 
     18 #include "llvm/ADT/StringRef.h"
     19 #include "llvm/ADT/Triple.h"
     20 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo
     21                               // lands.
     22 #include <list>
     23 #include <set>
     24 #include <string>
     25 
     26 namespace llvm {
     27   class raw_ostream;
     28   template<typename T> class ArrayRef;
     29 }
     30 namespace clang {
     31 namespace driver {
     32   class Action;
     33   class ArgList;
     34   class Compilation;
     35   class DerivedArgList;
     36   class HostInfo;
     37   class InputArgList;
     38   class InputInfo;
     39   class JobAction;
     40   class OptTable;
     41   class ToolChain;
     42 
     43 /// Driver - Encapsulate logic for constructing compilation processes
     44 /// from a set of gcc-driver-like command line arguments.
     45 class Driver {
     46   OptTable *Opts;
     47 
     48   Diagnostic &Diags;
     49 
     50 public:
     51   // Diag - Forwarding function for diagnostics.
     52   DiagnosticBuilder Diag(unsigned DiagID) const {
     53     return Diags.Report(DiagID);
     54   }
     55 
     56   // FIXME: Privatize once interface is stable.
     57 public:
     58   /// The name the driver was invoked as.
     59   std::string Name;
     60 
     61   /// The path the driver executable was in, as invoked from the
     62   /// command line.
     63   std::string Dir;
     64 
     65   /// The original path to the clang executable.
     66   std::string ClangExecutable;
     67 
     68   /// The path to the installed clang directory, if any.
     69   std::string InstalledDir;
     70 
     71   /// The path to the compiler resource directory.
     72   std::string ResourceDir;
     73 
     74   /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix'
     75   /// functionality.
     76   /// FIXME: This type of customization should be removed in favor of the
     77   /// universal driver when it is ready.
     78   typedef llvm::SmallVector<std::string, 4> prefix_list;
     79   prefix_list PrefixDirs;
     80 
     81   /// sysroot, if present
     82   std::string SysRoot;
     83 
     84   /// If the standard library is used
     85   bool UseStdLib;
     86 
     87   /// Default host triple.
     88   std::string DefaultHostTriple;
     89 
     90   /// Default name for linked images (e.g., "a.out").
     91   std::string DefaultImageName;
     92 
     93   /// Driver title to use with help.
     94   std::string DriverTitle;
     95 
     96   /// Host information for the platform the driver is running as. This
     97   /// will generally be the actual host platform, but not always.
     98   const HostInfo *Host;
     99 
    100   /// Information about the host which can be overridden by the user.
    101   std::string HostBits, HostMachine, HostSystem, HostRelease;
    102 
    103   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
    104   const char *CCPrintOptionsFilename;
    105 
    106   /// The file to log CC_PRINT_HEADERS output to, if enabled.
    107   const char *CCPrintHeadersFilename;
    108 
    109   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
    110   const char *CCLogDiagnosticsFilename;
    111 
    112   /// Whether the driver should follow g++ like behavior.
    113   unsigned CCCIsCXX : 1;
    114 
    115   /// Whether the driver is just the preprocessor
    116   unsigned CCCIsCPP : 1;
    117 
    118   /// Echo commands while executing (in -v style).
    119   unsigned CCCEcho : 1;
    120 
    121   /// Only print tool bindings, don't build any jobs.
    122   unsigned CCCPrintBindings : 1;
    123 
    124   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
    125   /// CCPrintOptionsFilename or to stderr.
    126   unsigned CCPrintOptions : 1;
    127 
    128   /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
    129   /// information to CCPrintHeadersFilename or to stderr.
    130   unsigned CCPrintHeaders : 1;
    131 
    132   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
    133   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
    134   /// format.
    135   unsigned CCLogDiagnostics : 1;
    136 
    137 private:
    138   /// Name to use when invoking gcc/g++.
    139   std::string CCCGenericGCCName;
    140 
    141   /// Whether to check that input files exist when constructing compilation
    142   /// jobs.
    143   unsigned CheckInputsExist : 1;
    144 
    145   /// Use the clang compiler where possible.
    146   unsigned CCCUseClang : 1;
    147 
    148   /// Use clang for handling C++ and Objective-C++ inputs.
    149   unsigned CCCUseClangCXX : 1;
    150 
    151   /// Use clang as a preprocessor (clang's preprocessor will still be
    152   /// used where an integrated CPP would).
    153   unsigned CCCUseClangCPP : 1;
    154 
    155 public:
    156   /// Use lazy precompiled headers for PCH support.
    157   unsigned CCCUsePCH : 1;
    158 
    159 private:
    160   /// Only use clang for the given architectures (only used when
    161   /// non-empty).
    162   std::set<llvm::Triple::ArchType> CCCClangArchs;
    163 
    164   /// Certain options suppress the 'no input files' warning.
    165   bool SuppressMissingInputWarning : 1;
    166 
    167   std::list<std::string> TempFiles;
    168   std::list<std::string> ResultFiles;
    169 
    170 private:
    171   /// TranslateInputArgs - Create a new derived argument list from the input
    172   /// arguments, after applying the standard argument translations.
    173   DerivedArgList *TranslateInputArgs(const InputArgList &Args) const;
    174 
    175 public:
    176   Driver(llvm::StringRef _ClangExecutable,
    177          llvm::StringRef _DefaultHostTriple,
    178          llvm::StringRef _DefaultImageName,
    179          bool IsProduction, bool CXXIsProduction,
    180          Diagnostic &_Diags);
    181   ~Driver();
    182 
    183   /// @name Accessors
    184   /// @{
    185 
    186   /// Name to use when invoking gcc/g++.
    187   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
    188 
    189 
    190   const OptTable &getOpts() const { return *Opts; }
    191 
    192   const Diagnostic &getDiags() const { return Diags; }
    193 
    194   bool getCheckInputsExist() const { return CheckInputsExist; }
    195 
    196   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
    197 
    198   const std::string &getTitle() { return DriverTitle; }
    199   void setTitle(std::string Value) { DriverTitle = Value; }
    200 
    201   /// \brief Get the path to the main clang executable.
    202   const char *getClangProgramPath() const {
    203     return ClangExecutable.c_str();
    204   }
    205 
    206   /// \brief Get the path to where the clang executable was installed.
    207   const char *getInstalledDir() const {
    208     if (!InstalledDir.empty())
    209       return InstalledDir.c_str();
    210     return Dir.c_str();
    211   }
    212   void setInstalledDir(llvm::StringRef Value) {
    213     InstalledDir = Value;
    214   }
    215 
    216   /// @}
    217   /// @name Primary Functionality
    218   /// @{
    219 
    220   /// BuildCompilation - Construct a compilation object for a command
    221   /// line argument vector.
    222   ///
    223   /// \return A compilation, or 0 if none was built for the given
    224   /// argument vector. A null return value does not necessarily
    225   /// indicate an error condition, the diagnostics should be queried
    226   /// to determine if an error occurred.
    227   Compilation *BuildCompilation(llvm::ArrayRef<const char *> Args);
    228 
    229   /// @name Driver Steps
    230   /// @{
    231 
    232   /// ParseArgStrings - Parse the given list of strings into an
    233   /// ArgList.
    234   InputArgList *ParseArgStrings(llvm::ArrayRef<const char *> Args);
    235 
    236   /// BuildActions - Construct the list of actions to perform for the
    237   /// given arguments, which are only done for a single architecture.
    238   ///
    239   /// \param TC - The default host tool chain.
    240   /// \param Args - The input arguments.
    241   /// \param Actions - The list to store the resulting actions onto.
    242   void BuildActions(const ToolChain &TC, const DerivedArgList &Args,
    243                     ActionList &Actions) const;
    244 
    245   /// BuildUniversalActions - Construct the list of actions to perform
    246   /// for the given arguments, which may require a universal build.
    247   ///
    248   /// \param TC - The default host tool chain.
    249   /// \param Args - The input arguments.
    250   /// \param Actions - The list to store the resulting actions onto.
    251   void BuildUniversalActions(const ToolChain &TC, const DerivedArgList &Args,
    252                              ActionList &Actions) const;
    253 
    254   /// BuildJobs - Bind actions to concrete tools and translate
    255   /// arguments to form the list of jobs to run.
    256   ///
    257   /// \arg C - The compilation that is being built.
    258   void BuildJobs(Compilation &C) const;
    259 
    260   /// ExecuteCompilation - Execute the compilation according to the command line
    261   /// arguments and return an appropriate exit code.
    262   ///
    263   /// This routine handles additional processing that must be done in addition
    264   /// to just running the subprocesses, for example reporting errors, removing
    265   /// temporary files, etc.
    266   int ExecuteCompilation(const Compilation &C) const;
    267 
    268   /// @}
    269   /// @name Helper Methods
    270   /// @{
    271 
    272   /// PrintActions - Print the list of actions.
    273   void PrintActions(const Compilation &C) const;
    274 
    275   /// PrintHelp - Print the help text.
    276   ///
    277   /// \param ShowHidden - Show hidden options.
    278   void PrintHelp(bool ShowHidden) const;
    279 
    280   /// PrintOptions - Print the list of arguments.
    281   void PrintOptions(const ArgList &Args) const;
    282 
    283   /// PrintVersion - Print the driver version.
    284   void PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const;
    285 
    286   /// GetFilePath - Lookup \arg Name in the list of file search paths.
    287   ///
    288   /// \arg TC - The tool chain for additional information on
    289   /// directories to search.
    290   //
    291   // FIXME: This should be in CompilationInfo.
    292   std::string GetFilePath(const char *Name, const ToolChain &TC) const;
    293 
    294   /// GetProgramPath - Lookup \arg Name in the list of program search
    295   /// paths.
    296   ///
    297   /// \arg TC - The provided tool chain for additional information on
    298   /// directories to search.
    299   ///
    300   /// \arg WantFile - False when searching for an executable file, otherwise
    301   /// true.  Defaults to false.
    302   //
    303   // FIXME: This should be in CompilationInfo.
    304   std::string GetProgramPath(const char *Name, const ToolChain &TC,
    305                               bool WantFile = false) const;
    306 
    307   /// HandleImmediateArgs - Handle any arguments which should be
    308   /// treated before building actions or binding tools.
    309   ///
    310   /// \return Whether any compilation should be built for this
    311   /// invocation.
    312   bool HandleImmediateArgs(const Compilation &C);
    313 
    314   /// ConstructAction - Construct the appropriate action to do for
    315   /// \arg Phase on the \arg Input, taking in to account arguments
    316   /// like -fsyntax-only or --analyze.
    317   Action *ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
    318                                Action *Input) const;
    319 
    320 
    321   /// BuildJobsForAction - Construct the jobs to perform for the
    322   /// action \arg A.
    323   void BuildJobsForAction(Compilation &C,
    324                           const Action *A,
    325                           const ToolChain *TC,
    326                           const char *BoundArch,
    327                           bool AtTopLevel,
    328                           const char *LinkingOutput,
    329                           InputInfo &Result) const;
    330 
    331   /// GetNamedOutputPath - Return the name to use for the output of
    332   /// the action \arg JA. The result is appended to the compilation's
    333   /// list of temporary or result files, as appropriate.
    334   ///
    335   /// \param C - The compilation.
    336   /// \param JA - The action of interest.
    337   /// \param BaseInput - The original input file that this action was
    338   /// triggered by.
    339   /// \param AtTopLevel - Whether this is a "top-level" action.
    340   const char *GetNamedOutputPath(Compilation &C,
    341                                  const JobAction &JA,
    342                                  const char *BaseInput,
    343                                  bool AtTopLevel) const;
    344 
    345   /// GetTemporaryPath - Return the pathname of a temporary file to
    346   /// use as part of compilation; the file will have the given suffix.
    347   ///
    348   /// GCC goes to extra lengths here to be a bit more robust.
    349   std::string GetTemporaryPath(const char *Suffix) const;
    350 
    351   /// GetHostInfo - Construct a new host info object for the given
    352   /// host triple.
    353   const HostInfo *GetHostInfo(const char *HostTriple) const;
    354 
    355   /// ShouldUseClangCompilar - Should the clang compiler be used to
    356   /// handle this action.
    357   bool ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
    358                               const llvm::Triple &ArchName) const;
    359 
    360   bool IsUsingLTO(const ArgList &Args) const;
    361 
    362   /// @}
    363 
    364   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
    365   /// return the grouped values as integers. Numbers which are not
    366   /// provided are set to 0.
    367   ///
    368   /// \return True if the entire string was parsed (9.2), or all
    369   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
    370   /// groups were parsed but extra characters remain at the end.
    371   static bool GetReleaseVersion(const char *Str, unsigned &Major,
    372                                 unsigned &Minor, unsigned &Micro,
    373                                 bool &HadExtra);
    374 };
    375 
    376 } // end namespace driver
    377 } // end namespace clang
    378 
    379 #endif
    380