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/Action.h"
     16 #include "clang/Driver/Phases.h"
     17 #include "clang/Driver/ToolChain.h"
     18 #include "clang/Driver/Types.h"
     19 #include "clang/Driver/Util.h"
     20 #include "llvm/ADT/StringMap.h"
     21 #include "llvm/ADT/StringRef.h"
     22 
     23 #include <list>
     24 #include <map>
     25 #include <string>
     26 
     27 namespace llvm {
     28 class Triple;
     29 
     30 namespace opt {
     31   class Arg;
     32   class ArgList;
     33   class DerivedArgList;
     34   class InputArgList;
     35   class OptTable;
     36 }
     37 }
     38 
     39 namespace clang {
     40 
     41 namespace vfs {
     42 class FileSystem;
     43 }
     44 
     45 namespace driver {
     46 
     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   std::unique_ptr<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   enum BitcodeEmbedMode {
     86     EmbedNone,
     87     EmbedMarker,
     88     EmbedBitcode
     89   } BitcodeEmbed;
     90 
     91   /// LTO mode selected via -f(no-)?lto(=.*)? options.
     92   LTOKind LTOMode;
     93 
     94 public:
     95   enum OpenMPRuntimeKind {
     96     /// An unknown OpenMP runtime. We can't generate effective OpenMP code
     97     /// without knowing what runtime to target.
     98     OMPRT_Unknown,
     99 
    100     /// The LLVM OpenMP runtime. When completed and integrated, this will become
    101     /// the default for Clang.
    102     OMPRT_OMP,
    103 
    104     /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
    105     /// this runtime but can swallow the pragmas, and find and link against the
    106     /// runtime library itself.
    107     OMPRT_GOMP,
    108 
    109     /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
    110     /// OpenMP runtime. We support this mode for users with existing
    111     /// dependencies on this runtime library name.
    112     OMPRT_IOMP5
    113   };
    114 
    115   // Diag - Forwarding function for diagnostics.
    116   DiagnosticBuilder Diag(unsigned DiagID) const {
    117     return Diags.Report(DiagID);
    118   }
    119 
    120   // FIXME: Privatize once interface is stable.
    121 public:
    122   /// The name the driver was invoked as.
    123   std::string Name;
    124 
    125   /// The path the driver executable was in, as invoked from the
    126   /// command line.
    127   std::string Dir;
    128 
    129   /// The original path to the clang executable.
    130   std::string ClangExecutable;
    131 
    132   /// The path to the installed clang directory, if any.
    133   std::string InstalledDir;
    134 
    135   /// The path to the compiler resource directory.
    136   std::string ResourceDir;
    137 
    138   /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
    139   /// functionality.
    140   /// FIXME: This type of customization should be removed in favor of the
    141   /// universal driver when it is ready.
    142   typedef SmallVector<std::string, 4> prefix_list;
    143   prefix_list PrefixDirs;
    144 
    145   /// sysroot, if present
    146   std::string SysRoot;
    147 
    148   /// Dynamic loader prefix, if present
    149   std::string DyldPrefix;
    150 
    151   /// If the standard library is used
    152   bool UseStdLib;
    153 
    154   /// Driver title to use with help.
    155   std::string DriverTitle;
    156 
    157   /// Information about the host which can be overridden by the user.
    158   std::string HostBits, HostMachine, HostSystem, HostRelease;
    159 
    160   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
    161   const char *CCPrintOptionsFilename;
    162 
    163   /// The file to log CC_PRINT_HEADERS output to, if enabled.
    164   const char *CCPrintHeadersFilename;
    165 
    166   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
    167   const char *CCLogDiagnosticsFilename;
    168 
    169   /// A list of inputs and their types for the given arguments.
    170   typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
    171       InputList;
    172 
    173   /// Whether the driver should follow g++ like behavior.
    174   bool CCCIsCXX() const { return Mode == GXXMode; }
    175 
    176   /// Whether the driver is just the preprocessor.
    177   bool CCCIsCPP() const { return Mode == CPPMode; }
    178 
    179   /// Whether the driver should follow gcc like behavior.
    180   bool CCCIsCC() const { return Mode == GCCMode; }
    181 
    182   /// Whether the driver should follow cl.exe like behavior.
    183   bool IsCLMode() const { return Mode == CLMode; }
    184 
    185   /// Only print tool bindings, don't build any jobs.
    186   unsigned CCCPrintBindings : 1;
    187 
    188   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
    189   /// CCPrintOptionsFilename or to stderr.
    190   unsigned CCPrintOptions : 1;
    191 
    192   /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
    193   /// information to CCPrintHeadersFilename or to stderr.
    194   unsigned CCPrintHeaders : 1;
    195 
    196   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
    197   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
    198   /// format.
    199   unsigned CCLogDiagnostics : 1;
    200 
    201   /// Whether the driver is generating diagnostics for debugging purposes.
    202   unsigned CCGenDiagnostics : 1;
    203 
    204 private:
    205   /// Default target triple.
    206   std::string DefaultTargetTriple;
    207 
    208   /// Name to use when invoking gcc/g++.
    209   std::string CCCGenericGCCName;
    210 
    211   /// Whether to check that input files exist when constructing compilation
    212   /// jobs.
    213   unsigned CheckInputsExist : 1;
    214 
    215 public:
    216   /// Use lazy precompiled headers for PCH support.
    217   unsigned CCCUsePCH : 1;
    218 
    219 private:
    220   /// Certain options suppress the 'no input files' warning.
    221   unsigned SuppressMissingInputWarning : 1;
    222 
    223   std::list<std::string> TempFiles;
    224   std::list<std::string> ResultFiles;
    225 
    226   /// \brief Cache of all the ToolChains in use by the driver.
    227   ///
    228   /// This maps from the string representation of a triple to a ToolChain
    229   /// created targeting that triple. The driver owns all the ToolChain objects
    230   /// stored in it, and will clean them up when torn down.
    231   mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
    232 
    233 private:
    234   /// TranslateInputArgs - Create a new derived argument list from the input
    235   /// arguments, after applying the standard argument translations.
    236   llvm::opt::DerivedArgList *
    237   TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
    238 
    239   // getFinalPhase - Determine which compilation mode we are in and record
    240   // which option we used to determine the final phase.
    241   phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
    242                            llvm::opt::Arg **FinalPhaseArg = nullptr) const;
    243 
    244   // Before executing jobs, sets up response files for commands that need them.
    245   void setUpResponseFiles(Compilation &C, Command &Cmd);
    246 
    247   void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
    248                                  SmallVectorImpl<std::string> &Names) const;
    249 
    250   /// \brief Find the appropriate .crash diagonostic file for the child crash
    251   /// under this driver and copy it out to a temporary destination with the
    252   /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
    253   /// directory for the user to look at.
    254   ///
    255   /// \param ReproCrashFilename The file path to copy the .crash to.
    256   /// \param CrashDiagDir       The suggested directory for the user to look at
    257   ///                           in case the search or copy fails.
    258   ///
    259   /// \returns If the .crash is found and successfully copied return true,
    260   /// otherwise false and return the suggested directory in \p CrashDiagDir.
    261   bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
    262                               SmallString<128> &CrashDiagDir);
    263 
    264 public:
    265   Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
    266          DiagnosticsEngine &Diags,
    267          IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
    268 
    269   /// @name Accessors
    270   /// @{
    271 
    272   /// Name to use when invoking gcc/g++.
    273   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
    274 
    275   const llvm::opt::OptTable &getOpts() const { return *Opts; }
    276 
    277   const DiagnosticsEngine &getDiags() const { return Diags; }
    278 
    279   vfs::FileSystem &getVFS() const { return *VFS; }
    280 
    281   bool getCheckInputsExist() const { return CheckInputsExist; }
    282 
    283   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
    284 
    285   const std::string &getTitle() { return DriverTitle; }
    286   void setTitle(std::string Value) { DriverTitle = std::move(Value); }
    287 
    288   /// \brief Get the path to the main clang executable.
    289   const char *getClangProgramPath() const {
    290     return ClangExecutable.c_str();
    291   }
    292 
    293   /// \brief Get the path to where the clang executable was installed.
    294   const char *getInstalledDir() const {
    295     if (!InstalledDir.empty())
    296       return InstalledDir.c_str();
    297     return Dir.c_str();
    298   }
    299   void setInstalledDir(StringRef Value) {
    300     InstalledDir = Value;
    301   }
    302 
    303   bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
    304   bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
    305 
    306   bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
    307   bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
    308   bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
    309 
    310   /// Compute the desired OpenMP runtime from the flags provided.
    311   OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
    312 
    313   /// @}
    314   /// @name Primary Functionality
    315   /// @{
    316 
    317   /// CreateOffloadingDeviceToolChains - create all the toolchains required to
    318   /// support offloading devices given the programming models specified in the
    319   /// current compilation. Also, update the host tool chain kind accordingly.
    320   void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
    321 
    322   /// BuildCompilation - Construct a compilation object for a command
    323   /// line argument vector.
    324   ///
    325   /// \return A compilation, or 0 if none was built for the given
    326   /// argument vector. A null return value does not necessarily
    327   /// indicate an error condition, the diagnostics should be queried
    328   /// to determine if an error occurred.
    329   Compilation *BuildCompilation(ArrayRef<const char *> Args);
    330 
    331   /// @name Driver Steps
    332   /// @{
    333 
    334   /// ParseDriverMode - Look for and handle the driver mode option in Args.
    335   void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
    336 
    337   /// ParseArgStrings - Parse the given list of strings into an
    338   /// ArgList.
    339   llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args);
    340 
    341   /// BuildInputs - Construct the list of inputs and their types from
    342   /// the given arguments.
    343   ///
    344   /// \param TC - The default host tool chain.
    345   /// \param Args - The input arguments.
    346   /// \param Inputs - The list to store the resulting compilation
    347   /// inputs onto.
    348   void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
    349                    InputList &Inputs) const;
    350 
    351   /// BuildActions - Construct the list of actions to perform for the
    352   /// given arguments, which are only done for a single architecture.
    353   ///
    354   /// \param C - The compilation that is being built.
    355   /// \param Args - The input arguments.
    356   /// \param Actions - The list to store the resulting actions onto.
    357   void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
    358                     const InputList &Inputs, ActionList &Actions) const;
    359 
    360   /// BuildUniversalActions - Construct the list of actions to perform
    361   /// for the given arguments, which may require a universal build.
    362   ///
    363   /// \param C - The compilation that is being built.
    364   /// \param TC - The default host tool chain.
    365   void BuildUniversalActions(Compilation &C, const ToolChain &TC,
    366                              const InputList &BAInputs) const;
    367 
    368   /// BuildJobs - Bind actions to concrete tools and translate
    369   /// arguments to form the list of jobs to run.
    370   ///
    371   /// \param C - The compilation that is being built.
    372   void BuildJobs(Compilation &C) const;
    373 
    374   /// ExecuteCompilation - Execute the compilation according to the command line
    375   /// arguments and return an appropriate exit code.
    376   ///
    377   /// This routine handles additional processing that must be done in addition
    378   /// to just running the subprocesses, for example reporting errors, setting
    379   /// up response files, removing temporary files, etc.
    380   int ExecuteCompilation(Compilation &C,
    381      SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
    382 
    383   /// generateCompilationDiagnostics - Generate diagnostics information
    384   /// including preprocessed source file(s).
    385   ///
    386   void generateCompilationDiagnostics(Compilation &C,
    387                                       const Command &FailingCommand);
    388 
    389   /// @}
    390   /// @name Helper Methods
    391   /// @{
    392 
    393   /// PrintActions - Print the list of actions.
    394   void PrintActions(const Compilation &C) const;
    395 
    396   /// PrintHelp - Print the help text.
    397   ///
    398   /// \param ShowHidden - Show hidden options.
    399   void PrintHelp(bool ShowHidden) const;
    400 
    401   /// PrintVersion - Print the driver version.
    402   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
    403 
    404   /// GetFilePath - Lookup \p Name in the list of file search paths.
    405   ///
    406   /// \param TC - The tool chain for additional information on
    407   /// directories to search.
    408   //
    409   // FIXME: This should be in CompilationInfo.
    410   std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
    411 
    412   /// GetProgramPath - Lookup \p Name in the list of program search paths.
    413   ///
    414   /// \param TC - The provided tool chain for additional information on
    415   /// directories to search.
    416   //
    417   // FIXME: This should be in CompilationInfo.
    418   std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
    419 
    420   /// HandleImmediateArgs - Handle any arguments which should be
    421   /// treated before building actions or binding tools.
    422   ///
    423   /// \return Whether any compilation should be built for this
    424   /// invocation.
    425   bool HandleImmediateArgs(const Compilation &C);
    426 
    427   /// ConstructAction - Construct the appropriate action to do for
    428   /// \p Phase on the \p Input, taking in to account arguments
    429   /// like -fsyntax-only or --analyze.
    430   Action *ConstructPhaseAction(Compilation &C, const llvm::opt::ArgList &Args,
    431                                phases::ID Phase, Action *Input) const;
    432 
    433   /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
    434   /// return an InputInfo for the result of running \p A.  Will only construct
    435   /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
    436   InputInfo
    437   BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
    438                      StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
    439                      const char *LinkingOutput,
    440                      std::map<std::pair<const Action *, std::string>, InputInfo>
    441                          &CachedResults,
    442                      Action::OffloadKind TargetDeviceOffloadKind) const;
    443 
    444   /// Returns the default name for linked images (e.g., "a.out").
    445   const char *getDefaultImageName() const;
    446 
    447   /// GetNamedOutputPath - Return the name to use for the output of
    448   /// the action \p JA. The result is appended to the compilation's
    449   /// list of temporary or result files, as appropriate.
    450   ///
    451   /// \param C - The compilation.
    452   /// \param JA - The action of interest.
    453   /// \param BaseInput - The original input file that this action was
    454   /// triggered by.
    455   /// \param BoundArch - The bound architecture.
    456   /// \param AtTopLevel - Whether this is a "top-level" action.
    457   /// \param MultipleArchs - Whether multiple -arch options were supplied.
    458   /// \param NormalizedTriple - The normalized triple of the relevant target.
    459   const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
    460                                  const char *BaseInput, StringRef BoundArch,
    461                                  bool AtTopLevel, bool MultipleArchs,
    462                                  StringRef NormalizedTriple) const;
    463 
    464   /// GetTemporaryPath - Return the pathname of a temporary file to use
    465   /// as part of compilation; the file will have the given prefix and suffix.
    466   ///
    467   /// GCC goes to extra lengths here to be a bit more robust.
    468   std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
    469 
    470   /// Return the pathname of the pch file in clang-cl mode.
    471   std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
    472 
    473   /// ShouldUseClangCompiler - Should the clang compiler be used to
    474   /// handle this action.
    475   bool ShouldUseClangCompiler(const JobAction &JA) const;
    476 
    477   /// Returns true if we are performing any kind of LTO.
    478   bool isUsingLTO() const { return LTOMode != LTOK_None; }
    479 
    480   /// Get the specific kind of LTO being performed.
    481   LTOKind getLTOMode() const { return LTOMode; }
    482 
    483 private:
    484   /// Set the driver mode (cl, gcc, etc) from an option string of the form
    485   /// --driver-mode=<mode>.
    486   void setDriverModeFromOption(StringRef Opt);
    487 
    488   /// Parse the \p Args list for LTO options and record the type of LTO
    489   /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
    490   void setLTOMode(const llvm::opt::ArgList &Args);
    491 
    492   /// \brief Retrieves a ToolChain for a particular \p Target triple.
    493   ///
    494   /// Will cache ToolChains for the life of the driver object, and create them
    495   /// on-demand.
    496   const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
    497                                 const llvm::Triple &Target) const;
    498 
    499   /// @}
    500 
    501   /// \brief Get bitmasks for which option flags to include and exclude based on
    502   /// the driver mode.
    503   std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
    504 
    505   /// Helper used in BuildJobsForAction.  Doesn't use the cache when building
    506   /// jobs specifically for the given action, but will use the cache when
    507   /// building jobs for the Action's inputs.
    508   InputInfo BuildJobsForActionNoCache(
    509       Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
    510       bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
    511       std::map<std::pair<const Action *, std::string>, InputInfo>
    512           &CachedResults,
    513       Action::OffloadKind TargetDeviceOffloadKind) const;
    514 
    515 public:
    516   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
    517   /// return the grouped values as integers. Numbers which are not
    518   /// provided are set to 0.
    519   ///
    520   /// \return True if the entire string was parsed (9.2), or all
    521   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
    522   /// groups were parsed but extra characters remain at the end.
    523   static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
    524                                 unsigned &Micro, bool &HadExtra);
    525 
    526   /// Parse digits from a string \p Str and fulfill \p Digits with
    527   /// the parsed numbers. This method assumes that the max number of
    528   /// digits to look for is equal to Digits.size().
    529   ///
    530   /// \return True if the entire string was parsed and there are
    531   /// no extra characters remaining at the end.
    532   static bool GetReleaseVersion(StringRef Str,
    533                                 MutableArrayRef<unsigned> Digits);
    534 };
    535 
    536 /// \return True if the last defined optimization level is -Ofast.
    537 /// And False otherwise.
    538 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
    539 
    540 } // end namespace driver
    541 } // end namespace clang
    542 
    543 #endif
    544