Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:52

0001 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLVM_CLANG_DRIVER_DRIVER_H
0010 #define LLVM_CLANG_DRIVER_DRIVER_H
0011 
0012 #include "clang/Basic/Diagnostic.h"
0013 #include "clang/Basic/HeaderInclude.h"
0014 #include "clang/Basic/LLVM.h"
0015 #include "clang/Driver/Action.h"
0016 #include "clang/Driver/DriverDiagnostic.h"
0017 #include "clang/Driver/InputInfo.h"
0018 #include "clang/Driver/Options.h"
0019 #include "clang/Driver/Phases.h"
0020 #include "clang/Driver/ToolChain.h"
0021 #include "clang/Driver/Types.h"
0022 #include "clang/Driver/Util.h"
0023 #include "llvm/ADT/ArrayRef.h"
0024 #include "llvm/ADT/STLFunctionalExtras.h"
0025 #include "llvm/ADT/StringMap.h"
0026 #include "llvm/ADT/StringRef.h"
0027 #include "llvm/Option/Arg.h"
0028 #include "llvm/Option/ArgList.h"
0029 #include "llvm/Support/StringSaver.h"
0030 
0031 #include <map>
0032 #include <set>
0033 #include <string>
0034 #include <vector>
0035 
0036 namespace llvm {
0037 class Triple;
0038 namespace vfs {
0039 class FileSystem;
0040 }
0041 namespace cl {
0042 class ExpansionContext;
0043 }
0044 } // namespace llvm
0045 
0046 namespace clang {
0047 
0048 namespace driver {
0049 
0050 typedef SmallVector<InputInfo, 4> InputInfoList;
0051 
0052 class Command;
0053 class Compilation;
0054 class JobAction;
0055 class ToolChain;
0056 
0057 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
0058 enum LTOKind {
0059   LTOK_None,
0060   LTOK_Full,
0061   LTOK_Thin,
0062   LTOK_Unknown
0063 };
0064 
0065 /// Whether headers used to construct C++20 module units should be looked
0066 /// up by the path supplied on the command line, or in the user or system
0067 /// search paths.
0068 enum ModuleHeaderMode {
0069   HeaderMode_None,
0070   HeaderMode_Default,
0071   HeaderMode_User,
0072   HeaderMode_System
0073 };
0074 
0075 /// Options for specifying CUID used by CUDA/HIP for uniquely identifying
0076 /// compilation units.
0077 class CUIDOptions {
0078 public:
0079   enum class Kind { Hash, Random, Fixed, None, Invalid };
0080 
0081   CUIDOptions() = default;
0082   CUIDOptions(llvm::opt::DerivedArgList &Args, const Driver &D);
0083 
0084   // Get the CUID for an input string
0085   std::string getCUID(StringRef InputFile,
0086                       llvm::opt::DerivedArgList &Args) const;
0087 
0088   bool isEnabled() const {
0089     return UseCUID != Kind::None && UseCUID != Kind::Invalid;
0090   }
0091 
0092 private:
0093   Kind UseCUID = Kind::None;
0094   StringRef FixedCUID;
0095 };
0096 
0097 /// Driver - Encapsulate logic for constructing compilation processes
0098 /// from a set of gcc-driver-like command line arguments.
0099 class Driver {
0100   DiagnosticsEngine &Diags;
0101 
0102   IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
0103 
0104   enum DriverMode {
0105     GCCMode,
0106     GXXMode,
0107     CPPMode,
0108     CLMode,
0109     FlangMode,
0110     DXCMode
0111   } Mode;
0112 
0113   enum SaveTempsMode {
0114     SaveTempsNone,
0115     SaveTempsCwd,
0116     SaveTempsObj
0117   } SaveTemps;
0118 
0119   enum BitcodeEmbedMode {
0120     EmbedNone,
0121     EmbedMarker,
0122     EmbedBitcode
0123   } BitcodeEmbed;
0124 
0125   enum OffloadMode {
0126     OffloadHostDevice,
0127     OffloadHost,
0128     OffloadDevice,
0129   } Offload;
0130 
0131   /// Header unit mode set by -fmodule-header={user,system}.
0132   ModuleHeaderMode CXX20HeaderType;
0133 
0134   /// Set if we should process inputs and jobs with C++20 module
0135   /// interpretation.
0136   bool ModulesModeCXX20;
0137 
0138   /// LTO mode selected via -f(no-)?lto(=.*)? options.
0139   LTOKind LTOMode;
0140 
0141   /// LTO mode selected via -f(no-offload-)?lto(=.*)? options.
0142   LTOKind OffloadLTOMode;
0143 
0144   /// Options for CUID
0145   CUIDOptions CUIDOpts;
0146 
0147 public:
0148   enum OpenMPRuntimeKind {
0149     /// An unknown OpenMP runtime. We can't generate effective OpenMP code
0150     /// without knowing what runtime to target.
0151     OMPRT_Unknown,
0152 
0153     /// The LLVM OpenMP runtime. When completed and integrated, this will become
0154     /// the default for Clang.
0155     OMPRT_OMP,
0156 
0157     /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
0158     /// this runtime but can swallow the pragmas, and find and link against the
0159     /// runtime library itself.
0160     OMPRT_GOMP,
0161 
0162     /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
0163     /// OpenMP runtime. We support this mode for users with existing
0164     /// dependencies on this runtime library name.
0165     OMPRT_IOMP5
0166   };
0167 
0168   // Diag - Forwarding function for diagnostics.
0169   DiagnosticBuilder Diag(unsigned DiagID) const {
0170     return Diags.Report(DiagID);
0171   }
0172 
0173   // FIXME: Privatize once interface is stable.
0174 public:
0175   /// The name the driver was invoked as.
0176   std::string Name;
0177 
0178   /// The path the driver executable was in, as invoked from the
0179   /// command line.
0180   std::string Dir;
0181 
0182   /// The original path to the clang executable.
0183   std::string ClangExecutable;
0184 
0185   /// Target and driver mode components extracted from clang executable name.
0186   ParsedClangName ClangNameParts;
0187 
0188   /// The path to the compiler resource directory.
0189   std::string ResourceDir;
0190 
0191   /// System directory for config files.
0192   std::string SystemConfigDir;
0193 
0194   /// User directory for config files.
0195   std::string UserConfigDir;
0196 
0197   /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
0198   /// functionality.
0199   /// FIXME: This type of customization should be removed in favor of the
0200   /// universal driver when it is ready.
0201   typedef SmallVector<std::string, 4> prefix_list;
0202   prefix_list PrefixDirs;
0203 
0204   /// sysroot, if present
0205   std::string SysRoot;
0206 
0207   /// Dynamic loader prefix, if present
0208   std::string DyldPrefix;
0209 
0210   /// Driver title to use with help.
0211   std::string DriverTitle;
0212 
0213   /// Information about the host which can be overridden by the user.
0214   std::string HostBits, HostMachine, HostSystem, HostRelease;
0215 
0216   /// The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled.
0217   std::string CCPrintStatReportFilename;
0218 
0219   /// The file to log CC_PRINT_INTERNAL_STAT_FILE output to, if enabled.
0220   std::string CCPrintInternalStatReportFilename;
0221 
0222   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
0223   std::string CCPrintOptionsFilename;
0224 
0225   /// The file to log CC_PRINT_HEADERS output to, if enabled.
0226   std::string CCPrintHeadersFilename;
0227 
0228   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
0229   std::string CCLogDiagnosticsFilename;
0230 
0231   /// An input type and its arguments.
0232   using InputTy = std::pair<types::ID, const llvm::opt::Arg *>;
0233 
0234   /// A list of inputs and their types for the given arguments.
0235   using InputList = SmallVector<InputTy, 16>;
0236 
0237   /// Whether the driver should follow g++ like behavior.
0238   bool CCCIsCXX() const { return Mode == GXXMode; }
0239 
0240   /// Whether the driver is just the preprocessor.
0241   bool CCCIsCPP() const { return Mode == CPPMode; }
0242 
0243   /// Whether the driver should follow gcc like behavior.
0244   bool CCCIsCC() const { return Mode == GCCMode; }
0245 
0246   /// Whether the driver should follow cl.exe like behavior.
0247   bool IsCLMode() const { return Mode == CLMode; }
0248 
0249   /// Whether the driver should invoke flang for fortran inputs.
0250   /// Other modes fall back to calling gcc which in turn calls gfortran.
0251   bool IsFlangMode() const { return Mode == FlangMode; }
0252 
0253   /// Whether the driver should follow dxc.exe like behavior.
0254   bool IsDXCMode() const { return Mode == DXCMode; }
0255 
0256   /// Only print tool bindings, don't build any jobs.
0257   LLVM_PREFERRED_TYPE(bool)
0258   unsigned CCCPrintBindings : 1;
0259 
0260   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
0261   /// CCPrintOptionsFilename or to stderr.
0262   LLVM_PREFERRED_TYPE(bool)
0263   unsigned CCPrintOptions : 1;
0264 
0265   /// The format of the header information that is emitted. If CC_PRINT_HEADERS
0266   /// is set, the format is textual. Otherwise, the format is determined by the
0267   /// enviroment variable CC_PRINT_HEADERS_FORMAT.
0268   HeaderIncludeFormatKind CCPrintHeadersFormat = HIFMT_None;
0269 
0270   /// This flag determines whether clang should filter the header information
0271   /// that is emitted. If enviroment variable CC_PRINT_HEADERS_FILTERING is set
0272   /// to "only-direct-system", only system headers that are directly included
0273   /// from non-system headers are emitted.
0274   HeaderIncludeFilteringKind CCPrintHeadersFiltering = HIFIL_None;
0275 
0276   /// Name of the library that provides implementations of
0277   /// IEEE-754 128-bit float math functions used by Fortran F128
0278   /// runtime library. It should be linked as needed by the linker job.
0279   std::string FlangF128MathLibrary;
0280 
0281   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
0282   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
0283   /// format.
0284   LLVM_PREFERRED_TYPE(bool)
0285   unsigned CCLogDiagnostics : 1;
0286 
0287   /// Whether the driver is generating diagnostics for debugging purposes.
0288   LLVM_PREFERRED_TYPE(bool)
0289   unsigned CCGenDiagnostics : 1;
0290 
0291   /// Set CC_PRINT_PROC_STAT mode, which causes the driver to dump
0292   /// performance report to CC_PRINT_PROC_STAT_FILE or to stdout.
0293   LLVM_PREFERRED_TYPE(bool)
0294   unsigned CCPrintProcessStats : 1;
0295 
0296   /// Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal
0297   /// performance report to CC_PRINT_INTERNAL_STAT_FILE or to stdout.
0298   LLVM_PREFERRED_TYPE(bool)
0299   unsigned CCPrintInternalStats : 1;
0300 
0301   /// Pointer to the ExecuteCC1Tool function, if available.
0302   /// When the clangDriver lib is used through clang.exe, this provides a
0303   /// shortcut for executing the -cc1 command-line directly, in the same
0304   /// process.
0305   using CC1ToolFunc =
0306       llvm::function_ref<int(SmallVectorImpl<const char *> &ArgV)>;
0307   CC1ToolFunc CC1Main = nullptr;
0308 
0309 private:
0310   /// Raw target triple.
0311   std::string TargetTriple;
0312 
0313   /// Name to use when invoking gcc/g++.
0314   std::string CCCGenericGCCName;
0315 
0316   /// Paths to configuration files used.
0317   std::vector<std::string> ConfigFiles;
0318 
0319   /// Allocator for string saver.
0320   llvm::BumpPtrAllocator Alloc;
0321 
0322   /// Object that stores strings read from configuration file.
0323   llvm::StringSaver Saver;
0324 
0325   /// Arguments originated from configuration file (head part).
0326   std::unique_ptr<llvm::opt::InputArgList> CfgOptionsHead;
0327 
0328   /// Arguments originated from configuration file (tail part).
0329   std::unique_ptr<llvm::opt::InputArgList> CfgOptionsTail;
0330 
0331   /// Arguments originated from command line.
0332   std::unique_ptr<llvm::opt::InputArgList> CLOptions;
0333 
0334   /// If this is non-null, the driver will prepend this argument before
0335   /// reinvoking clang. This is useful for the llvm-driver where clang's
0336   /// realpath will be to the llvm binary and not clang, so it must pass
0337   /// "clang" as it's first argument.
0338   const char *PrependArg;
0339 
0340   /// Whether to check that input files exist when constructing compilation
0341   /// jobs.
0342   LLVM_PREFERRED_TYPE(bool)
0343   unsigned CheckInputsExist : 1;
0344   /// Whether to probe for PCH files on disk, in order to upgrade
0345   /// -include foo.h to -include-pch foo.h.pch.
0346   LLVM_PREFERRED_TYPE(bool)
0347   unsigned ProbePrecompiled : 1;
0348 
0349 public:
0350   // getFinalPhase - Determine which compilation mode we are in and record
0351   // which option we used to determine the final phase.
0352   // TODO: Much of what getFinalPhase returns are not actually true compiler
0353   //       modes. Fold this functionality into Types::getCompilationPhases and
0354   //       handleArguments.
0355   phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
0356                            llvm::opt::Arg **FinalPhaseArg = nullptr) const;
0357 
0358 private:
0359   /// Certain options suppress the 'no input files' warning.
0360   LLVM_PREFERRED_TYPE(bool)
0361   unsigned SuppressMissingInputWarning : 1;
0362 
0363   /// Cache of all the ToolChains in use by the driver.
0364   ///
0365   /// This maps from the string representation of a triple to a ToolChain
0366   /// created targeting that triple. The driver owns all the ToolChain objects
0367   /// stored in it, and will clean them up when torn down.
0368   mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
0369 
0370   /// Cache of known offloading architectures for the ToolChain already derived.
0371   /// This should only be modified when we first initialize the offloading
0372   /// toolchains.
0373   llvm::DenseMap<const ToolChain *, llvm::DenseSet<llvm::StringRef>> KnownArchs;
0374 
0375 private:
0376   /// TranslateInputArgs - Create a new derived argument list from the input
0377   /// arguments, after applying the standard argument translations.
0378   llvm::opt::DerivedArgList *
0379   TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
0380 
0381   // handleArguments - All code related to claiming and printing diagnostics
0382   // related to arguments to the driver are done here.
0383   void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args,
0384                        const InputList &Inputs, ActionList &Actions) const;
0385 
0386   // Before executing jobs, sets up response files for commands that need them.
0387   void setUpResponseFiles(Compilation &C, Command &Cmd);
0388 
0389   void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
0390                                  SmallVectorImpl<std::string> &Names) const;
0391 
0392   /// Find the appropriate .crash diagonostic file for the child crash
0393   /// under this driver and copy it out to a temporary destination with the
0394   /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
0395   /// directory for the user to look at.
0396   ///
0397   /// \param ReproCrashFilename The file path to copy the .crash to.
0398   /// \param CrashDiagDir       The suggested directory for the user to look at
0399   ///                           in case the search or copy fails.
0400   ///
0401   /// \returns If the .crash is found and successfully copied return true,
0402   /// otherwise false and return the suggested directory in \p CrashDiagDir.
0403   bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
0404                               SmallString<128> &CrashDiagDir);
0405 
0406 public:
0407 
0408   /// Takes the path to a binary that's either in bin/ or lib/ and returns
0409   /// the path to clang's resource directory.
0410   static std::string GetResourcesPath(StringRef BinaryPath);
0411 
0412   Driver(StringRef ClangExecutable, StringRef TargetTriple,
0413          DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler",
0414          IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
0415 
0416   /// @name Accessors
0417   /// @{
0418 
0419   /// Name to use when invoking gcc/g++.
0420   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
0421 
0422   llvm::ArrayRef<std::string> getConfigFiles() const {
0423     return ConfigFiles;
0424   }
0425 
0426   const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
0427 
0428   DiagnosticsEngine &getDiags() const { return Diags; }
0429 
0430   llvm::vfs::FileSystem &getVFS() const { return *VFS; }
0431 
0432   bool getCheckInputsExist() const { return CheckInputsExist; }
0433 
0434   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
0435 
0436   bool getProbePrecompiled() const { return ProbePrecompiled; }
0437   void setProbePrecompiled(bool Value) { ProbePrecompiled = Value; }
0438 
0439   const char *getPrependArg() const { return PrependArg; }
0440   void setPrependArg(const char *Value) { PrependArg = Value; }
0441 
0442   void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
0443 
0444   const std::string &getTitle() { return DriverTitle; }
0445   void setTitle(std::string Value) { DriverTitle = std::move(Value); }
0446 
0447   std::string getTargetTriple() const { return TargetTriple; }
0448 
0449   /// Get the path to the main clang executable.
0450   const char *getClangProgramPath() const {
0451     return ClangExecutable.c_str();
0452   }
0453 
0454   bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
0455   bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
0456 
0457   bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
0458   bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
0459   bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
0460 
0461   bool offloadHostOnly() const { return Offload == OffloadHost; }
0462   bool offloadDeviceOnly() const { return Offload == OffloadDevice; }
0463 
0464   void setFlangF128MathLibrary(std::string name) {
0465     FlangF128MathLibrary = std::move(name);
0466   }
0467   StringRef getFlangF128MathLibrary() const { return FlangF128MathLibrary; }
0468 
0469   /// Compute the desired OpenMP runtime from the flags provided.
0470   OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
0471 
0472   /// @}
0473   /// @name Primary Functionality
0474   /// @{
0475 
0476   /// CreateOffloadingDeviceToolChains - create all the toolchains required to
0477   /// support offloading devices given the programming models specified in the
0478   /// current compilation. Also, update the host tool chain kind accordingly.
0479   void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
0480 
0481   /// BuildCompilation - Construct a compilation object for a command
0482   /// line argument vector.
0483   ///
0484   /// \return A compilation, or 0 if none was built for the given
0485   /// argument vector. A null return value does not necessarily
0486   /// indicate an error condition, the diagnostics should be queried
0487   /// to determine if an error occurred.
0488   Compilation *BuildCompilation(ArrayRef<const char *> Args);
0489 
0490   /// ParseArgStrings - Parse the given list of strings into an
0491   /// ArgList.
0492   llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
0493                                           bool UseDriverMode,
0494                                           bool &ContainsError) const;
0495 
0496   /// BuildInputs - Construct the list of inputs and their types from
0497   /// the given arguments.
0498   ///
0499   /// \param TC - The default host tool chain.
0500   /// \param Args - The input arguments.
0501   /// \param Inputs - The list to store the resulting compilation
0502   /// inputs onto.
0503   void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
0504                    InputList &Inputs) const;
0505 
0506   /// BuildActions - Construct the list of actions to perform for the
0507   /// given arguments, which are only done for a single architecture.
0508   ///
0509   /// \param C - The compilation that is being built.
0510   /// \param Args - The input arguments.
0511   /// \param Actions - The list to store the resulting actions onto.
0512   void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
0513                     const InputList &Inputs, ActionList &Actions) const;
0514 
0515   /// BuildUniversalActions - Construct the list of actions to perform
0516   /// for the given arguments, which may require a universal build.
0517   ///
0518   /// \param C - The compilation that is being built.
0519   /// \param TC - The default host tool chain.
0520   void BuildUniversalActions(Compilation &C, const ToolChain &TC,
0521                              const InputList &BAInputs) const;
0522 
0523   /// BuildOffloadingActions - Construct the list of actions to perform for the
0524   /// offloading toolchain that will be embedded in the host.
0525   ///
0526   /// \param C - The compilation that is being built.
0527   /// \param Args - The input arguments.
0528   /// \param Input - The input type and arguments
0529   /// \param CUID - The CUID for \p Input
0530   /// \param HostAction - The host action used in the offloading toolchain.
0531   Action *BuildOffloadingActions(Compilation &C,
0532                                  llvm::opt::DerivedArgList &Args,
0533                                  const InputTy &Input, StringRef CUID,
0534                                  Action *HostAction) const;
0535 
0536   /// Returns the set of bound architectures active for this offload kind.
0537   /// If there are no bound architctures we return a set containing only the
0538   /// empty string. The \p SuppressError option is used to suppress errors.
0539   llvm::DenseSet<StringRef>
0540   getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
0541                   Action::OffloadKind Kind, const ToolChain *TC,
0542                   bool SuppressError = false) const;
0543 
0544   /// Check that the file referenced by Value exists. If it doesn't,
0545   /// issue a diagnostic and return false.
0546   /// If TypoCorrect is true and the file does not exist, see if it looks
0547   /// like a likely typo for a flag and if so print a "did you mean" blurb.
0548   bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args,
0549                               StringRef Value, types::ID Ty,
0550                               bool TypoCorrect) const;
0551 
0552   /// BuildJobs - Bind actions to concrete tools and translate
0553   /// arguments to form the list of jobs to run.
0554   ///
0555   /// \param C - The compilation that is being built.
0556   void BuildJobs(Compilation &C) const;
0557 
0558   /// ExecuteCompilation - Execute the compilation according to the command line
0559   /// arguments and return an appropriate exit code.
0560   ///
0561   /// This routine handles additional processing that must be done in addition
0562   /// to just running the subprocesses, for example reporting errors, setting
0563   /// up response files, removing temporary files, etc.
0564   int ExecuteCompilation(Compilation &C,
0565      SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
0566 
0567   /// Contains the files in the compilation diagnostic report generated by
0568   /// generateCompilationDiagnostics.
0569   struct CompilationDiagnosticReport {
0570     llvm::SmallVector<std::string, 4> TemporaryFiles;
0571   };
0572 
0573   /// generateCompilationDiagnostics - Generate diagnostics information
0574   /// including preprocessed source file(s).
0575   ///
0576   void generateCompilationDiagnostics(
0577       Compilation &C, const Command &FailingCommand,
0578       StringRef AdditionalInformation = "",
0579       CompilationDiagnosticReport *GeneratedReport = nullptr);
0580 
0581   enum class CommandStatus {
0582     Crash = 1,
0583     Error,
0584     Ok,
0585   };
0586 
0587   enum class ReproLevel {
0588     Off = 0,
0589     OnCrash = static_cast<int>(CommandStatus::Crash),
0590     OnError = static_cast<int>(CommandStatus::Error),
0591     Always = static_cast<int>(CommandStatus::Ok),
0592   };
0593 
0594   bool maybeGenerateCompilationDiagnostics(
0595       CommandStatus CS, ReproLevel Level, Compilation &C,
0596       const Command &FailingCommand, StringRef AdditionalInformation = "",
0597       CompilationDiagnosticReport *GeneratedReport = nullptr) {
0598     if (static_cast<int>(CS) > static_cast<int>(Level))
0599       return false;
0600     if (CS != CommandStatus::Crash)
0601       Diags.Report(diag::err_drv_force_crash)
0602           << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
0603     // Hack to ensure that diagnostic notes get emitted.
0604     Diags.setLastDiagnosticIgnored(false);
0605     generateCompilationDiagnostics(C, FailingCommand, AdditionalInformation,
0606                                    GeneratedReport);
0607     return true;
0608   }
0609 
0610   /// @}
0611   /// @name Helper Methods
0612   /// @{
0613 
0614   /// PrintActions - Print the list of actions.
0615   void PrintActions(const Compilation &C) const;
0616 
0617   /// PrintHelp - Print the help text.
0618   ///
0619   /// \param ShowHidden - Show hidden options.
0620   void PrintHelp(bool ShowHidden) const;
0621 
0622   /// PrintVersion - Print the driver version.
0623   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
0624 
0625   /// GetFilePath - Lookup \p Name in the list of file search paths.
0626   ///
0627   /// \param TC - The tool chain for additional information on
0628   /// directories to search.
0629   //
0630   // FIXME: This should be in CompilationInfo.
0631   std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
0632 
0633   /// GetProgramPath - Lookup \p Name in the list of program search paths.
0634   ///
0635   /// \param TC - The provided tool chain for additional information on
0636   /// directories to search.
0637   //
0638   // FIXME: This should be in CompilationInfo.
0639   std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
0640 
0641   /// Lookup the path to the Standard library module manifest.
0642   ///
0643   /// \param C - The compilation.
0644   /// \param TC - The tool chain for additional information on
0645   /// directories to search.
0646   //
0647   // FIXME: This should be in CompilationInfo.
0648   std::string GetStdModuleManifestPath(const Compilation &C,
0649                                        const ToolChain &TC) const;
0650 
0651   /// HandleAutocompletions - Handle --autocomplete by searching and printing
0652   /// possible flags, descriptions, and its arguments.
0653   void HandleAutocompletions(StringRef PassedFlags) const;
0654 
0655   /// HandleImmediateArgs - Handle any arguments which should be
0656   /// treated before building actions or binding tools.
0657   ///
0658   /// \return Whether any compilation should be built for this
0659   /// invocation. The compilation can only be modified when
0660   /// this function returns false.
0661   bool HandleImmediateArgs(Compilation &C);
0662 
0663   /// ConstructAction - Construct the appropriate action to do for
0664   /// \p Phase on the \p Input, taking in to account arguments
0665   /// like -fsyntax-only or --analyze.
0666   Action *ConstructPhaseAction(
0667       Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase,
0668       Action *Input,
0669       Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
0670 
0671   /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
0672   /// return an InputInfo for the result of running \p A.  Will only construct
0673   /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
0674   InputInfoList BuildJobsForAction(
0675       Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
0676       bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
0677       std::map<std::pair<const Action *, std::string>, InputInfoList>
0678           &CachedResults,
0679       Action::OffloadKind TargetDeviceOffloadKind) const;
0680 
0681   /// Returns the default name for linked images (e.g., "a.out").
0682   const char *getDefaultImageName() const;
0683 
0684   /// Creates a temp file.
0685   /// 1. If \p MultipleArch is false or \p BoundArch is empty, the temp file is
0686   ///    in the temporary directory with name $Prefix-%%%%%%.$Suffix.
0687   /// 2. If \p MultipleArch is true and \p BoundArch is not empty,
0688   ///    2a. If \p NeedUniqueDirectory is false, the temp file is in the
0689   ///        temporary directory with name $Prefix-$BoundArch-%%%%%.$Suffix.
0690   ///    2b. If \p NeedUniqueDirectory is true, the temp file is in a unique
0691   ///        subdiretory with random name under the temporary directory, and
0692   ///        the temp file itself has name $Prefix-$BoundArch.$Suffix.
0693   const char *CreateTempFile(Compilation &C, StringRef Prefix, StringRef Suffix,
0694                              bool MultipleArchs = false,
0695                              StringRef BoundArch = {},
0696                              bool NeedUniqueDirectory = false) const;
0697 
0698   /// GetNamedOutputPath - Return the name to use for the output of
0699   /// the action \p JA. The result is appended to the compilation's
0700   /// list of temporary or result files, as appropriate.
0701   ///
0702   /// \param C - The compilation.
0703   /// \param JA - The action of interest.
0704   /// \param BaseInput - The original input file that this action was
0705   /// triggered by.
0706   /// \param BoundArch - The bound architecture.
0707   /// \param AtTopLevel - Whether this is a "top-level" action.
0708   /// \param MultipleArchs - Whether multiple -arch options were supplied.
0709   /// \param NormalizedTriple - The normalized triple of the relevant target.
0710   const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
0711                                  const char *BaseInput, StringRef BoundArch,
0712                                  bool AtTopLevel, bool MultipleArchs,
0713                                  StringRef NormalizedTriple) const;
0714 
0715   /// GetTemporaryPath - Return the pathname of a temporary file to use
0716   /// as part of compilation; the file will have the given prefix and suffix.
0717   ///
0718   /// GCC goes to extra lengths here to be a bit more robust.
0719   std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
0720 
0721   /// GetTemporaryDirectory - Return the pathname of a temporary directory to
0722   /// use as part of compilation; the directory will have the given prefix.
0723   std::string GetTemporaryDirectory(StringRef Prefix) const;
0724 
0725   /// Return the pathname of the pch file in clang-cl mode.
0726   std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
0727 
0728   /// ShouldUseClangCompiler - Should the clang compiler be used to
0729   /// handle this action.
0730   bool ShouldUseClangCompiler(const JobAction &JA) const;
0731 
0732   /// ShouldUseFlangCompiler - Should the flang compiler be used to
0733   /// handle this action.
0734   bool ShouldUseFlangCompiler(const JobAction &JA) const;
0735 
0736   /// ShouldEmitStaticLibrary - Should the linker emit a static library.
0737   bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const;
0738 
0739   /// Returns true if the user has indicated a C++20 header unit mode.
0740   bool hasHeaderMode() const { return CXX20HeaderType != HeaderMode_None; }
0741 
0742   /// Get the mode for handling headers as set by fmodule-header{=}.
0743   ModuleHeaderMode getModuleHeaderMode() const { return CXX20HeaderType; }
0744 
0745   /// Returns true if we are performing any kind of LTO.
0746   bool isUsingLTO() const { return getLTOMode() != LTOK_None; }
0747 
0748   /// Get the specific kind of LTO being performed.
0749   LTOKind getLTOMode() const { return LTOMode; }
0750 
0751   /// Returns true if we are performing any kind of offload LTO.
0752   bool isUsingOffloadLTO() const { return getOffloadLTOMode() != LTOK_None; }
0753 
0754   /// Get the specific kind of offload LTO being performed.
0755   LTOKind getOffloadLTOMode() const { return OffloadLTOMode; }
0756 
0757   /// Get the CUID option.
0758   const CUIDOptions &getCUIDOpts() const { return CUIDOpts; }
0759 
0760 private:
0761 
0762   /// Tries to load options from configuration files.
0763   ///
0764   /// \returns true if error occurred.
0765   bool loadConfigFiles();
0766 
0767   /// Tries to load options from default configuration files (deduced from
0768   /// executable filename).
0769   ///
0770   /// \returns true if error occurred.
0771   bool loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx);
0772 
0773   /// Tries to load options from customization file.
0774   ///
0775   /// \returns true if error occurred.
0776   bool loadZOSCustomizationFile(llvm::cl::ExpansionContext &);
0777 
0778   /// Read options from the specified file.
0779   ///
0780   /// \param [in] FileName File to read.
0781   /// \param [in] Search and expansion options.
0782   /// \returns true, if error occurred while reading.
0783   bool readConfigFile(StringRef FileName, llvm::cl::ExpansionContext &ExpCtx);
0784 
0785   /// Set the driver mode (cl, gcc, etc) from the value of the `--driver-mode`
0786   /// option.
0787   void setDriverMode(StringRef DriverModeValue);
0788 
0789   /// Parse the \p Args list for LTO options and record the type of LTO
0790   /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
0791   void setLTOMode(const llvm::opt::ArgList &Args);
0792 
0793   /// Retrieves a ToolChain for a particular \p Target triple.
0794   ///
0795   /// Will cache ToolChains for the life of the driver object, and create them
0796   /// on-demand.
0797   const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
0798                                 const llvm::Triple &Target) const;
0799 
0800   /// @}
0801 
0802   /// Retrieves a ToolChain for a particular device \p Target triple
0803   ///
0804   /// \param[in] HostTC is the host ToolChain paired with the device
0805   ///
0806   /// \param[in] TargetDeviceOffloadKind (e.g. OFK_Cuda/OFK_OpenMP/OFK_SYCL) is
0807   /// an Offloading action that is optionally passed to a ToolChain (used by
0808   /// CUDA, to specify if it's used in conjunction with OpenMP)
0809   ///
0810   /// Will cache ToolChains for the life of the driver object, and create them
0811   /// on-demand.
0812   const ToolChain &getOffloadingDeviceToolChain(
0813       const llvm::opt::ArgList &Args, const llvm::Triple &Target,
0814       const ToolChain &HostTC,
0815       const Action::OffloadKind &TargetDeviceOffloadKind) const;
0816 
0817   /// Get bitmasks for which option flags to include and exclude based on
0818   /// the driver mode.
0819   llvm::opt::Visibility
0820   getOptionVisibilityMask(bool UseDriverMode = true) const;
0821 
0822   /// Helper used in BuildJobsForAction.  Doesn't use the cache when building
0823   /// jobs specifically for the given action, but will use the cache when
0824   /// building jobs for the Action's inputs.
0825   InputInfoList BuildJobsForActionNoCache(
0826       Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
0827       bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
0828       std::map<std::pair<const Action *, std::string>, InputInfoList>
0829           &CachedResults,
0830       Action::OffloadKind TargetDeviceOffloadKind) const;
0831 
0832   /// Return the typical executable name for the specified driver \p Mode.
0833   static const char *getExecutableForDriverMode(DriverMode Mode);
0834 
0835 public:
0836   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
0837   /// return the grouped values as integers. Numbers which are not
0838   /// provided are set to 0.
0839   ///
0840   /// \return True if the entire string was parsed (9.2), or all
0841   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
0842   /// groups were parsed but extra characters remain at the end.
0843   static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
0844                                 unsigned &Micro, bool &HadExtra);
0845 
0846   /// Parse digits from a string \p Str and fulfill \p Digits with
0847   /// the parsed numbers. This method assumes that the max number of
0848   /// digits to look for is equal to Digits.size().
0849   ///
0850   /// \return True if the entire string was parsed and there are
0851   /// no extra characters remaining at the end.
0852   static bool GetReleaseVersion(StringRef Str,
0853                                 MutableArrayRef<unsigned> Digits);
0854   /// Compute the default -fmodule-cache-path.
0855   /// \return True if the system provides a default cache directory.
0856   static bool getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
0857 };
0858 
0859 /// \return True if the last defined optimization level is -Ofast.
0860 /// And False otherwise.
0861 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
0862 
0863 /// \return True if the argument combination will end up generating remarks.
0864 bool willEmitRemarks(const llvm::opt::ArgList &Args);
0865 
0866 /// Returns the driver mode option's value, i.e. `X` in `--driver-mode=X`. If \p
0867 /// Args doesn't mention one explicitly, tries to deduce from `ProgName`.
0868 /// Returns empty on failure.
0869 /// Common values are "gcc", "g++", "cpp", "cl" and "flang". Returned value need
0870 /// not be one of these.
0871 llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef<const char *> Args);
0872 
0873 /// Checks whether the value produced by getDriverMode is for CL mode.
0874 bool IsClangCL(StringRef DriverMode);
0875 
0876 /// Expand response files from a clang driver or cc1 invocation.
0877 ///
0878 /// \param Args The arguments that will be expanded.
0879 /// \param ClangCLMode Whether clang is in CL mode.
0880 /// \param Alloc Allocator for new arguments.
0881 /// \param FS Filesystem to use when expanding files.
0882 llvm::Error expandResponseFiles(SmallVectorImpl<const char *> &Args,
0883                                 bool ClangCLMode, llvm::BumpPtrAllocator &Alloc,
0884                                 llvm::vfs::FileSystem *FS = nullptr);
0885 
0886 /// Apply a space separated list of edits to the input argument lists.
0887 /// See applyOneOverrideOption.
0888 void applyOverrideOptions(SmallVectorImpl<const char *> &Args,
0889                           const char *OverrideOpts,
0890                           llvm::StringSet<> &SavedStrings,
0891                           raw_ostream *OS = nullptr);
0892 
0893 } // end namespace driver
0894 } // end namespace clang
0895 
0896 #endif