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   /// Target and driver mode components extracted from clang executable name.
    133   ParsedClangName ClangNameParts;
    134 
    135   /// The path to the installed clang directory, if any.
    136   std::string InstalledDir;
    137 
    138   /// The path to the compiler resource directory.
    139   std::string ResourceDir;
    140 
    141   /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
    142   /// functionality.
    143   /// FIXME: This type of customization should be removed in favor of the
    144   /// universal driver when it is ready.
    145   typedef SmallVector<std::string, 4> prefix_list;
    146   prefix_list PrefixDirs;
    147 
    148   /// sysroot, if present
    149   std::string SysRoot;
    150 
    151   /// Dynamic loader prefix, if present
    152   std::string DyldPrefix;
    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   /// Force clang to emit reproducer for driver invocation. This is enabled
    220   /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
    221   /// or when using the -gen-reproducer driver flag.
    222   unsigned GenReproducer : 1;
    223 
    224 private:
    225   /// Certain options suppress the 'no input files' warning.
    226   unsigned SuppressMissingInputWarning : 1;
    227 
    228   std::list<std::string> TempFiles;
    229   std::list<std::string> ResultFiles;
    230 
    231   /// \brief Cache of all the ToolChains in use by the driver.
    232   ///
    233   /// This maps from the string representation of a triple to a ToolChain
    234   /// created targeting that triple. The driver owns all the ToolChain objects
    235   /// stored in it, and will clean them up when torn down.
    236   mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
    237 
    238 private:
    239   /// TranslateInputArgs - Create a new derived argument list from the input
    240   /// arguments, after applying the standard argument translations.
    241   llvm::opt::DerivedArgList *
    242   TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
    243 
    244   // getFinalPhase - Determine which compilation mode we are in and record
    245   // which option we used to determine the final phase.
    246   phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
    247                            llvm::opt::Arg **FinalPhaseArg = nullptr) const;
    248 
    249   // Before executing jobs, sets up response files for commands that need them.
    250   void setUpResponseFiles(Compilation &C, Command &Cmd);
    251 
    252   void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
    253                                  SmallVectorImpl<std::string> &Names) const;
    254 
    255   /// \brief Find the appropriate .crash diagonostic file for the child crash
    256   /// under this driver and copy it out to a temporary destination with the
    257   /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
    258   /// directory for the user to look at.
    259   ///
    260   /// \param ReproCrashFilename The file path to copy the .crash to.
    261   /// \param CrashDiagDir       The suggested directory for the user to look at
    262   ///                           in case the search or copy fails.
    263   ///
    264   /// \returns If the .crash is found and successfully copied return true,
    265   /// otherwise false and return the suggested directory in \p CrashDiagDir.
    266   bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
    267                               SmallString<128> &CrashDiagDir);
    268 
    269 public:
    270   Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
    271          DiagnosticsEngine &Diags,
    272          IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
    273 
    274   /// @name Accessors
    275   /// @{
    276 
    277   /// Name to use when invoking gcc/g++.
    278   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
    279 
    280   const llvm::opt::OptTable &getOpts() const { return *Opts; }
    281 
    282   const DiagnosticsEngine &getDiags() const { return Diags; }
    283 
    284   vfs::FileSystem &getVFS() const { return *VFS; }
    285 
    286   bool getCheckInputsExist() const { return CheckInputsExist; }
    287 
    288   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
    289 
    290   void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
    291 
    292   const std::string &getTitle() { return DriverTitle; }
    293   void setTitle(std::string Value) { DriverTitle = std::move(Value); }
    294 
    295   /// \brief Get the path to the main clang executable.
    296   const char *getClangProgramPath() const {
    297     return ClangExecutable.c_str();
    298   }
    299 
    300   /// \brief Get the path to where the clang executable was installed.
    301   const char *getInstalledDir() const {
    302     if (!InstalledDir.empty())
    303       return InstalledDir.c_str();
    304     return Dir.c_str();
    305   }
    306   void setInstalledDir(StringRef Value) {
    307     InstalledDir = Value;
    308   }
    309 
    310   bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
    311   bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
    312 
    313   bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
    314   bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
    315   bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
    316 
    317   /// Compute the desired OpenMP runtime from the flags provided.
    318   OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
    319 
    320   /// @}
    321   /// @name Primary Functionality
    322   /// @{
    323 
    324   /// CreateOffloadingDeviceToolChains - create all the toolchains required to
    325   /// support offloading devices given the programming models specified in the
    326   /// current compilation. Also, update the host tool chain kind accordingly.
    327   void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
    328 
    329   /// BuildCompilation - Construct a compilation object for a command
    330   /// line argument vector.
    331   ///
    332   /// \return A compilation, or 0 if none was built for the given
    333   /// argument vector. A null return value does not necessarily
    334   /// indicate an error condition, the diagnostics should be queried
    335   /// to determine if an error occurred.
    336   Compilation *BuildCompilation(ArrayRef<const char *> Args);
    337 
    338   /// @name Driver Steps
    339   /// @{
    340 
    341   /// ParseDriverMode - Look for and handle the driver mode option in Args.
    342   void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
    343 
    344   /// ParseArgStrings - Parse the given list of strings into an
    345   /// ArgList.
    346   llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
    347                                           bool &ContainsError);
    348 
    349   /// BuildInputs - Construct the list of inputs and their types from
    350   /// the given arguments.
    351   ///
    352   /// \param TC - The default host tool chain.
    353   /// \param Args - The input arguments.
    354   /// \param Inputs - The list to store the resulting compilation
    355   /// inputs onto.
    356   void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
    357                    InputList &Inputs) const;
    358 
    359   /// BuildActions - Construct the list of actions to perform for the
    360   /// given arguments, which are only done for a single architecture.
    361   ///
    362   /// \param C - The compilation that is being built.
    363   /// \param Args - The input arguments.
    364   /// \param Actions - The list to store the resulting actions onto.
    365   void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
    366                     const InputList &Inputs, ActionList &Actions) const;
    367 
    368   /// BuildUniversalActions - Construct the list of actions to perform
    369   /// for the given arguments, which may require a universal build.
    370   ///
    371   /// \param C - The compilation that is being built.
    372   /// \param TC - The default host tool chain.
    373   void BuildUniversalActions(Compilation &C, const ToolChain &TC,
    374                              const InputList &BAInputs) const;
    375 
    376   /// BuildJobs - Bind actions to concrete tools and translate
    377   /// arguments to form the list of jobs to run.
    378   ///
    379   /// \param C - The compilation that is being built.
    380   void BuildJobs(Compilation &C) const;
    381 
    382   /// ExecuteCompilation - Execute the compilation according to the command line
    383   /// arguments and return an appropriate exit code.
    384   ///
    385   /// This routine handles additional processing that must be done in addition
    386   /// to just running the subprocesses, for example reporting errors, setting
    387   /// up response files, removing temporary files, etc.
    388   int ExecuteCompilation(Compilation &C,
    389      SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
    390 
    391   /// generateCompilationDiagnostics - Generate diagnostics information
    392   /// including preprocessed source file(s).
    393   ///
    394   void generateCompilationDiagnostics(Compilation &C,
    395                                       const Command &FailingCommand);
    396 
    397   /// @}
    398   /// @name Helper Methods
    399   /// @{
    400 
    401   /// PrintActions - Print the list of actions.
    402   void PrintActions(const Compilation &C) const;
    403 
    404   /// PrintHelp - Print the help text.
    405   ///
    406   /// \param ShowHidden - Show hidden options.
    407   void PrintHelp(bool ShowHidden) const;
    408 
    409   /// PrintVersion - Print the driver version.
    410   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
    411 
    412   /// GetFilePath - Lookup \p Name in the list of file search paths.
    413   ///
    414   /// \param TC - The tool chain for additional information on
    415   /// directories to search.
    416   //
    417   // FIXME: This should be in CompilationInfo.
    418   std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
    419 
    420   /// GetProgramPath - Lookup \p Name in the list of program search paths.
    421   ///
    422   /// \param TC - The provided tool chain for additional information on
    423   /// directories to search.
    424   //
    425   // FIXME: This should be in CompilationInfo.
    426   std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
    427 
    428   /// handleAutocompletions - Handle --autocomplete by searching and printing
    429   /// possible flags, descriptions, and its arguments.
    430   void handleAutocompletions(StringRef PassedFlags) const;
    431 
    432   /// HandleImmediateArgs - Handle any arguments which should be
    433   /// treated before building actions or binding tools.
    434   ///
    435   /// \return Whether any compilation should be built for this
    436   /// invocation.
    437   bool HandleImmediateArgs(const Compilation &C);
    438 
    439   /// ConstructAction - Construct the appropriate action to do for
    440   /// \p Phase on the \p Input, taking in to account arguments
    441   /// like -fsyntax-only or --analyze.
    442   Action *ConstructPhaseAction(Compilation &C, const llvm::opt::ArgList &Args,
    443                                phases::ID Phase, Action *Input) const;
    444 
    445   /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
    446   /// return an InputInfo for the result of running \p A.  Will only construct
    447   /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
    448   InputInfo
    449   BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
    450                      StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
    451                      const char *LinkingOutput,
    452                      std::map<std::pair<const Action *, std::string>, InputInfo>
    453                          &CachedResults,
    454                      Action::OffloadKind TargetDeviceOffloadKind) const;
    455 
    456   /// Returns the default name for linked images (e.g., "a.out").
    457   const char *getDefaultImageName() const;
    458 
    459   /// GetNamedOutputPath - Return the name to use for the output of
    460   /// the action \p JA. The result is appended to the compilation's
    461   /// list of temporary or result files, as appropriate.
    462   ///
    463   /// \param C - The compilation.
    464   /// \param JA - The action of interest.
    465   /// \param BaseInput - The original input file that this action was
    466   /// triggered by.
    467   /// \param BoundArch - The bound architecture.
    468   /// \param AtTopLevel - Whether this is a "top-level" action.
    469   /// \param MultipleArchs - Whether multiple -arch options were supplied.
    470   /// \param NormalizedTriple - The normalized triple of the relevant target.
    471   const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
    472                                  const char *BaseInput, StringRef BoundArch,
    473                                  bool AtTopLevel, bool MultipleArchs,
    474                                  StringRef NormalizedTriple) const;
    475 
    476   /// GetTemporaryPath - Return the pathname of a temporary file to use
    477   /// as part of compilation; the file will have the given prefix and suffix.
    478   ///
    479   /// GCC goes to extra lengths here to be a bit more robust.
    480   std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
    481 
    482   /// Return the pathname of the pch file in clang-cl mode.
    483   std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
    484 
    485   /// ShouldUseClangCompiler - Should the clang compiler be used to
    486   /// handle this action.
    487   bool ShouldUseClangCompiler(const JobAction &JA) const;
    488 
    489   /// Returns true if we are performing any kind of LTO.
    490   bool isUsingLTO() const { return LTOMode != LTOK_None; }
    491 
    492   /// Get the specific kind of LTO being performed.
    493   LTOKind getLTOMode() const { return LTOMode; }
    494 
    495 private:
    496   /// Set the driver mode (cl, gcc, etc) from an option string of the form
    497   /// --driver-mode=<mode>.
    498   void setDriverModeFromOption(StringRef Opt);
    499 
    500   /// Parse the \p Args list for LTO options and record the type of LTO
    501   /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
    502   void setLTOMode(const llvm::opt::ArgList &Args);
    503 
    504   /// \brief Retrieves a ToolChain for a particular \p Target triple.
    505   ///
    506   /// Will cache ToolChains for the life of the driver object, and create them
    507   /// on-demand.
    508   const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
    509                                 const llvm::Triple &Target) const;
    510 
    511   /// @}
    512 
    513   /// \brief Get bitmasks for which option flags to include and exclude based on
    514   /// the driver mode.
    515   std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
    516 
    517   /// Helper used in BuildJobsForAction.  Doesn't use the cache when building
    518   /// jobs specifically for the given action, but will use the cache when
    519   /// building jobs for the Action's inputs.
    520   InputInfo BuildJobsForActionNoCache(
    521       Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
    522       bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
    523       std::map<std::pair<const Action *, std::string>, InputInfo>
    524           &CachedResults,
    525       Action::OffloadKind TargetDeviceOffloadKind) const;
    526 
    527 public:
    528   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
    529   /// return the grouped values as integers. Numbers which are not
    530   /// provided are set to 0.
    531   ///
    532   /// \return True if the entire string was parsed (9.2), or all
    533   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
    534   /// groups were parsed but extra characters remain at the end.
    535   static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
    536                                 unsigned &Micro, bool &HadExtra);
    537 
    538   /// Parse digits from a string \p Str and fulfill \p Digits with
    539   /// the parsed numbers. This method assumes that the max number of
    540   /// digits to look for is equal to Digits.size().
    541   ///
    542   /// \return True if the entire string was parsed and there are
    543   /// no extra characters remaining at the end.
    544   static bool GetReleaseVersion(StringRef Str,
    545                                 MutableArrayRef<unsigned> Digits);
    546 };
    547 
    548 /// \return True if the last defined optimization level is -Ofast.
    549 /// And False otherwise.
    550 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
    551 
    552 } // end namespace driver
    553 } // end namespace clang
    554 
    555 #endif
    556