1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLVM_CLANG_DRIVER_DRIVER_H 10 #define LLVM_CLANG_DRIVER_DRIVER_H 11 12 #include "clang/Basic/Diagnostic.h" 13 #include "clang/Basic/HeaderInclude.h" 14 #include "clang/Basic/LLVM.h" 15 #include "clang/Driver/Action.h" 16 #include "clang/Driver/DriverDiagnostic.h" 17 #include "clang/Driver/InputInfo.h" 18 #include "clang/Driver/Options.h" 19 #include "clang/Driver/Phases.h" 20 #include "clang/Driver/ToolChain.h" 21 #include "clang/Driver/Types.h" 22 #include "clang/Driver/Util.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/ADT/STLFunctionalExtras.h" 25 #include "llvm/ADT/StringMap.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Option/Arg.h" 28 #include "llvm/Option/ArgList.h" 29 #include "llvm/Support/StringSaver.h" 30 31 #include <map> 32 #include <set> 33 #include <string> 34 #include <vector> 35 36 namespace llvm { 37 class Triple; 38 namespace vfs { 39 class FileSystem; 40 } 41 namespace cl { 42 class ExpansionContext; 43 } 44 } // namespace llvm 45 46 namespace clang { 47 48 namespace driver { 49 50 typedef SmallVector<InputInfo, 4> InputInfoList; 51 52 class Command; 53 class Compilation; 54 class JobAction; 55 class ToolChain; 56 57 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options. 58 enum LTOKind { 59 LTOK_None, 60 LTOK_Full, 61 LTOK_Thin, 62 LTOK_Unknown 63 }; 64 65 /// Whether headers used to construct C++20 module units should be looked 66 /// up by the path supplied on the command line, or in the user or system 67 /// search paths. 68 enum ModuleHeaderMode { 69 HeaderMode_None, 70 HeaderMode_Default, 71 HeaderMode_User, 72 HeaderMode_System 73 }; 74 75 /// Options for specifying CUID used by CUDA/HIP for uniquely identifying 76 /// compilation units. 77 class CUIDOptions { 78 public: 79 enum class Kind { Hash, Random, Fixed, None, Invalid }; 80 81 CUIDOptions() = default; 82 CUIDOptions(llvm::opt::DerivedArgList &Args, const Driver &D); 83 84 // Get the CUID for an input string 85 std::string getCUID(StringRef InputFile, 86 llvm::opt::DerivedArgList &Args) const; 87 isEnabled()88 bool isEnabled() const { 89 return UseCUID != Kind::None && UseCUID != Kind::Invalid; 90 } 91 92 private: 93 Kind UseCUID = Kind::None; 94 StringRef FixedCUID; 95 }; 96 97 /// Driver - Encapsulate logic for constructing compilation processes 98 /// from a set of gcc-driver-like command line arguments. 99 class Driver { 100 DiagnosticsEngine &Diags; 101 102 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS; 103 104 enum DriverMode { 105 GCCMode, 106 GXXMode, 107 CPPMode, 108 CLMode, 109 FlangMode, 110 DXCMode 111 } Mode; 112 113 enum SaveTempsMode { 114 SaveTempsNone, 115 SaveTempsCwd, 116 SaveTempsObj 117 } SaveTemps; 118 119 enum BitcodeEmbedMode { 120 EmbedNone, 121 EmbedMarker, 122 EmbedBitcode 123 } BitcodeEmbed; 124 125 enum OffloadMode { 126 OffloadHostDevice, 127 OffloadHost, 128 OffloadDevice, 129 } Offload; 130 131 /// Header unit mode set by -fmodule-header={user,system}. 132 ModuleHeaderMode CXX20HeaderType; 133 134 /// Set if we should process inputs and jobs with C++20 module 135 /// interpretation. 136 bool ModulesModeCXX20; 137 138 /// LTO mode selected via -f(no-)?lto(=.*)? options. 139 LTOKind LTOMode; 140 141 /// LTO mode selected via -f(no-offload-)?lto(=.*)? options. 142 LTOKind OffloadLTOMode; 143 144 /// Options for CUID 145 CUIDOptions CUIDOpts; 146 147 public: 148 enum OpenMPRuntimeKind { 149 /// An unknown OpenMP runtime. We can't generate effective OpenMP code 150 /// without knowing what runtime to target. 151 OMPRT_Unknown, 152 153 /// The LLVM OpenMP runtime. When completed and integrated, this will become 154 /// the default for Clang. 155 OMPRT_OMP, 156 157 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for 158 /// this runtime but can swallow the pragmas, and find and link against the 159 /// runtime library itself. 160 OMPRT_GOMP, 161 162 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel 163 /// OpenMP runtime. We support this mode for users with existing 164 /// dependencies on this runtime library name. 165 OMPRT_IOMP5 166 }; 167 168 // Diag - Forwarding function for diagnostics. Diag(unsigned DiagID)169 DiagnosticBuilder Diag(unsigned DiagID) const { 170 return Diags.Report(DiagID); 171 } 172 173 // FIXME: Privatize once interface is stable. 174 public: 175 /// The name the driver was invoked as. 176 std::string Name; 177 178 /// The path the driver executable was in, as invoked from the 179 /// command line. 180 std::string Dir; 181 182 /// The original path to the clang executable. 183 std::string ClangExecutable; 184 185 /// Target and driver mode components extracted from clang executable name. 186 ParsedClangName ClangNameParts; 187 188 /// The path to the compiler resource directory. 189 std::string ResourceDir; 190 191 /// System directory for config files. 192 std::string SystemConfigDir; 193 194 /// User directory for config files. 195 std::string UserConfigDir; 196 197 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix' 198 /// functionality. 199 /// FIXME: This type of customization should be removed in favor of the 200 /// universal driver when it is ready. 201 typedef SmallVector<std::string, 4> prefix_list; 202 prefix_list PrefixDirs; 203 204 /// sysroot, if present 205 std::string SysRoot; 206 207 /// Dynamic loader prefix, if present 208 std::string DyldPrefix; 209 210 /// Driver title to use with help. 211 std::string DriverTitle; 212 213 /// Information about the host which can be overridden by the user. 214 std::string HostBits, HostMachine, HostSystem, HostRelease; 215 216 /// The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled. 217 std::string CCPrintStatReportFilename; 218 219 /// The file to log CC_PRINT_INTERNAL_STAT_FILE output to, if enabled. 220 std::string CCPrintInternalStatReportFilename; 221 222 /// The file to log CC_PRINT_OPTIONS output to, if enabled. 223 std::string CCPrintOptionsFilename; 224 225 /// The file to log CC_PRINT_HEADERS output to, if enabled. 226 std::string CCPrintHeadersFilename; 227 228 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled. 229 std::string CCLogDiagnosticsFilename; 230 231 /// An input type and its arguments. 232 using InputTy = std::pair<types::ID, const llvm::opt::Arg *>; 233 234 /// A list of inputs and their types for the given arguments. 235 using InputList = SmallVector<InputTy, 16>; 236 237 /// Whether the driver should follow g++ like behavior. CCCIsCXX()238 bool CCCIsCXX() const { return Mode == GXXMode; } 239 240 /// Whether the driver is just the preprocessor. CCCIsCPP()241 bool CCCIsCPP() const { return Mode == CPPMode; } 242 243 /// Whether the driver should follow gcc like behavior. CCCIsCC()244 bool CCCIsCC() const { return Mode == GCCMode; } 245 246 /// Whether the driver should follow cl.exe like behavior. IsCLMode()247 bool IsCLMode() const { return Mode == CLMode; } 248 249 /// Whether the driver should invoke flang for fortran inputs. 250 /// Other modes fall back to calling gcc which in turn calls gfortran. IsFlangMode()251 bool IsFlangMode() const { return Mode == FlangMode; } 252 253 /// Whether the driver should follow dxc.exe like behavior. IsDXCMode()254 bool IsDXCMode() const { return Mode == DXCMode; } 255 256 /// Only print tool bindings, don't build any jobs. 257 LLVM_PREFERRED_TYPE(bool) 258 unsigned CCCPrintBindings : 1; 259 260 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to 261 /// CCPrintOptionsFilename or to stderr. 262 LLVM_PREFERRED_TYPE(bool) 263 unsigned CCPrintOptions : 1; 264 265 /// The format of the header information that is emitted. If CC_PRINT_HEADERS 266 /// is set, the format is textual. Otherwise, the format is determined by the 267 /// enviroment variable CC_PRINT_HEADERS_FORMAT. 268 HeaderIncludeFormatKind CCPrintHeadersFormat = HIFMT_None; 269 270 /// This flag determines whether clang should filter the header information 271 /// that is emitted. If enviroment variable CC_PRINT_HEADERS_FILTERING is set 272 /// to "only-direct-system", only system headers that are directly included 273 /// from non-system headers are emitted. 274 HeaderIncludeFilteringKind CCPrintHeadersFiltering = HIFIL_None; 275 276 /// Name of the library that provides implementations of 277 /// IEEE-754 128-bit float math functions used by Fortran F128 278 /// runtime library. It should be linked as needed by the linker job. 279 std::string FlangF128MathLibrary; 280 281 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics 282 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable 283 /// format. 284 LLVM_PREFERRED_TYPE(bool) 285 unsigned CCLogDiagnostics : 1; 286 287 /// Whether the driver is generating diagnostics for debugging purposes. 288 LLVM_PREFERRED_TYPE(bool) 289 unsigned CCGenDiagnostics : 1; 290 291 /// Set CC_PRINT_PROC_STAT mode, which causes the driver to dump 292 /// performance report to CC_PRINT_PROC_STAT_FILE or to stdout. 293 LLVM_PREFERRED_TYPE(bool) 294 unsigned CCPrintProcessStats : 1; 295 296 /// Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal 297 /// performance report to CC_PRINT_INTERNAL_STAT_FILE or to stdout. 298 LLVM_PREFERRED_TYPE(bool) 299 unsigned CCPrintInternalStats : 1; 300 301 /// Pointer to the ExecuteCC1Tool function, if available. 302 /// When the clangDriver lib is used through clang.exe, this provides a 303 /// shortcut for executing the -cc1 command-line directly, in the same 304 /// process. 305 using CC1ToolFunc = 306 llvm::function_ref<int(SmallVectorImpl<const char *> &ArgV)>; 307 CC1ToolFunc CC1Main = nullptr; 308 309 private: 310 /// Raw target triple. 311 std::string TargetTriple; 312 313 /// Name to use when invoking gcc/g++. 314 std::string CCCGenericGCCName; 315 316 /// Paths to configuration files used. 317 std::vector<std::string> ConfigFiles; 318 319 /// Allocator for string saver. 320 llvm::BumpPtrAllocator Alloc; 321 322 /// Object that stores strings read from configuration file. 323 llvm::StringSaver Saver; 324 325 /// Arguments originated from configuration file (head part). 326 std::unique_ptr<llvm::opt::InputArgList> CfgOptionsHead; 327 328 /// Arguments originated from configuration file (tail part). 329 std::unique_ptr<llvm::opt::InputArgList> CfgOptionsTail; 330 331 /// Arguments originated from command line. 332 std::unique_ptr<llvm::opt::InputArgList> CLOptions; 333 334 /// If this is non-null, the driver will prepend this argument before 335 /// reinvoking clang. This is useful for the llvm-driver where clang's 336 /// realpath will be to the llvm binary and not clang, so it must pass 337 /// "clang" as it's first argument. 338 const char *PrependArg; 339 340 /// Whether to check that input files exist when constructing compilation 341 /// jobs. 342 LLVM_PREFERRED_TYPE(bool) 343 unsigned CheckInputsExist : 1; 344 /// Whether to probe for PCH files on disk, in order to upgrade 345 /// -include foo.h to -include-pch foo.h.pch. 346 LLVM_PREFERRED_TYPE(bool) 347 unsigned ProbePrecompiled : 1; 348 349 public: 350 // getFinalPhase - Determine which compilation mode we are in and record 351 // which option we used to determine the final phase. 352 // TODO: Much of what getFinalPhase returns are not actually true compiler 353 // modes. Fold this functionality into Types::getCompilationPhases and 354 // handleArguments. 355 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL, 356 llvm::opt::Arg **FinalPhaseArg = nullptr) const; 357 358 private: 359 /// Certain options suppress the 'no input files' warning. 360 LLVM_PREFERRED_TYPE(bool) 361 unsigned SuppressMissingInputWarning : 1; 362 363 /// Cache of all the ToolChains in use by the driver. 364 /// 365 /// This maps from the string representation of a triple to a ToolChain 366 /// created targeting that triple. The driver owns all the ToolChain objects 367 /// stored in it, and will clean them up when torn down. 368 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains; 369 370 /// The associated offloading architectures with each toolchain. 371 llvm::DenseMap<const ToolChain *, llvm::SmallVector<llvm::StringRef>> 372 OffloadArchs; 373 374 private: 375 /// TranslateInputArgs - Create a new derived argument list from the input 376 /// arguments, after applying the standard argument translations. 377 llvm::opt::DerivedArgList * 378 TranslateInputArgs(const llvm::opt::InputArgList &Args) const; 379 380 // handleArguments - All code related to claiming and printing diagnostics 381 // related to arguments to the driver are done here. 382 void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args, 383 const InputList &Inputs, ActionList &Actions) const; 384 385 // Before executing jobs, sets up response files for commands that need them. 386 void setUpResponseFiles(Compilation &C, Command &Cmd); 387 388 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC, 389 SmallVectorImpl<std::string> &Names) const; 390 391 /// Find the appropriate .crash diagonostic file for the child crash 392 /// under this driver and copy it out to a temporary destination with the 393 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a 394 /// directory for the user to look at. 395 /// 396 /// \param ReproCrashFilename The file path to copy the .crash to. 397 /// \param CrashDiagDir The suggested directory for the user to look at 398 /// in case the search or copy fails. 399 /// 400 /// \returns If the .crash is found and successfully copied return true, 401 /// otherwise false and return the suggested directory in \p CrashDiagDir. 402 bool getCrashDiagnosticFile(StringRef ReproCrashFilename, 403 SmallString<128> &CrashDiagDir); 404 405 public: 406 407 /// Takes the path to a binary that's either in bin/ or lib/ and returns 408 /// the path to clang's resource directory. 409 static std::string GetResourcesPath(StringRef BinaryPath); 410 411 Driver(StringRef ClangExecutable, StringRef TargetTriple, 412 DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler", 413 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); 414 415 /// @name Accessors 416 /// @{ 417 418 /// Name to use when invoking gcc/g++. getCCCGenericGCCName()419 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; } 420 getConfigFiles()421 llvm::ArrayRef<std::string> getConfigFiles() const { 422 return ConfigFiles; 423 } 424 getOpts()425 const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); } 426 getDiags()427 DiagnosticsEngine &getDiags() const { return Diags; } 428 getVFS()429 llvm::vfs::FileSystem &getVFS() const { return *VFS; } 430 getCheckInputsExist()431 bool getCheckInputsExist() const { return CheckInputsExist; } 432 setCheckInputsExist(bool Value)433 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; } 434 getProbePrecompiled()435 bool getProbePrecompiled() const { return ProbePrecompiled; } setProbePrecompiled(bool Value)436 void setProbePrecompiled(bool Value) { ProbePrecompiled = Value; } 437 getPrependArg()438 const char *getPrependArg() const { return PrependArg; } setPrependArg(const char * Value)439 void setPrependArg(const char *Value) { PrependArg = Value; } 440 setTargetAndMode(const ParsedClangName & TM)441 void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; } 442 getTitle()443 const std::string &getTitle() { return DriverTitle; } setTitle(std::string Value)444 void setTitle(std::string Value) { DriverTitle = std::move(Value); } 445 getTargetTriple()446 std::string getTargetTriple() const { return TargetTriple; } 447 448 /// Get the path to the main clang executable. getClangProgramPath()449 const char *getClangProgramPath() const { 450 return ClangExecutable.c_str(); 451 } 452 isSaveTempsEnabled()453 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; } isSaveTempsObj()454 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; } 455 embedBitcodeEnabled()456 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; } embedBitcodeInObject()457 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); } embedBitcodeMarkerOnly()458 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); } 459 offloadHostOnly()460 bool offloadHostOnly() const { return Offload == OffloadHost; } offloadDeviceOnly()461 bool offloadDeviceOnly() const { return Offload == OffloadDevice; } 462 setFlangF128MathLibrary(std::string name)463 void setFlangF128MathLibrary(std::string name) { 464 FlangF128MathLibrary = std::move(name); 465 } getFlangF128MathLibrary()466 StringRef getFlangF128MathLibrary() const { return FlangF128MathLibrary; } 467 468 /// Compute the desired OpenMP runtime from the flags provided. 469 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const; 470 471 /// @} 472 /// @name Primary Functionality 473 /// @{ 474 475 /// CreateOffloadingDeviceToolChains - create all the toolchains required to 476 /// support offloading devices given the programming models specified in the 477 /// current compilation. Also, update the host tool chain kind accordingly. 478 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs); 479 480 /// BuildCompilation - Construct a compilation object for a command 481 /// line argument vector. 482 /// 483 /// \return A compilation, or 0 if none was built for the given 484 /// argument vector. A null return value does not necessarily 485 /// indicate an error condition, the diagnostics should be queried 486 /// to determine if an error occurred. 487 Compilation *BuildCompilation(ArrayRef<const char *> Args); 488 489 /// ParseArgStrings - Parse the given list of strings into an 490 /// ArgList. 491 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args, 492 bool UseDriverMode, 493 bool &ContainsError) const; 494 495 /// BuildInputs - Construct the list of inputs and their types from 496 /// the given arguments. 497 /// 498 /// \param TC - The default host tool chain. 499 /// \param Args - The input arguments. 500 /// \param Inputs - The list to store the resulting compilation 501 /// inputs onto. 502 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args, 503 InputList &Inputs) const; 504 505 /// BuildActions - Construct the list of actions to perform for the 506 /// given arguments, which are only done for a single architecture. 507 /// 508 /// \param C - The compilation that is being built. 509 /// \param Args - The input arguments. 510 /// \param Actions - The list to store the resulting actions onto. 511 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args, 512 const InputList &Inputs, ActionList &Actions) const; 513 514 /// BuildUniversalActions - Construct the list of actions to perform 515 /// for the given arguments, which may require a universal build. 516 /// 517 /// \param C - The compilation that is being built. 518 /// \param TC - The default host tool chain. 519 void BuildUniversalActions(Compilation &C, const ToolChain &TC, 520 const InputList &BAInputs) const; 521 522 /// BuildOffloadingActions - Construct the list of actions to perform for the 523 /// offloading toolchain that will be embedded in the host. 524 /// 525 /// \param C - The compilation that is being built. 526 /// \param Args - The input arguments. 527 /// \param Input - The input type and arguments 528 /// \param CUID - The CUID for \p Input 529 /// \param HostAction - The host action used in the offloading toolchain. 530 Action *BuildOffloadingActions(Compilation &C, 531 llvm::opt::DerivedArgList &Args, 532 const InputTy &Input, StringRef CUID, 533 Action *HostAction) const; 534 535 /// Returns the set of bound architectures active for this offload kind. 536 /// If there are no bound architctures we return a set containing only the 537 /// empty string. 538 llvm::SmallVector<StringRef> 539 getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, 540 Action::OffloadKind Kind, const ToolChain *TC, 541 bool SpecificToolchain = true) const; 542 543 /// Check that the file referenced by Value exists. If it doesn't, 544 /// issue a diagnostic and return false. 545 /// If TypoCorrect is true and the file does not exist, see if it looks 546 /// like a likely typo for a flag and if so print a "did you mean" blurb. 547 bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args, 548 StringRef Value, types::ID Ty, 549 bool TypoCorrect) const; 550 551 /// BuildJobs - Bind actions to concrete tools and translate 552 /// arguments to form the list of jobs to run. 553 /// 554 /// \param C - The compilation that is being built. 555 void BuildJobs(Compilation &C) const; 556 557 /// ExecuteCompilation - Execute the compilation according to the command line 558 /// arguments and return an appropriate exit code. 559 /// 560 /// This routine handles additional processing that must be done in addition 561 /// to just running the subprocesses, for example reporting errors, setting 562 /// up response files, removing temporary files, etc. 563 int ExecuteCompilation(Compilation &C, 564 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands); 565 566 /// Contains the files in the compilation diagnostic report generated by 567 /// generateCompilationDiagnostics. 568 struct CompilationDiagnosticReport { 569 llvm::SmallVector<std::string, 4> TemporaryFiles; 570 }; 571 572 /// generateCompilationDiagnostics - Generate diagnostics information 573 /// including preprocessed source file(s). 574 /// 575 void generateCompilationDiagnostics( 576 Compilation &C, const Command &FailingCommand, 577 StringRef AdditionalInformation = "", 578 CompilationDiagnosticReport *GeneratedReport = nullptr); 579 580 enum class CommandStatus { 581 Crash = 1, 582 Error, 583 Ok, 584 }; 585 586 enum class ReproLevel { 587 Off = 0, 588 OnCrash = static_cast<int>(CommandStatus::Crash), 589 OnError = static_cast<int>(CommandStatus::Error), 590 Always = static_cast<int>(CommandStatus::Ok), 591 }; 592 593 bool maybeGenerateCompilationDiagnostics( 594 CommandStatus CS, ReproLevel Level, Compilation &C, 595 const Command &FailingCommand, StringRef AdditionalInformation = "", 596 CompilationDiagnosticReport *GeneratedReport = nullptr) { 597 if (static_cast<int>(CS) > static_cast<int>(Level)) 598 return false; 599 if (CS != CommandStatus::Crash) 600 Diags.Report(diag::err_drv_force_crash) 601 << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"); 602 // Hack to ensure that diagnostic notes get emitted. 603 Diags.setLastDiagnosticIgnored(false); 604 generateCompilationDiagnostics(C, FailingCommand, AdditionalInformation, 605 GeneratedReport); 606 return true; 607 } 608 609 /// @} 610 /// @name Helper Methods 611 /// @{ 612 613 /// PrintActions - Print the list of actions. 614 void PrintActions(const Compilation &C) const; 615 616 /// PrintHelp - Print the help text. 617 /// 618 /// \param ShowHidden - Show hidden options. 619 void PrintHelp(bool ShowHidden) const; 620 621 /// PrintVersion - Print the driver version. 622 void PrintVersion(const Compilation &C, raw_ostream &OS) const; 623 624 /// GetFilePath - Lookup \p Name in the list of file search paths. 625 /// 626 /// \param TC - The tool chain for additional information on 627 /// directories to search. 628 // 629 // FIXME: This should be in CompilationInfo. 630 std::string GetFilePath(StringRef Name, const ToolChain &TC) const; 631 632 /// GetProgramPath - Lookup \p Name in the list of program search paths. 633 /// 634 /// \param TC - The provided tool chain for additional information on 635 /// directories to search. 636 // 637 // FIXME: This should be in CompilationInfo. 638 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const; 639 640 /// Lookup the path to the Standard library module manifest. 641 /// 642 /// \param C - The compilation. 643 /// \param TC - The tool chain for additional information on 644 /// directories to search. 645 // 646 // FIXME: This should be in CompilationInfo. 647 std::string GetStdModuleManifestPath(const Compilation &C, 648 const ToolChain &TC) const; 649 650 /// HandleAutocompletions - Handle --autocomplete by searching and printing 651 /// possible flags, descriptions, and its arguments. 652 void HandleAutocompletions(StringRef PassedFlags) const; 653 654 /// HandleImmediateArgs - Handle any arguments which should be 655 /// treated before building actions or binding tools. 656 /// 657 /// \return Whether any compilation should be built for this 658 /// invocation. The compilation can only be modified when 659 /// this function returns false. 660 bool HandleImmediateArgs(Compilation &C); 661 662 /// ConstructAction - Construct the appropriate action to do for 663 /// \p Phase on the \p Input, taking in to account arguments 664 /// like -fsyntax-only or --analyze. 665 Action *ConstructPhaseAction( 666 Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase, 667 Action *Input, 668 Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const; 669 670 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and 671 /// return an InputInfo for the result of running \p A. Will only construct 672 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once. 673 InputInfoList BuildJobsForAction( 674 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 675 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 676 std::map<std::pair<const Action *, std::string>, InputInfoList> 677 &CachedResults, 678 Action::OffloadKind TargetDeviceOffloadKind) const; 679 680 /// Returns the default name for linked images (e.g., "a.out"). 681 const char *getDefaultImageName() const; 682 683 /// Creates a temp file. 684 /// 1. If \p MultipleArch is false or \p BoundArch is empty, the temp file is 685 /// in the temporary directory with name $Prefix-%%%%%%.$Suffix. 686 /// 2. If \p MultipleArch is true and \p BoundArch is not empty, 687 /// 2a. If \p NeedUniqueDirectory is false, the temp file is in the 688 /// temporary directory with name $Prefix-$BoundArch-%%%%%.$Suffix. 689 /// 2b. If \p NeedUniqueDirectory is true, the temp file is in a unique 690 /// subdiretory with random name under the temporary directory, and 691 /// the temp file itself has name $Prefix-$BoundArch.$Suffix. 692 const char *CreateTempFile(Compilation &C, StringRef Prefix, StringRef Suffix, 693 bool MultipleArchs = false, 694 StringRef BoundArch = {}, 695 bool NeedUniqueDirectory = false) const; 696 697 /// GetNamedOutputPath - Return the name to use for the output of 698 /// the action \p JA. The result is appended to the compilation's 699 /// list of temporary or result files, as appropriate. 700 /// 701 /// \param C - The compilation. 702 /// \param JA - The action of interest. 703 /// \param BaseInput - The original input file that this action was 704 /// triggered by. 705 /// \param BoundArch - The bound architecture. 706 /// \param AtTopLevel - Whether this is a "top-level" action. 707 /// \param MultipleArchs - Whether multiple -arch options were supplied. 708 /// \param NormalizedTriple - The normalized triple of the relevant target. 709 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA, 710 const char *BaseInput, StringRef BoundArch, 711 bool AtTopLevel, bool MultipleArchs, 712 StringRef NormalizedTriple) const; 713 714 /// GetTemporaryPath - Return the pathname of a temporary file to use 715 /// as part of compilation; the file will have the given prefix and suffix. 716 /// 717 /// GCC goes to extra lengths here to be a bit more robust. 718 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const; 719 720 /// GetTemporaryDirectory - Return the pathname of a temporary directory to 721 /// use as part of compilation; the directory will have the given prefix. 722 std::string GetTemporaryDirectory(StringRef Prefix) const; 723 724 /// Return the pathname of the pch file in clang-cl mode. 725 std::string GetClPchPath(Compilation &C, StringRef BaseName) const; 726 727 /// ShouldUseClangCompiler - Should the clang compiler be used to 728 /// handle this action. 729 bool ShouldUseClangCompiler(const JobAction &JA) const; 730 731 /// ShouldUseFlangCompiler - Should the flang compiler be used to 732 /// handle this action. 733 bool ShouldUseFlangCompiler(const JobAction &JA) const; 734 735 /// ShouldEmitStaticLibrary - Should the linker emit a static library. 736 bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const; 737 738 /// Returns true if the user has indicated a C++20 header unit mode. hasHeaderMode()739 bool hasHeaderMode() const { return CXX20HeaderType != HeaderMode_None; } 740 741 /// Get the mode for handling headers as set by fmodule-header{=}. getModuleHeaderMode()742 ModuleHeaderMode getModuleHeaderMode() const { return CXX20HeaderType; } 743 744 /// Returns true if we are performing any kind of LTO. isUsingLTO()745 bool isUsingLTO() const { return getLTOMode() != LTOK_None; } 746 747 /// Get the specific kind of LTO being performed. getLTOMode()748 LTOKind getLTOMode() const { return LTOMode; } 749 750 /// Returns true if we are performing any kind of offload LTO. isUsingOffloadLTO()751 bool isUsingOffloadLTO() const { return getOffloadLTOMode() != LTOK_None; } 752 753 /// Get the specific kind of offload LTO being performed. getOffloadLTOMode()754 LTOKind getOffloadLTOMode() const { return OffloadLTOMode; } 755 756 /// Get the CUID option. getCUIDOpts()757 const CUIDOptions &getCUIDOpts() const { return CUIDOpts; } 758 759 private: 760 761 /// Tries to load options from configuration files. 762 /// 763 /// \returns true if error occurred. 764 bool loadConfigFiles(); 765 766 /// Tries to load options from default configuration files (deduced from 767 /// executable filename). 768 /// 769 /// \returns true if error occurred. 770 bool loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx); 771 772 /// Tries to load options from customization file. 773 /// 774 /// \returns true if error occurred. 775 bool loadZOSCustomizationFile(llvm::cl::ExpansionContext &); 776 777 /// Read options from the specified file. 778 /// 779 /// \param [in] FileName File to read. 780 /// \param [in] Search and expansion options. 781 /// \returns true, if error occurred while reading. 782 bool readConfigFile(StringRef FileName, llvm::cl::ExpansionContext &ExpCtx); 783 784 /// Set the driver mode (cl, gcc, etc) from the value of the `--driver-mode` 785 /// option. 786 void setDriverMode(StringRef DriverModeValue); 787 788 /// Parse the \p Args list for LTO options and record the type of LTO 789 /// compilation based on which -f(no-)?lto(=.*)? option occurs last. 790 void setLTOMode(const llvm::opt::ArgList &Args); 791 792 /// Retrieves a ToolChain for a particular \p Target triple. 793 /// 794 /// Will cache ToolChains for the life of the driver object, and create them 795 /// on-demand. 796 const ToolChain &getToolChain(const llvm::opt::ArgList &Args, 797 const llvm::Triple &Target) const; 798 799 /// Retrieves a ToolChain for a particular \p Target triple for offloading. 800 /// 801 /// Will cache ToolChains for the life of the driver object, and create them 802 /// on-demand. 803 const ToolChain &getOffloadToolChain(const llvm::opt::ArgList &Args, 804 const Action::OffloadKind Kind, 805 const llvm::Triple &Target, 806 const llvm::Triple &AuxTarget) const; 807 808 /// Get bitmasks for which option flags to include and exclude based on 809 /// the driver mode. 810 llvm::opt::Visibility 811 getOptionVisibilityMask(bool UseDriverMode = true) const; 812 813 /// Helper used in BuildJobsForAction. Doesn't use the cache when building 814 /// jobs specifically for the given action, but will use the cache when 815 /// building jobs for the Action's inputs. 816 InputInfoList BuildJobsForActionNoCache( 817 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 818 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 819 std::map<std::pair<const Action *, std::string>, InputInfoList> 820 &CachedResults, 821 Action::OffloadKind TargetDeviceOffloadKind) const; 822 823 /// Return the typical executable name for the specified driver \p Mode. 824 static const char *getExecutableForDriverMode(DriverMode Mode); 825 826 public: 827 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and 828 /// return the grouped values as integers. Numbers which are not 829 /// provided are set to 0. 830 /// 831 /// \return True if the entire string was parsed (9.2), or all 832 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all 833 /// groups were parsed but extra characters remain at the end. 834 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 835 unsigned &Micro, bool &HadExtra); 836 837 /// Parse digits from a string \p Str and fulfill \p Digits with 838 /// the parsed numbers. This method assumes that the max number of 839 /// digits to look for is equal to Digits.size(). 840 /// 841 /// \return True if the entire string was parsed and there are 842 /// no extra characters remaining at the end. 843 static bool GetReleaseVersion(StringRef Str, 844 MutableArrayRef<unsigned> Digits); 845 /// Compute the default -fmodule-cache-path. 846 /// \return True if the system provides a default cache directory. 847 static bool getDefaultModuleCachePath(SmallVectorImpl<char> &Result); 848 }; 849 850 /// \return True if the last defined optimization level is -Ofast. 851 /// And False otherwise. 852 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args); 853 854 /// \return True if the argument combination will end up generating remarks. 855 bool willEmitRemarks(const llvm::opt::ArgList &Args); 856 857 /// Returns the driver mode option's value, i.e. `X` in `--driver-mode=X`. If \p 858 /// Args doesn't mention one explicitly, tries to deduce from `ProgName`. 859 /// Returns empty on failure. 860 /// Common values are "gcc", "g++", "cpp", "cl" and "flang". Returned value need 861 /// not be one of these. 862 llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef<const char *> Args); 863 864 /// Checks whether the value produced by getDriverMode is for CL mode. 865 bool IsClangCL(StringRef DriverMode); 866 867 /// Expand response files from a clang driver or cc1 invocation. 868 /// 869 /// \param Args The arguments that will be expanded. 870 /// \param ClangCLMode Whether clang is in CL mode. 871 /// \param Alloc Allocator for new arguments. 872 /// \param FS Filesystem to use when expanding files. 873 llvm::Error expandResponseFiles(SmallVectorImpl<const char *> &Args, 874 bool ClangCLMode, llvm::BumpPtrAllocator &Alloc, 875 llvm::vfs::FileSystem *FS = nullptr); 876 877 /// Apply a space separated list of edits to the input argument lists. 878 /// See applyOneOverrideOption. 879 void applyOverrideOptions(SmallVectorImpl<const char *> &Args, 880 const char *OverrideOpts, 881 llvm::StringSet<> &SavedStrings, StringRef EnvVar, 882 raw_ostream *OS = nullptr); 883 884 } // end namespace driver 885 } // end namespace clang 886 887 #endif 888