Driver.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_DRIVER_DRIVER_H
  14. #define LLVM_CLANG_DRIVER_DRIVER_H
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/LLVM.h"
  17. #include "clang/Driver/Action.h"
  18. #include "clang/Driver/InputInfo.h"
  19. #include "clang/Driver/Options.h"
  20. #include "clang/Driver/Phases.h"
  21. #include "clang/Driver/ToolChain.h"
  22. #include "clang/Driver/Types.h"
  23. #include "clang/Driver/Util.h"
  24. #include "llvm/ADT/StringMap.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/Option/Arg.h"
  27. #include "llvm/Option/ArgList.h"
  28. #include "llvm/Support/StringSaver.h"
  29. #include <list>
  30. #include <map>
  31. #include <string>
  32. namespace llvm {
  33. class Triple;
  34. namespace vfs {
  35. class FileSystem;
  36. }
  37. } // namespace llvm
  38. namespace clang {
  39. namespace driver {
  40. typedef SmallVector<InputInfo, 4> InputInfoList;
  41. class Command;
  42. class Compilation;
  43. class JobList;
  44. class JobAction;
  45. class SanitizerArgs;
  46. class ToolChain;
  47. /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
  48. enum LTOKind {
  49. LTOK_None,
  50. LTOK_Full,
  51. LTOK_Thin,
  52. LTOK_Unknown
  53. };
  54. /// Driver - Encapsulate logic for constructing compilation processes
  55. /// from a set of gcc-driver-like command line arguments.
  56. class Driver {
  57. DiagnosticsEngine &Diags;
  58. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
  59. enum DriverMode {
  60. GCCMode,
  61. GXXMode,
  62. CPPMode,
  63. CLMode,
  64. FlangMode
  65. } Mode;
  66. enum SaveTempsMode {
  67. SaveTempsNone,
  68. SaveTempsCwd,
  69. SaveTempsObj
  70. } SaveTemps;
  71. enum BitcodeEmbedMode {
  72. EmbedNone,
  73. EmbedMarker,
  74. EmbedBitcode
  75. } BitcodeEmbed;
  76. /// LTO mode selected via -f(no-)?lto(=.*)? options.
  77. LTOKind LTOMode;
  78. /// LTO mode selected via -f(no-offload-)?lto(=.*)? options.
  79. LTOKind OffloadLTOMode;
  80. public:
  81. enum OpenMPRuntimeKind {
  82. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  83. /// without knowing what runtime to target.
  84. OMPRT_Unknown,
  85. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  86. /// the default for Clang.
  87. OMPRT_OMP,
  88. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  89. /// this runtime but can swallow the pragmas, and find and link against the
  90. /// runtime library itself.
  91. OMPRT_GOMP,
  92. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  93. /// OpenMP runtime. We support this mode for users with existing
  94. /// dependencies on this runtime library name.
  95. OMPRT_IOMP5
  96. };
  97. // Diag - Forwarding function for diagnostics.
  98. DiagnosticBuilder Diag(unsigned DiagID) const {
  99. return Diags.Report(DiagID);
  100. }
  101. // FIXME: Privatize once interface is stable.
  102. public:
  103. /// The name the driver was invoked as.
  104. std::string Name;
  105. /// The path the driver executable was in, as invoked from the
  106. /// command line.
  107. std::string Dir;
  108. /// The original path to the clang executable.
  109. std::string ClangExecutable;
  110. /// Target and driver mode components extracted from clang executable name.
  111. ParsedClangName ClangNameParts;
  112. /// The path to the installed clang directory, if any.
  113. std::string InstalledDir;
  114. /// The path to the compiler resource directory.
  115. std::string ResourceDir;
  116. /// System directory for config files.
  117. std::string SystemConfigDir;
  118. /// User directory for config files.
  119. std::string UserConfigDir;
  120. /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
  121. /// functionality.
  122. /// FIXME: This type of customization should be removed in favor of the
  123. /// universal driver when it is ready.
  124. typedef SmallVector<std::string, 4> prefix_list;
  125. prefix_list PrefixDirs;
  126. /// sysroot, if present
  127. std::string SysRoot;
  128. /// Dynamic loader prefix, if present
  129. std::string DyldPrefix;
  130. /// Driver title to use with help.
  131. std::string DriverTitle;
  132. /// Information about the host which can be overridden by the user.
  133. std::string HostBits, HostMachine, HostSystem, HostRelease;
  134. /// The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled.
  135. std::string CCPrintStatReportFilename;
  136. /// The file to log CC_PRINT_OPTIONS output to, if enabled.
  137. std::string CCPrintOptionsFilename;
  138. /// The file to log CC_PRINT_HEADERS output to, if enabled.
  139. std::string CCPrintHeadersFilename;
  140. /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
  141. std::string CCLogDiagnosticsFilename;
  142. /// An input type and its arguments.
  143. using InputTy = std::pair<types::ID, const llvm::opt::Arg *>;
  144. /// A list of inputs and their types for the given arguments.
  145. using InputList = SmallVector<InputTy, 16>;
  146. /// Whether the driver should follow g++ like behavior.
  147. bool CCCIsCXX() const { return Mode == GXXMode; }
  148. /// Whether the driver is just the preprocessor.
  149. bool CCCIsCPP() const { return Mode == CPPMode; }
  150. /// Whether the driver should follow gcc like behavior.
  151. bool CCCIsCC() const { return Mode == GCCMode; }
  152. /// Whether the driver should follow cl.exe like behavior.
  153. bool IsCLMode() const { return Mode == CLMode; }
  154. /// Whether the driver should invoke flang for fortran inputs.
  155. /// Other modes fall back to calling gcc which in turn calls gfortran.
  156. bool IsFlangMode() const { return Mode == FlangMode; }
  157. /// Only print tool bindings, don't build any jobs.
  158. unsigned CCCPrintBindings : 1;
  159. /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
  160. /// CCPrintOptionsFilename or to stderr.
  161. unsigned CCPrintOptions : 1;
  162. /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
  163. /// information to CCPrintHeadersFilename or to stderr.
  164. unsigned CCPrintHeaders : 1;
  165. /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
  166. /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
  167. /// format.
  168. unsigned CCLogDiagnostics : 1;
  169. /// Whether the driver is generating diagnostics for debugging purposes.
  170. unsigned CCGenDiagnostics : 1;
  171. /// Set CC_PRINT_PROC_STAT mode, which causes the driver to dump
  172. /// performance report to CC_PRINT_PROC_STAT_FILE or to stdout.
  173. unsigned CCPrintProcessStats : 1;
  174. /// Pointer to the ExecuteCC1Tool function, if available.
  175. /// When the clangDriver lib is used through clang.exe, this provides a
  176. /// shortcut for executing the -cc1 command-line directly, in the same
  177. /// process.
  178. typedef int (*CC1ToolFunc)(SmallVectorImpl<const char *> &ArgV);
  179. CC1ToolFunc CC1Main = nullptr;
  180. private:
  181. /// Raw target triple.
  182. std::string TargetTriple;
  183. /// Name to use when invoking gcc/g++.
  184. std::string CCCGenericGCCName;
  185. /// Name of configuration file if used.
  186. std::string ConfigFile;
  187. /// Allocator for string saver.
  188. llvm::BumpPtrAllocator Alloc;
  189. /// Object that stores strings read from configuration file.
  190. llvm::StringSaver Saver;
  191. /// Arguments originated from configuration file.
  192. std::unique_ptr<llvm::opt::InputArgList> CfgOptions;
  193. /// Arguments originated from command line.
  194. std::unique_ptr<llvm::opt::InputArgList> CLOptions;
  195. /// Whether to check that input files exist when constructing compilation
  196. /// jobs.
  197. unsigned CheckInputsExist : 1;
  198. public:
  199. /// Force clang to emit reproducer for driver invocation. This is enabled
  200. /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
  201. /// or when using the -gen-reproducer driver flag.
  202. unsigned GenReproducer : 1;
  203. // getFinalPhase - Determine which compilation mode we are in and record
  204. // which option we used to determine the final phase.
  205. // TODO: Much of what getFinalPhase returns are not actually true compiler
  206. // modes. Fold this functionality into Types::getCompilationPhases and
  207. // handleArguments.
  208. phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
  209. llvm::opt::Arg **FinalPhaseArg = nullptr) const;
  210. private:
  211. /// Certain options suppress the 'no input files' warning.
  212. unsigned SuppressMissingInputWarning : 1;
  213. /// Cache of all the ToolChains in use by the driver.
  214. ///
  215. /// This maps from the string representation of a triple to a ToolChain
  216. /// created targeting that triple. The driver owns all the ToolChain objects
  217. /// stored in it, and will clean them up when torn down.
  218. mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
  219. private:
  220. /// TranslateInputArgs - Create a new derived argument list from the input
  221. /// arguments, after applying the standard argument translations.
  222. llvm::opt::DerivedArgList *
  223. TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
  224. // handleArguments - All code related to claiming and printing diagnostics
  225. // related to arguments to the driver are done here.
  226. void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args,
  227. const InputList &Inputs, ActionList &Actions) const;
  228. // Before executing jobs, sets up response files for commands that need them.
  229. void setUpResponseFiles(Compilation &C, Command &Cmd);
  230. void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
  231. SmallVectorImpl<std::string> &Names) const;
  232. /// Find the appropriate .crash diagonostic file for the child crash
  233. /// under this driver and copy it out to a temporary destination with the
  234. /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
  235. /// directory for the user to look at.
  236. ///
  237. /// \param ReproCrashFilename The file path to copy the .crash to.
  238. /// \param CrashDiagDir The suggested directory for the user to look at
  239. /// in case the search or copy fails.
  240. ///
  241. /// \returns If the .crash is found and successfully copied return true,
  242. /// otherwise false and return the suggested directory in \p CrashDiagDir.
  243. bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
  244. SmallString<128> &CrashDiagDir);
  245. public:
  246. /// Takes the path to a binary that's either in bin/ or lib/ and returns
  247. /// the path to clang's resource directory.
  248. static std::string GetResourcesPath(StringRef BinaryPath,
  249. StringRef CustomResourceDir = "");
  250. Driver(StringRef ClangExecutable, StringRef TargetTriple,
  251. DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler",
  252. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
  253. /// @name Accessors
  254. /// @{
  255. /// Name to use when invoking gcc/g++.
  256. const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
  257. const std::string &getConfigFile() const { return ConfigFile; }
  258. const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
  259. DiagnosticsEngine &getDiags() const { return Diags; }
  260. llvm::vfs::FileSystem &getVFS() const { return *VFS; }
  261. bool getCheckInputsExist() const { return CheckInputsExist; }
  262. void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
  263. void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
  264. const std::string &getTitle() { return DriverTitle; }
  265. void setTitle(std::string Value) { DriverTitle = std::move(Value); }
  266. std::string getTargetTriple() const { return TargetTriple; }
  267. /// Get the path to the main clang executable.
  268. const char *getClangProgramPath() const {
  269. return ClangExecutable.c_str();
  270. }
  271. /// Get the path to where the clang executable was installed.
  272. const char *getInstalledDir() const {
  273. if (!InstalledDir.empty())
  274. return InstalledDir.c_str();
  275. return Dir.c_str();
  276. }
  277. void setInstalledDir(StringRef Value) { InstalledDir = std::string(Value); }
  278. bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
  279. bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
  280. bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
  281. bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
  282. bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
  283. /// Compute the desired OpenMP runtime from the flags provided.
  284. OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
  285. /// @}
  286. /// @name Primary Functionality
  287. /// @{
  288. /// CreateOffloadingDeviceToolChains - create all the toolchains required to
  289. /// support offloading devices given the programming models specified in the
  290. /// current compilation. Also, update the host tool chain kind accordingly.
  291. void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
  292. /// BuildCompilation - Construct a compilation object for a command
  293. /// line argument vector.
  294. ///
  295. /// \return A compilation, or 0 if none was built for the given
  296. /// argument vector. A null return value does not necessarily
  297. /// indicate an error condition, the diagnostics should be queried
  298. /// to determine if an error occurred.
  299. Compilation *BuildCompilation(ArrayRef<const char *> Args);
  300. /// ParseArgStrings - Parse the given list of strings into an
  301. /// ArgList.
  302. llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
  303. bool IsClCompatMode,
  304. bool &ContainsError);
  305. /// BuildInputs - Construct the list of inputs and their types from
  306. /// the given arguments.
  307. ///
  308. /// \param TC - The default host tool chain.
  309. /// \param Args - The input arguments.
  310. /// \param Inputs - The list to store the resulting compilation
  311. /// inputs onto.
  312. void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
  313. InputList &Inputs) const;
  314. /// BuildActions - Construct the list of actions to perform for the
  315. /// given arguments, which are only done for a single architecture.
  316. ///
  317. /// \param C - The compilation that is being built.
  318. /// \param Args - The input arguments.
  319. /// \param Actions - The list to store the resulting actions onto.
  320. void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
  321. const InputList &Inputs, ActionList &Actions) const;
  322. /// BuildUniversalActions - Construct the list of actions to perform
  323. /// for the given arguments, which may require a universal build.
  324. ///
  325. /// \param C - The compilation that is being built.
  326. /// \param TC - The default host tool chain.
  327. void BuildUniversalActions(Compilation &C, const ToolChain &TC,
  328. const InputList &BAInputs) const;
  329. /// BuildOffloadingActions - Construct the list of actions to perform for the
  330. /// offloading toolchain that will be embedded in the host.
  331. ///
  332. /// \param C - The compilation that is being built.
  333. /// \param Args - The input arguments.
  334. /// \param Input - The input type and arguments
  335. /// \param HostAction - The host action used in the offloading toolchain.
  336. Action *BuildOffloadingActions(Compilation &C,
  337. llvm::opt::DerivedArgList &Args,
  338. const InputTy &Input,
  339. Action *HostAction) const;
  340. /// Check that the file referenced by Value exists. If it doesn't,
  341. /// issue a diagnostic and return false.
  342. /// If TypoCorrect is true and the file does not exist, see if it looks
  343. /// like a likely typo for a flag and if so print a "did you mean" blurb.
  344. bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args,
  345. StringRef Value, types::ID Ty,
  346. bool TypoCorrect) const;
  347. /// BuildJobs - Bind actions to concrete tools and translate
  348. /// arguments to form the list of jobs to run.
  349. ///
  350. /// \param C - The compilation that is being built.
  351. void BuildJobs(Compilation &C) const;
  352. /// ExecuteCompilation - Execute the compilation according to the command line
  353. /// arguments and return an appropriate exit code.
  354. ///
  355. /// This routine handles additional processing that must be done in addition
  356. /// to just running the subprocesses, for example reporting errors, setting
  357. /// up response files, removing temporary files, etc.
  358. int ExecuteCompilation(Compilation &C,
  359. SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
  360. /// Contains the files in the compilation diagnostic report generated by
  361. /// generateCompilationDiagnostics.
  362. struct CompilationDiagnosticReport {
  363. llvm::SmallVector<std::string, 4> TemporaryFiles;
  364. };
  365. /// generateCompilationDiagnostics - Generate diagnostics information
  366. /// including preprocessed source file(s).
  367. ///
  368. void generateCompilationDiagnostics(
  369. Compilation &C, const Command &FailingCommand,
  370. StringRef AdditionalInformation = "",
  371. CompilationDiagnosticReport *GeneratedReport = nullptr);
  372. /// @}
  373. /// @name Helper Methods
  374. /// @{
  375. /// PrintActions - Print the list of actions.
  376. void PrintActions(const Compilation &C) const;
  377. /// PrintHelp - Print the help text.
  378. ///
  379. /// \param ShowHidden - Show hidden options.
  380. void PrintHelp(bool ShowHidden) const;
  381. /// PrintVersion - Print the driver version.
  382. void PrintVersion(const Compilation &C, raw_ostream &OS) const;
  383. /// GetFilePath - Lookup \p Name in the list of file search paths.
  384. ///
  385. /// \param TC - The tool chain for additional information on
  386. /// directories to search.
  387. //
  388. // FIXME: This should be in CompilationInfo.
  389. std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
  390. /// GetProgramPath - Lookup \p Name in the list of program search paths.
  391. ///
  392. /// \param TC - The provided tool chain for additional information on
  393. /// directories to search.
  394. //
  395. // FIXME: This should be in CompilationInfo.
  396. std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
  397. /// HandleAutocompletions - Handle --autocomplete by searching and printing
  398. /// possible flags, descriptions, and its arguments.
  399. void HandleAutocompletions(StringRef PassedFlags) const;
  400. /// HandleImmediateArgs - Handle any arguments which should be
  401. /// treated before building actions or binding tools.
  402. ///
  403. /// \return Whether any compilation should be built for this
  404. /// invocation.
  405. bool HandleImmediateArgs(const Compilation &C);
  406. /// ConstructAction - Construct the appropriate action to do for
  407. /// \p Phase on the \p Input, taking in to account arguments
  408. /// like -fsyntax-only or --analyze.
  409. Action *ConstructPhaseAction(
  410. Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase,
  411. Action *Input,
  412. Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
  413. /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
  414. /// return an InputInfo for the result of running \p A. Will only construct
  415. /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
  416. InputInfoList BuildJobsForAction(
  417. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  418. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  419. std::map<std::pair<const Action *, std::string>, InputInfoList>
  420. &CachedResults,
  421. Action::OffloadKind TargetDeviceOffloadKind) const;
  422. /// Returns the default name for linked images (e.g., "a.out").
  423. const char *getDefaultImageName() const;
  424. /// GetNamedOutputPath - Return the name to use for the output of
  425. /// the action \p JA. The result is appended to the compilation's
  426. /// list of temporary or result files, as appropriate.
  427. ///
  428. /// \param C - The compilation.
  429. /// \param JA - The action of interest.
  430. /// \param BaseInput - The original input file that this action was
  431. /// triggered by.
  432. /// \param BoundArch - The bound architecture.
  433. /// \param AtTopLevel - Whether this is a "top-level" action.
  434. /// \param MultipleArchs - Whether multiple -arch options were supplied.
  435. /// \param NormalizedTriple - The normalized triple of the relevant target.
  436. const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
  437. const char *BaseInput, StringRef BoundArch,
  438. bool AtTopLevel, bool MultipleArchs,
  439. StringRef NormalizedTriple) const;
  440. /// GetTemporaryPath - Return the pathname of a temporary file to use
  441. /// as part of compilation; the file will have the given prefix and suffix.
  442. ///
  443. /// GCC goes to extra lengths here to be a bit more robust.
  444. std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
  445. /// GetTemporaryDirectory - Return the pathname of a temporary directory to
  446. /// use as part of compilation; the directory will have the given prefix.
  447. std::string GetTemporaryDirectory(StringRef Prefix) const;
  448. /// Return the pathname of the pch file in clang-cl mode.
  449. std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
  450. /// ShouldUseClangCompiler - Should the clang compiler be used to
  451. /// handle this action.
  452. bool ShouldUseClangCompiler(const JobAction &JA) const;
  453. /// ShouldUseFlangCompiler - Should the flang compiler be used to
  454. /// handle this action.
  455. bool ShouldUseFlangCompiler(const JobAction &JA) const;
  456. /// ShouldEmitStaticLibrary - Should the linker emit a static library.
  457. bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const;
  458. /// Returns true if we are performing any kind of LTO.
  459. bool isUsingLTO(bool IsOffload = false) const {
  460. return getLTOMode(IsOffload) != LTOK_None;
  461. }
  462. /// Get the specific kind of LTO being performed.
  463. LTOKind getLTOMode(bool IsOffload = false) const {
  464. return IsOffload ? OffloadLTOMode : LTOMode;
  465. }
  466. private:
  467. /// Tries to load options from configuration file.
  468. ///
  469. /// \returns true if error occurred.
  470. bool loadConfigFile();
  471. /// Read options from the specified file.
  472. ///
  473. /// \param [in] FileName File to read.
  474. /// \returns true, if error occurred while reading.
  475. bool readConfigFile(StringRef FileName);
  476. /// Set the driver mode (cl, gcc, etc) from the value of the `--driver-mode`
  477. /// option.
  478. void setDriverMode(StringRef DriverModeValue);
  479. /// Parse the \p Args list for LTO options and record the type of LTO
  480. /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
  481. void setLTOMode(const llvm::opt::ArgList &Args);
  482. /// Retrieves a ToolChain for a particular \p Target triple.
  483. ///
  484. /// Will cache ToolChains for the life of the driver object, and create them
  485. /// on-demand.
  486. const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
  487. const llvm::Triple &Target) const;
  488. /// @}
  489. /// Retrieves a ToolChain for a particular device \p Target triple
  490. ///
  491. /// \param[in] HostTC is the host ToolChain paired with the device
  492. ///
  493. /// \param[in] Action (e.g. OFK_Cuda/OFK_OpenMP/OFK_SYCL) is an Offloading
  494. /// action that is optionally passed to a ToolChain (used by CUDA, to specify
  495. /// if it's used in conjunction with OpenMP)
  496. ///
  497. /// Will cache ToolChains for the life of the driver object, and create them
  498. /// on-demand.
  499. const ToolChain &getOffloadingDeviceToolChain(
  500. const llvm::opt::ArgList &Args, const llvm::Triple &Target,
  501. const ToolChain &HostTC,
  502. const Action::OffloadKind &TargetDeviceOffloadKind) const;
  503. /// Get bitmasks for which option flags to include and exclude based on
  504. /// the driver mode.
  505. std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const;
  506. /// Helper used in BuildJobsForAction. Doesn't use the cache when building
  507. /// jobs specifically for the given action, but will use the cache when
  508. /// building jobs for the Action's inputs.
  509. InputInfoList BuildJobsForActionNoCache(
  510. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  511. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  512. std::map<std::pair<const Action *, std::string>, InputInfoList>
  513. &CachedResults,
  514. Action::OffloadKind TargetDeviceOffloadKind) const;
  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. /// Parse digits from a string \p Str and fulfill \p Digits with
  526. /// the parsed numbers. This method assumes that the max number of
  527. /// digits to look for is equal to Digits.size().
  528. ///
  529. /// \return True if the entire string was parsed and there are
  530. /// no extra characters remaining at the end.
  531. static bool GetReleaseVersion(StringRef Str,
  532. MutableArrayRef<unsigned> Digits);
  533. /// Compute the default -fmodule-cache-path.
  534. /// \return True if the system provides a default cache directory.
  535. static bool getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
  536. };
  537. /// \return True if the last defined optimization level is -Ofast.
  538. /// And False otherwise.
  539. bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
  540. /// \return True if the argument combination will end up generating remarks.
  541. bool willEmitRemarks(const llvm::opt::ArgList &Args);
  542. /// Returns the driver mode option's value, i.e. `X` in `--driver-mode=X`. If \p
  543. /// Args doesn't mention one explicitly, tries to deduce from `ProgName`.
  544. /// Returns empty on failure.
  545. /// Common values are "gcc", "g++", "cpp", "cl" and "flang". Returned value need
  546. /// not be one of these.
  547. llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef<const char *> Args);
  548. /// Checks whether the value produced by getDriverMode is for CL mode.
  549. bool IsClangCL(StringRef DriverMode);
  550. } // end namespace driver
  551. } // end namespace clang
  552. #endif
  553. #ifdef __GNUC__
  554. #pragma GCC diagnostic pop
  555. #endif